core.es.js 743 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749
  1. /**
  2. * @license
  3. * Video.js 8.3.0 <http://videojs.com/>
  4. * Copyright Brightcove, Inc. <https://www.brightcove.com/>
  5. * Available under Apache License Version 2.0
  6. * <https://github.com/videojs/video.js/blob/main/LICENSE>
  7. *
  8. * Includes vtt.js <https://github.com/mozilla/vtt.js>
  9. * Available under Apache License Version 2.0
  10. * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
  11. */
  12. import window from 'global/window';
  13. import document from 'global/document';
  14. import keycode from 'keycode';
  15. import safeParseTuple from 'safe-json-parse/tuple';
  16. import XHR from '@videojs/xhr';
  17. import vtt from 'videojs-vtt.js';
  18. var version = "8.3.0";
  19. /**
  20. * An Object that contains lifecycle hooks as keys which point to an array
  21. * of functions that are run when a lifecycle is triggered
  22. *
  23. * @private
  24. */
  25. const hooks_ = {};
  26. /**
  27. * Get a list of hooks for a specific lifecycle
  28. *
  29. * @param {string} type
  30. * the lifecycle to get hooks from
  31. *
  32. * @param {Function|Function[]} [fn]
  33. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  34. *
  35. * @return {Array}
  36. * an array of hooks, or an empty array if there are none.
  37. */
  38. const hooks = function (type, fn) {
  39. hooks_[type] = hooks_[type] || [];
  40. if (fn) {
  41. hooks_[type] = hooks_[type].concat(fn);
  42. }
  43. return hooks_[type];
  44. };
  45. /**
  46. * Add a function hook to a specific videojs lifecycle.
  47. *
  48. * @param {string} type
  49. * the lifecycle to hook the function to.
  50. *
  51. * @param {Function|Function[]}
  52. * The function or array of functions to attach.
  53. */
  54. const hook = function (type, fn) {
  55. hooks(type, fn);
  56. };
  57. /**
  58. * Remove a hook from a specific videojs lifecycle.
  59. *
  60. * @param {string} type
  61. * the lifecycle that the function hooked to
  62. *
  63. * @param {Function} fn
  64. * The hooked function to remove
  65. *
  66. * @return {boolean}
  67. * The function that was removed or undef
  68. */
  69. const removeHook = function (type, fn) {
  70. const index = hooks(type).indexOf(fn);
  71. if (index <= -1) {
  72. return false;
  73. }
  74. hooks_[type] = hooks_[type].slice();
  75. hooks_[type].splice(index, 1);
  76. return true;
  77. };
  78. /**
  79. * Add a function hook that will only run once to a specific videojs lifecycle.
  80. *
  81. * @param {string} type
  82. * the lifecycle to hook the function to.
  83. *
  84. * @param {Function|Function[]}
  85. * The function or array of functions to attach.
  86. */
  87. const hookOnce = function (type, fn) {
  88. hooks(type, [].concat(fn).map(original => {
  89. const wrapper = (...args) => {
  90. removeHook(type, wrapper);
  91. return original(...args);
  92. };
  93. return wrapper;
  94. }));
  95. };
  96. /**
  97. * @file fullscreen-api.js
  98. * @module fullscreen-api
  99. */
  100. /**
  101. * Store the browser-specific methods for the fullscreen API.
  102. *
  103. * @type {Object}
  104. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  105. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  106. */
  107. const FullscreenApi = {
  108. prefixed: true
  109. };
  110. // browser API methods
  111. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  112. // WebKit
  113. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  114. // Mozilla
  115. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  116. // Microsoft
  117. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  118. const specApi = apiMap[0];
  119. let browserApi;
  120. // determine the supported set of functions
  121. for (let i = 0; i < apiMap.length; i++) {
  122. // check for exitFullscreen function
  123. if (apiMap[i][1] in document) {
  124. browserApi = apiMap[i];
  125. break;
  126. }
  127. }
  128. // map the browser API names to the spec API names
  129. if (browserApi) {
  130. for (let i = 0; i < browserApi.length; i++) {
  131. FullscreenApi[specApi[i]] = browserApi[i];
  132. }
  133. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  134. }
  135. /**
  136. * @file create-logger.js
  137. * @module create-logger
  138. */
  139. // This is the private tracking variable for the logging history.
  140. let history = [];
  141. /**
  142. * Log messages to the console and history based on the type of message
  143. *
  144. * @private
  145. * @param {string} type
  146. * The name of the console method to use.
  147. *
  148. * @param {Array} args
  149. * The arguments to be passed to the matching console method.
  150. */
  151. const LogByTypeFactory = (name, log) => (type, level, args) => {
  152. const lvl = log.levels[level];
  153. const lvlRegExp = new RegExp(`^(${lvl})$`);
  154. if (type !== 'log') {
  155. // Add the type to the front of the message when it's not "log".
  156. args.unshift(type.toUpperCase() + ':');
  157. }
  158. // Add console prefix after adding to history.
  159. args.unshift(name + ':');
  160. // Add a clone of the args at this point to history.
  161. if (history) {
  162. history.push([].concat(args));
  163. // only store 1000 history entries
  164. const splice = history.length - 1000;
  165. history.splice(0, splice > 0 ? splice : 0);
  166. }
  167. // If there's no console then don't try to output messages, but they will
  168. // still be stored in history.
  169. if (!window.console) {
  170. return;
  171. }
  172. // Was setting these once outside of this function, but containing them
  173. // in the function makes it easier to test cases where console doesn't exist
  174. // when the module is executed.
  175. let fn = window.console[type];
  176. if (!fn && type === 'debug') {
  177. // Certain browsers don't have support for console.debug. For those, we
  178. // should default to the closest comparable log.
  179. fn = window.console.info || window.console.log;
  180. }
  181. // Bail out if there's no console or if this type is not allowed by the
  182. // current logging level.
  183. if (!fn || !lvl || !lvlRegExp.test(type)) {
  184. return;
  185. }
  186. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  187. };
  188. function createLogger$1(name) {
  189. // This is the private tracking variable for logging level.
  190. let level = 'info';
  191. // the curried logByType bound to the specific log and history
  192. let logByType;
  193. /**
  194. * Logs plain debug messages. Similar to `console.log`.
  195. *
  196. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  197. * of our JSDoc template, we cannot properly document this as both a function
  198. * and a namespace, so its function signature is documented here.
  199. *
  200. * #### Arguments
  201. * ##### *args
  202. * *[]
  203. *
  204. * Any combination of values that could be passed to `console.log()`.
  205. *
  206. * #### Return Value
  207. *
  208. * `undefined`
  209. *
  210. * @namespace
  211. * @param {...*} args
  212. * One or more messages or objects that should be logged.
  213. */
  214. const log = function (...args) {
  215. logByType('log', level, args);
  216. };
  217. // This is the logByType helper that the logging methods below use
  218. logByType = LogByTypeFactory(name, log);
  219. /**
  220. * Create a new sublogger which chains the old name to the new name.
  221. *
  222. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  223. * ```js
  224. * mylogger('foo');
  225. * // > VIDEOJS: player: foo
  226. * ```
  227. *
  228. * @param {string} name
  229. * The name to add call the new logger
  230. * @return {Object}
  231. */
  232. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  233. /**
  234. * Enumeration of available logging levels, where the keys are the level names
  235. * and the values are `|`-separated strings containing logging methods allowed
  236. * in that logging level. These strings are used to create a regular expression
  237. * matching the function name being called.
  238. *
  239. * Levels provided by Video.js are:
  240. *
  241. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  242. * this effect. The most restrictive.
  243. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  244. * `log.warn`, and `log.error`).
  245. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  246. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  247. * - `warn`: Matches `log.warn` and `log.error` calls.
  248. * - `error`: Matches only `log.error` calls.
  249. *
  250. * @type {Object}
  251. */
  252. log.levels = {
  253. all: 'debug|log|warn|error',
  254. off: '',
  255. debug: 'debug|log|warn|error',
  256. info: 'log|warn|error',
  257. warn: 'warn|error',
  258. error: 'error',
  259. DEFAULT: level
  260. };
  261. /**
  262. * Get or set the current logging level.
  263. *
  264. * If a string matching a key from {@link module:log.levels} is provided, acts
  265. * as a setter.
  266. *
  267. * @param {string} [lvl]
  268. * Pass a valid level to set a new logging level.
  269. *
  270. * @return {string}
  271. * The current logging level.
  272. */
  273. log.level = lvl => {
  274. if (typeof lvl === 'string') {
  275. if (!log.levels.hasOwnProperty(lvl)) {
  276. throw new Error(`"${lvl}" in not a valid log level`);
  277. }
  278. level = lvl;
  279. }
  280. return level;
  281. };
  282. /**
  283. * Returns an array containing everything that has been logged to the history.
  284. *
  285. * This array is a shallow clone of the internal history record. However, its
  286. * contents are _not_ cloned; so, mutating objects inside this array will
  287. * mutate them in history.
  288. *
  289. * @return {Array}
  290. */
  291. log.history = () => history ? [].concat(history) : [];
  292. /**
  293. * Allows you to filter the history by the given logger name
  294. *
  295. * @param {string} fname
  296. * The name to filter by
  297. *
  298. * @return {Array}
  299. * The filtered list to return
  300. */
  301. log.history.filter = fname => {
  302. return (history || []).filter(historyItem => {
  303. // if the first item in each historyItem includes `fname`, then it's a match
  304. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  305. });
  306. };
  307. /**
  308. * Clears the internal history tracking, but does not prevent further history
  309. * tracking.
  310. */
  311. log.history.clear = () => {
  312. if (history) {
  313. history.length = 0;
  314. }
  315. };
  316. /**
  317. * Disable history tracking if it is currently enabled.
  318. */
  319. log.history.disable = () => {
  320. if (history !== null) {
  321. history.length = 0;
  322. history = null;
  323. }
  324. };
  325. /**
  326. * Enable history tracking if it is currently disabled.
  327. */
  328. log.history.enable = () => {
  329. if (history === null) {
  330. history = [];
  331. }
  332. };
  333. /**
  334. * Logs error messages. Similar to `console.error`.
  335. *
  336. * @param {...*} args
  337. * One or more messages or objects that should be logged as an error
  338. */
  339. log.error = (...args) => logByType('error', level, args);
  340. /**
  341. * Logs warning messages. Similar to `console.warn`.
  342. *
  343. * @param {...*} args
  344. * One or more messages or objects that should be logged as a warning.
  345. */
  346. log.warn = (...args) => logByType('warn', level, args);
  347. /**
  348. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  349. * log if `console.debug` is not available
  350. *
  351. * @param {...*} args
  352. * One or more messages or objects that should be logged as debug.
  353. */
  354. log.debug = (...args) => logByType('debug', level, args);
  355. return log;
  356. }
  357. /**
  358. * @file log.js
  359. * @module log
  360. */
  361. const log = createLogger$1('VIDEOJS');
  362. const createLogger = log.createLogger;
  363. /**
  364. * @file obj.js
  365. * @module obj
  366. */
  367. /**
  368. * @callback obj:EachCallback
  369. *
  370. * @param {*} value
  371. * The current key for the object that is being iterated over.
  372. *
  373. * @param {string} key
  374. * The current key-value for object that is being iterated over
  375. */
  376. /**
  377. * @callback obj:ReduceCallback
  378. *
  379. * @param {*} accum
  380. * The value that is accumulating over the reduce loop.
  381. *
  382. * @param {*} value
  383. * The current key for the object that is being iterated over.
  384. *
  385. * @param {string} key
  386. * The current key-value for object that is being iterated over
  387. *
  388. * @return {*}
  389. * The new accumulated value.
  390. */
  391. const toString = Object.prototype.toString;
  392. /**
  393. * Get the keys of an Object
  394. *
  395. * @param {Object}
  396. * The Object to get the keys from
  397. *
  398. * @return {string[]}
  399. * An array of the keys from the object. Returns an empty array if the
  400. * object passed in was invalid or had no keys.
  401. *
  402. * @private
  403. */
  404. const keys = function (object) {
  405. return isObject(object) ? Object.keys(object) : [];
  406. };
  407. /**
  408. * Array-like iteration for objects.
  409. *
  410. * @param {Object} object
  411. * The object to iterate over
  412. *
  413. * @param {obj:EachCallback} fn
  414. * The callback function which is called for each key in the object.
  415. */
  416. function each(object, fn) {
  417. keys(object).forEach(key => fn(object[key], key));
  418. }
  419. /**
  420. * Array-like reduce for objects.
  421. *
  422. * @param {Object} object
  423. * The Object that you want to reduce.
  424. *
  425. * @param {Function} fn
  426. * A callback function which is called for each key in the object. It
  427. * receives the accumulated value and the per-iteration value and key
  428. * as arguments.
  429. *
  430. * @param {*} [initial = 0]
  431. * Starting value
  432. *
  433. * @return {*}
  434. * The final accumulated value.
  435. */
  436. function reduce(object, fn, initial = 0) {
  437. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  438. }
  439. /**
  440. * Returns whether a value is an object of any kind - including DOM nodes,
  441. * arrays, regular expressions, etc. Not functions, though.
  442. *
  443. * This avoids the gotcha where using `typeof` on a `null` value
  444. * results in `'object'`.
  445. *
  446. * @param {Object} value
  447. * @return {boolean}
  448. */
  449. function isObject(value) {
  450. return !!value && typeof value === 'object';
  451. }
  452. /**
  453. * Returns whether an object appears to be a "plain" object - that is, a
  454. * direct instance of `Object`.
  455. *
  456. * @param {Object} value
  457. * @return {boolean}
  458. */
  459. function isPlain(value) {
  460. return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;
  461. }
  462. /**
  463. * Merge two objects recursively.
  464. *
  465. * Performs a deep merge like
  466. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  467. * plain objects (not arrays, elements, or anything else).
  468. *
  469. * Non-plain object values will be copied directly from the right-most
  470. * argument.
  471. *
  472. * @param {Object[]} sources
  473. * One or more objects to merge into a new object.
  474. *
  475. * @return {Object}
  476. * A new object that is the merged result of all sources.
  477. */
  478. function merge(...sources) {
  479. const result = {};
  480. sources.forEach(source => {
  481. if (!source) {
  482. return;
  483. }
  484. each(source, (value, key) => {
  485. if (!isPlain(value)) {
  486. result[key] = value;
  487. return;
  488. }
  489. if (!isPlain(result[key])) {
  490. result[key] = {};
  491. }
  492. result[key] = merge(result[key], value);
  493. });
  494. });
  495. return result;
  496. }
  497. /**
  498. * Object.defineProperty but "lazy", which means that the value is only set after
  499. * it is retrieved the first time, rather than being set right away.
  500. *
  501. * @param {Object} obj the object to set the property on
  502. * @param {string} key the key for the property to set
  503. * @param {Function} getValue the function used to get the value when it is needed.
  504. * @param {boolean} setter whether a setter should be allowed or not
  505. */
  506. function defineLazyProperty(obj, key, getValue, setter = true) {
  507. const set = value => Object.defineProperty(obj, key, {
  508. value,
  509. enumerable: true,
  510. writable: true
  511. });
  512. const options = {
  513. configurable: true,
  514. enumerable: true,
  515. get() {
  516. const value = getValue();
  517. set(value);
  518. return value;
  519. }
  520. };
  521. if (setter) {
  522. options.set = set;
  523. }
  524. return Object.defineProperty(obj, key, options);
  525. }
  526. var Obj = /*#__PURE__*/Object.freeze({
  527. __proto__: null,
  528. each: each,
  529. reduce: reduce,
  530. isObject: isObject,
  531. isPlain: isPlain,
  532. merge: merge,
  533. defineLazyProperty: defineLazyProperty
  534. });
  535. /**
  536. * @file browser.js
  537. * @module browser
  538. */
  539. /**
  540. * Whether or not this device is an iPod.
  541. *
  542. * @static
  543. * @type {Boolean}
  544. */
  545. let IS_IPOD = false;
  546. /**
  547. * The detected iOS version - or `null`.
  548. *
  549. * @static
  550. * @type {string|null}
  551. */
  552. let IOS_VERSION = null;
  553. /**
  554. * Whether or not this is an Android device.
  555. *
  556. * @static
  557. * @type {Boolean}
  558. */
  559. let IS_ANDROID = false;
  560. /**
  561. * The detected Android version - or `null` if not Android or indeterminable.
  562. *
  563. * @static
  564. * @type {number|string|null}
  565. */
  566. let ANDROID_VERSION;
  567. /**
  568. * Whether or not this is Mozilla Firefox.
  569. *
  570. * @static
  571. * @type {Boolean}
  572. */
  573. let IS_FIREFOX = false;
  574. /**
  575. * Whether or not this is Microsoft Edge.
  576. *
  577. * @static
  578. * @type {Boolean}
  579. */
  580. let IS_EDGE = false;
  581. /**
  582. * Whether or not this is any Chromium Browser
  583. *
  584. * @static
  585. * @type {Boolean}
  586. */
  587. let IS_CHROMIUM = false;
  588. /**
  589. * Whether or not this is any Chromium browser that is not Edge.
  590. *
  591. * This will also be `true` for Chrome on iOS, which will have different support
  592. * as it is actually Safari under the hood.
  593. *
  594. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  595. * IS_CHROMIUM should be used instead.
  596. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  597. *
  598. * @static
  599. * @deprecated
  600. * @type {Boolean}
  601. */
  602. let IS_CHROME = false;
  603. /**
  604. * The detected Chromium version - or `null`.
  605. *
  606. * @static
  607. * @type {number|null}
  608. */
  609. let CHROMIUM_VERSION = null;
  610. /**
  611. * The detected Google Chrome version - or `null`.
  612. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  613. * Deprecated, use CHROMIUM_VERSION instead.
  614. *
  615. * @static
  616. * @deprecated
  617. * @type {number|null}
  618. */
  619. let CHROME_VERSION = null;
  620. /**
  621. * The detected Internet Explorer version - or `null`.
  622. *
  623. * @static
  624. * @deprecated
  625. * @type {number|null}
  626. */
  627. let IE_VERSION = null;
  628. /**
  629. * Whether or not this is desktop Safari.
  630. *
  631. * @static
  632. * @type {Boolean}
  633. */
  634. let IS_SAFARI = false;
  635. /**
  636. * Whether or not this is a Windows machine.
  637. *
  638. * @static
  639. * @type {Boolean}
  640. */
  641. let IS_WINDOWS = false;
  642. /**
  643. * Whether or not this device is an iPad.
  644. *
  645. * @static
  646. * @type {Boolean}
  647. */
  648. let IS_IPAD = false;
  649. /**
  650. * Whether or not this device is an iPhone.
  651. *
  652. * @static
  653. * @type {Boolean}
  654. */
  655. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  656. // to identify iPhones, we need to exclude iPads.
  657. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  658. let IS_IPHONE = false;
  659. /**
  660. * Whether or not this device is touch-enabled.
  661. *
  662. * @static
  663. * @const
  664. * @type {Boolean}
  665. */
  666. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  667. const UAD = window.navigator && window.navigator.userAgentData;
  668. if (UAD) {
  669. // If userAgentData is present, use it instead of userAgent to avoid warnings
  670. // Currently only implemented on Chromium
  671. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  672. IS_ANDROID = UAD.platform === 'Android';
  673. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  674. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  675. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  676. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  677. IS_WINDOWS = UAD.platform === 'Windows';
  678. }
  679. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  680. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  681. // the checks need to be made agiainst the regular userAgent string.
  682. if (!IS_CHROMIUM) {
  683. const USER_AGENT = window.navigator && window.navigator.userAgent || '';
  684. IS_IPOD = /iPod/i.test(USER_AGENT);
  685. IOS_VERSION = function () {
  686. const match = USER_AGENT.match(/OS (\d+)_/i);
  687. if (match && match[1]) {
  688. return match[1];
  689. }
  690. return null;
  691. }();
  692. IS_ANDROID = /Android/i.test(USER_AGENT);
  693. ANDROID_VERSION = function () {
  694. // This matches Android Major.Minor.Patch versions
  695. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  696. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  697. if (!match) {
  698. return null;
  699. }
  700. const major = match[1] && parseFloat(match[1]);
  701. const minor = match[2] && parseFloat(match[2]);
  702. if (major && minor) {
  703. return parseFloat(match[1] + '.' + match[2]);
  704. } else if (major) {
  705. return major;
  706. }
  707. return null;
  708. }();
  709. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  710. IS_EDGE = /Edg/i.test(USER_AGENT);
  711. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  712. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  713. CHROMIUM_VERSION = CHROME_VERSION = function () {
  714. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  715. if (match && match[2]) {
  716. return parseFloat(match[2]);
  717. }
  718. return null;
  719. }();
  720. IE_VERSION = function () {
  721. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  722. let version = result && parseFloat(result[1]);
  723. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  724. // IE 11 has a different user agent string than other IE versions
  725. version = 11.0;
  726. }
  727. return version;
  728. }();
  729. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  730. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  731. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  732. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  733. }
  734. /**
  735. * Whether or not this is an iOS device.
  736. *
  737. * @static
  738. * @const
  739. * @type {Boolean}
  740. */
  741. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  742. /**
  743. * Whether or not this is any flavor of Safari - including iOS.
  744. *
  745. * @static
  746. * @const
  747. * @type {Boolean}
  748. */
  749. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  750. var browser = /*#__PURE__*/Object.freeze({
  751. __proto__: null,
  752. get IS_IPOD () { return IS_IPOD; },
  753. get IOS_VERSION () { return IOS_VERSION; },
  754. get IS_ANDROID () { return IS_ANDROID; },
  755. get ANDROID_VERSION () { return ANDROID_VERSION; },
  756. get IS_FIREFOX () { return IS_FIREFOX; },
  757. get IS_EDGE () { return IS_EDGE; },
  758. get IS_CHROMIUM () { return IS_CHROMIUM; },
  759. get IS_CHROME () { return IS_CHROME; },
  760. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  761. get CHROME_VERSION () { return CHROME_VERSION; },
  762. get IE_VERSION () { return IE_VERSION; },
  763. get IS_SAFARI () { return IS_SAFARI; },
  764. get IS_WINDOWS () { return IS_WINDOWS; },
  765. get IS_IPAD () { return IS_IPAD; },
  766. get IS_IPHONE () { return IS_IPHONE; },
  767. TOUCH_ENABLED: TOUCH_ENABLED,
  768. IS_IOS: IS_IOS,
  769. IS_ANY_SAFARI: IS_ANY_SAFARI
  770. });
  771. /**
  772. * @file dom.js
  773. * @module dom
  774. */
  775. /**
  776. * Detect if a value is a string with any non-whitespace characters.
  777. *
  778. * @private
  779. * @param {string} str
  780. * The string to check
  781. *
  782. * @return {boolean}
  783. * Will be `true` if the string is non-blank, `false` otherwise.
  784. *
  785. */
  786. function isNonBlankString(str) {
  787. // we use str.trim as it will trim any whitespace characters
  788. // from the front or back of non-whitespace characters. aka
  789. // Any string that contains non-whitespace characters will
  790. // still contain them after `trim` but whitespace only strings
  791. // will have a length of 0, failing this check.
  792. return typeof str === 'string' && Boolean(str.trim());
  793. }
  794. /**
  795. * Throws an error if the passed string has whitespace. This is used by
  796. * class methods to be relatively consistent with the classList API.
  797. *
  798. * @private
  799. * @param {string} str
  800. * The string to check for whitespace.
  801. *
  802. * @throws {Error}
  803. * Throws an error if there is whitespace in the string.
  804. */
  805. function throwIfWhitespace(str) {
  806. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  807. if (str.indexOf(' ') >= 0) {
  808. throw new Error('class has illegal whitespace characters');
  809. }
  810. }
  811. /**
  812. * Whether the current DOM interface appears to be real (i.e. not simulated).
  813. *
  814. * @return {boolean}
  815. * Will be `true` if the DOM appears to be real, `false` otherwise.
  816. */
  817. function isReal() {
  818. // Both document and window will never be undefined thanks to `global`.
  819. return document === window.document;
  820. }
  821. /**
  822. * Determines, via duck typing, whether or not a value is a DOM element.
  823. *
  824. * @param {*} value
  825. * The value to check.
  826. *
  827. * @return {boolean}
  828. * Will be `true` if the value is a DOM element, `false` otherwise.
  829. */
  830. function isEl(value) {
  831. return isObject(value) && value.nodeType === 1;
  832. }
  833. /**
  834. * Determines if the current DOM is embedded in an iframe.
  835. *
  836. * @return {boolean}
  837. * Will be `true` if the DOM is embedded in an iframe, `false`
  838. * otherwise.
  839. */
  840. function isInFrame() {
  841. // We need a try/catch here because Safari will throw errors when attempting
  842. // to get either `parent` or `self`
  843. try {
  844. return window.parent !== window.self;
  845. } catch (x) {
  846. return true;
  847. }
  848. }
  849. /**
  850. * Creates functions to query the DOM using a given method.
  851. *
  852. * @private
  853. * @param {string} method
  854. * The method to create the query with.
  855. *
  856. * @return {Function}
  857. * The query method
  858. */
  859. function createQuerier(method) {
  860. return function (selector, context) {
  861. if (!isNonBlankString(selector)) {
  862. return document[method](null);
  863. }
  864. if (isNonBlankString(context)) {
  865. context = document.querySelector(context);
  866. }
  867. const ctx = isEl(context) ? context : document;
  868. return ctx[method] && ctx[method](selector);
  869. };
  870. }
  871. /**
  872. * Creates an element and applies properties, attributes, and inserts content.
  873. *
  874. * @param {string} [tagName='div']
  875. * Name of tag to be created.
  876. *
  877. * @param {Object} [properties={}]
  878. * Element properties to be applied.
  879. *
  880. * @param {Object} [attributes={}]
  881. * Element attributes to be applied.
  882. *
  883. * @param {ContentDescriptor} [content]
  884. * A content descriptor object.
  885. *
  886. * @return {Element}
  887. * The element that was created.
  888. */
  889. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  890. const el = document.createElement(tagName);
  891. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  892. const val = properties[propName];
  893. // Handle textContent since it's not supported everywhere and we have a
  894. // method for it.
  895. if (propName === 'textContent') {
  896. textContent(el, val);
  897. } else if (el[propName] !== val || propName === 'tabIndex') {
  898. el[propName] = val;
  899. }
  900. });
  901. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  902. el.setAttribute(attrName, attributes[attrName]);
  903. });
  904. if (content) {
  905. appendContent(el, content);
  906. }
  907. return el;
  908. }
  909. /**
  910. * Injects text into an element, replacing any existing contents entirely.
  911. *
  912. * @param {Element} el
  913. * The element to add text content into
  914. *
  915. * @param {string} text
  916. * The text content to add.
  917. *
  918. * @return {Element}
  919. * The element with added text content.
  920. */
  921. function textContent(el, text) {
  922. if (typeof el.textContent === 'undefined') {
  923. el.innerText = text;
  924. } else {
  925. el.textContent = text;
  926. }
  927. return el;
  928. }
  929. /**
  930. * Insert an element as the first child node of another
  931. *
  932. * @param {Element} child
  933. * Element to insert
  934. *
  935. * @param {Element} parent
  936. * Element to insert child into
  937. */
  938. function prependTo(child, parent) {
  939. if (parent.firstChild) {
  940. parent.insertBefore(child, parent.firstChild);
  941. } else {
  942. parent.appendChild(child);
  943. }
  944. }
  945. /**
  946. * Check if an element has a class name.
  947. *
  948. * @param {Element} element
  949. * Element to check
  950. *
  951. * @param {string} classToCheck
  952. * Class name to check for
  953. *
  954. * @return {boolean}
  955. * Will be `true` if the element has a class, `false` otherwise.
  956. *
  957. * @throws {Error}
  958. * Throws an error if `classToCheck` has white space.
  959. */
  960. function hasClass(element, classToCheck) {
  961. throwIfWhitespace(classToCheck);
  962. return element.classList.contains(classToCheck);
  963. }
  964. /**
  965. * Add a class name to an element.
  966. *
  967. * @param {Element} element
  968. * Element to add class name to.
  969. *
  970. * @param {...string} classesToAdd
  971. * One or more class name to add.
  972. *
  973. * @return {Element}
  974. * The DOM element with the added class name.
  975. */
  976. function addClass(element, ...classesToAdd) {
  977. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  978. return element;
  979. }
  980. /**
  981. * Remove a class name from an element.
  982. *
  983. * @param {Element} element
  984. * Element to remove a class name from.
  985. *
  986. * @param {...string} classesToRemove
  987. * One or more class name to remove.
  988. *
  989. * @return {Element}
  990. * The DOM element with class name removed.
  991. */
  992. function removeClass(element, ...classesToRemove) {
  993. // Protect in case the player gets disposed
  994. if (!element) {
  995. log.warn("removeClass was called with an element that doesn't exist");
  996. return null;
  997. }
  998. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  999. return element;
  1000. }
  1001. /**
  1002. * The callback definition for toggleClass.
  1003. *
  1004. * @callback module:dom~PredicateCallback
  1005. * @param {Element} element
  1006. * The DOM element of the Component.
  1007. *
  1008. * @param {string} classToToggle
  1009. * The `className` that wants to be toggled
  1010. *
  1011. * @return {boolean|undefined}
  1012. * If `true` is returned, the `classToToggle` will be added to the
  1013. * `element`. If `false`, the `classToToggle` will be removed from
  1014. * the `element`. If `undefined`, the callback will be ignored.
  1015. */
  1016. /**
  1017. * Adds or removes a class name to/from an element depending on an optional
  1018. * condition or the presence/absence of the class name.
  1019. *
  1020. * @param {Element} element
  1021. * The element to toggle a class name on.
  1022. *
  1023. * @param {string} classToToggle
  1024. * The class that should be toggled.
  1025. *
  1026. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1027. * See the return value for {@link module:dom~PredicateCallback}
  1028. *
  1029. * @return {Element}
  1030. * The element with a class that has been toggled.
  1031. */
  1032. function toggleClass(element, classToToggle, predicate) {
  1033. if (typeof predicate === 'function') {
  1034. predicate = predicate(element, classToToggle);
  1035. }
  1036. if (typeof predicate !== 'boolean') {
  1037. predicate = undefined;
  1038. }
  1039. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1040. return element;
  1041. }
  1042. /**
  1043. * Apply attributes to an HTML element.
  1044. *
  1045. * @param {Element} el
  1046. * Element to add attributes to.
  1047. *
  1048. * @param {Object} [attributes]
  1049. * Attributes to be applied.
  1050. */
  1051. function setAttributes(el, attributes) {
  1052. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1053. const attrValue = attributes[attrName];
  1054. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1055. el.removeAttribute(attrName);
  1056. } else {
  1057. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1058. }
  1059. });
  1060. }
  1061. /**
  1062. * Get an element's attribute values, as defined on the HTML tag.
  1063. *
  1064. * Attributes are not the same as properties. They're defined on the tag
  1065. * or with setAttribute.
  1066. *
  1067. * @param {Element} tag
  1068. * Element from which to get tag attributes.
  1069. *
  1070. * @return {Object}
  1071. * All attributes of the element. Boolean attributes will be `true` or
  1072. * `false`, others will be strings.
  1073. */
  1074. function getAttributes(tag) {
  1075. const obj = {};
  1076. // known boolean attributes
  1077. // we can check for matching boolean properties, but not all browsers
  1078. // and not all tags know about these attributes, so, we still want to check them manually
  1079. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1080. if (tag && tag.attributes && tag.attributes.length > 0) {
  1081. const attrs = tag.attributes;
  1082. for (let i = attrs.length - 1; i >= 0; i--) {
  1083. const attrName = attrs[i].name;
  1084. let attrVal = attrs[i].value;
  1085. // check for known booleans
  1086. // the matching element property will return a value for typeof
  1087. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1088. // the value of an included boolean attribute is typically an empty
  1089. // string ('') which would equal false if we just check for a false value.
  1090. // we also don't want support bad code like autoplay='false'
  1091. attrVal = attrVal !== null ? true : false;
  1092. }
  1093. obj[attrName] = attrVal;
  1094. }
  1095. }
  1096. return obj;
  1097. }
  1098. /**
  1099. * Get the value of an element's attribute.
  1100. *
  1101. * @param {Element} el
  1102. * A DOM element.
  1103. *
  1104. * @param {string} attribute
  1105. * Attribute to get the value of.
  1106. *
  1107. * @return {string}
  1108. * The value of the attribute.
  1109. */
  1110. function getAttribute(el, attribute) {
  1111. return el.getAttribute(attribute);
  1112. }
  1113. /**
  1114. * Set the value of an element's attribute.
  1115. *
  1116. * @param {Element} el
  1117. * A DOM element.
  1118. *
  1119. * @param {string} attribute
  1120. * Attribute to set.
  1121. *
  1122. * @param {string} value
  1123. * Value to set the attribute to.
  1124. */
  1125. function setAttribute(el, attribute, value) {
  1126. el.setAttribute(attribute, value);
  1127. }
  1128. /**
  1129. * Remove an element's attribute.
  1130. *
  1131. * @param {Element} el
  1132. * A DOM element.
  1133. *
  1134. * @param {string} attribute
  1135. * Attribute to remove.
  1136. */
  1137. function removeAttribute(el, attribute) {
  1138. el.removeAttribute(attribute);
  1139. }
  1140. /**
  1141. * Attempt to block the ability to select text.
  1142. */
  1143. function blockTextSelection() {
  1144. document.body.focus();
  1145. document.onselectstart = function () {
  1146. return false;
  1147. };
  1148. }
  1149. /**
  1150. * Turn off text selection blocking.
  1151. */
  1152. function unblockTextSelection() {
  1153. document.onselectstart = function () {
  1154. return true;
  1155. };
  1156. }
  1157. /**
  1158. * Identical to the native `getBoundingClientRect` function, but ensures that
  1159. * the method is supported at all (it is in all browsers we claim to support)
  1160. * and that the element is in the DOM before continuing.
  1161. *
  1162. * This wrapper function also shims properties which are not provided by some
  1163. * older browsers (namely, IE8).
  1164. *
  1165. * Additionally, some browsers do not support adding properties to a
  1166. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1167. * properties (except `x` and `y` which are not widely supported). This helps
  1168. * avoid implementations where keys are non-enumerable.
  1169. *
  1170. * @param {Element} el
  1171. * Element whose `ClientRect` we want to calculate.
  1172. *
  1173. * @return {Object|undefined}
  1174. * Always returns a plain object - or `undefined` if it cannot.
  1175. */
  1176. function getBoundingClientRect(el) {
  1177. if (el && el.getBoundingClientRect && el.parentNode) {
  1178. const rect = el.getBoundingClientRect();
  1179. const result = {};
  1180. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1181. if (rect[k] !== undefined) {
  1182. result[k] = rect[k];
  1183. }
  1184. });
  1185. if (!result.height) {
  1186. result.height = parseFloat(computedStyle(el, 'height'));
  1187. }
  1188. if (!result.width) {
  1189. result.width = parseFloat(computedStyle(el, 'width'));
  1190. }
  1191. return result;
  1192. }
  1193. }
  1194. /**
  1195. * Represents the position of a DOM element on the page.
  1196. *
  1197. * @typedef {Object} module:dom~Position
  1198. *
  1199. * @property {number} left
  1200. * Pixels to the left.
  1201. *
  1202. * @property {number} top
  1203. * Pixels from the top.
  1204. */
  1205. /**
  1206. * Get the position of an element in the DOM.
  1207. *
  1208. * Uses `getBoundingClientRect` technique from John Resig.
  1209. *
  1210. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1211. *
  1212. * @param {Element} el
  1213. * Element from which to get offset.
  1214. *
  1215. * @return {module:dom~Position}
  1216. * The position of the element that was passed in.
  1217. */
  1218. function findPosition(el) {
  1219. if (!el || el && !el.offsetParent) {
  1220. return {
  1221. left: 0,
  1222. top: 0,
  1223. width: 0,
  1224. height: 0
  1225. };
  1226. }
  1227. const width = el.offsetWidth;
  1228. const height = el.offsetHeight;
  1229. let left = 0;
  1230. let top = 0;
  1231. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1232. left += el.offsetLeft;
  1233. top += el.offsetTop;
  1234. el = el.offsetParent;
  1235. }
  1236. return {
  1237. left,
  1238. top,
  1239. width,
  1240. height
  1241. };
  1242. }
  1243. /**
  1244. * Represents x and y coordinates for a DOM element or mouse pointer.
  1245. *
  1246. * @typedef {Object} module:dom~Coordinates
  1247. *
  1248. * @property {number} x
  1249. * x coordinate in pixels
  1250. *
  1251. * @property {number} y
  1252. * y coordinate in pixels
  1253. */
  1254. /**
  1255. * Get the pointer position within an element.
  1256. *
  1257. * The base on the coordinates are the bottom left of the element.
  1258. *
  1259. * @param {Element} el
  1260. * Element on which to get the pointer position on.
  1261. *
  1262. * @param {Event} event
  1263. * Event object.
  1264. *
  1265. * @return {module:dom~Coordinates}
  1266. * A coordinates object corresponding to the mouse position.
  1267. *
  1268. */
  1269. function getPointerPosition(el, event) {
  1270. const translated = {
  1271. x: 0,
  1272. y: 0
  1273. };
  1274. if (IS_IOS) {
  1275. let item = el;
  1276. while (item && item.nodeName.toLowerCase() !== 'html') {
  1277. const transform = computedStyle(item, 'transform');
  1278. if (/^matrix/.test(transform)) {
  1279. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1280. translated.x += values[4];
  1281. translated.y += values[5];
  1282. } else if (/^matrix3d/.test(transform)) {
  1283. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1284. translated.x += values[12];
  1285. translated.y += values[13];
  1286. }
  1287. item = item.parentNode;
  1288. }
  1289. }
  1290. const position = {};
  1291. const boxTarget = findPosition(event.target);
  1292. const box = findPosition(el);
  1293. const boxW = box.width;
  1294. const boxH = box.height;
  1295. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1296. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1297. if (event.changedTouches) {
  1298. offsetX = event.changedTouches[0].pageX - box.left;
  1299. offsetY = event.changedTouches[0].pageY + box.top;
  1300. if (IS_IOS) {
  1301. offsetX -= translated.x;
  1302. offsetY -= translated.y;
  1303. }
  1304. }
  1305. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1306. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1307. return position;
  1308. }
  1309. /**
  1310. * Determines, via duck typing, whether or not a value is a text node.
  1311. *
  1312. * @param {*} value
  1313. * Check if this value is a text node.
  1314. *
  1315. * @return {boolean}
  1316. * Will be `true` if the value is a text node, `false` otherwise.
  1317. */
  1318. function isTextNode(value) {
  1319. return isObject(value) && value.nodeType === 3;
  1320. }
  1321. /**
  1322. * Empties the contents of an element.
  1323. *
  1324. * @param {Element} el
  1325. * The element to empty children from
  1326. *
  1327. * @return {Element}
  1328. * The element with no children
  1329. */
  1330. function emptyEl(el) {
  1331. while (el.firstChild) {
  1332. el.removeChild(el.firstChild);
  1333. }
  1334. return el;
  1335. }
  1336. /**
  1337. * This is a mixed value that describes content to be injected into the DOM
  1338. * via some method. It can be of the following types:
  1339. *
  1340. * Type | Description
  1341. * -----------|-------------
  1342. * `string` | The value will be normalized into a text node.
  1343. * `Element` | The value will be accepted as-is.
  1344. * `Text` | A TextNode. The value will be accepted as-is.
  1345. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).
  1346. * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
  1347. *
  1348. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1349. */
  1350. /**
  1351. * Normalizes content for eventual insertion into the DOM.
  1352. *
  1353. * This allows a wide range of content definition methods, but helps protect
  1354. * from falling into the trap of simply writing to `innerHTML`, which could
  1355. * be an XSS concern.
  1356. *
  1357. * The content for an element can be passed in multiple types and
  1358. * combinations, whose behavior is as follows:
  1359. *
  1360. * @param {ContentDescriptor} content
  1361. * A content descriptor value.
  1362. *
  1363. * @return {Array}
  1364. * All of the content that was passed in, normalized to an array of
  1365. * elements or text nodes.
  1366. */
  1367. function normalizeContent(content) {
  1368. // First, invoke content if it is a function. If it produces an array,
  1369. // that needs to happen before normalization.
  1370. if (typeof content === 'function') {
  1371. content = content();
  1372. }
  1373. // Next up, normalize to an array, so one or many items can be normalized,
  1374. // filtered, and returned.
  1375. return (Array.isArray(content) ? content : [content]).map(value => {
  1376. // First, invoke value if it is a function to produce a new value,
  1377. // which will be subsequently normalized to a Node of some kind.
  1378. if (typeof value === 'function') {
  1379. value = value();
  1380. }
  1381. if (isEl(value) || isTextNode(value)) {
  1382. return value;
  1383. }
  1384. if (typeof value === 'string' && /\S/.test(value)) {
  1385. return document.createTextNode(value);
  1386. }
  1387. }).filter(value => value);
  1388. }
  1389. /**
  1390. * Normalizes and appends content to an element.
  1391. *
  1392. * @param {Element} el
  1393. * Element to append normalized content to.
  1394. *
  1395. * @param {ContentDescriptor} content
  1396. * A content descriptor value.
  1397. *
  1398. * @return {Element}
  1399. * The element with appended normalized content.
  1400. */
  1401. function appendContent(el, content) {
  1402. normalizeContent(content).forEach(node => el.appendChild(node));
  1403. return el;
  1404. }
  1405. /**
  1406. * Normalizes and inserts content into an element; this is identical to
  1407. * `appendContent()`, except it empties the element first.
  1408. *
  1409. * @param {Element} el
  1410. * Element to insert normalized content into.
  1411. *
  1412. * @param {ContentDescriptor} content
  1413. * A content descriptor value.
  1414. *
  1415. * @return {Element}
  1416. * The element with inserted normalized content.
  1417. */
  1418. function insertContent(el, content) {
  1419. return appendContent(emptyEl(el), content);
  1420. }
  1421. /**
  1422. * Check if an event was a single left click.
  1423. *
  1424. * @param {Event} event
  1425. * Event object.
  1426. *
  1427. * @return {boolean}
  1428. * Will be `true` if a single left click, `false` otherwise.
  1429. */
  1430. function isSingleLeftClick(event) {
  1431. // Note: if you create something draggable, be sure to
  1432. // call it on both `mousedown` and `mousemove` event,
  1433. // otherwise `mousedown` should be enough for a button
  1434. if (event.button === undefined && event.buttons === undefined) {
  1435. // Why do we need `buttons` ?
  1436. // Because, middle mouse sometimes have this:
  1437. // e.button === 0 and e.buttons === 4
  1438. // Furthermore, we want to prevent combination click, something like
  1439. // HOLD middlemouse then left click, that would be
  1440. // e.button === 0, e.buttons === 5
  1441. // just `button` is not gonna work
  1442. // Alright, then what this block does ?
  1443. // this is for chrome `simulate mobile devices`
  1444. // I want to support this as well
  1445. return true;
  1446. }
  1447. if (event.button === 0 && event.buttons === undefined) {
  1448. // Touch screen, sometimes on some specific device, `buttons`
  1449. // doesn't have anything (safari on ios, blackberry...)
  1450. return true;
  1451. }
  1452. // `mouseup` event on a single left click has
  1453. // `button` and `buttons` equal to 0
  1454. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1455. return true;
  1456. }
  1457. if (event.button !== 0 || event.buttons !== 1) {
  1458. // This is the reason we have those if else block above
  1459. // if any special case we can catch and let it slide
  1460. // we do it above, when get to here, this definitely
  1461. // is-not-left-click
  1462. return false;
  1463. }
  1464. return true;
  1465. }
  1466. /**
  1467. * Finds a single DOM element matching `selector` within the optional
  1468. * `context` of another DOM element (defaulting to `document`).
  1469. *
  1470. * @param {string} selector
  1471. * A valid CSS selector, which will be passed to `querySelector`.
  1472. *
  1473. * @param {Element|String} [context=document]
  1474. * A DOM element within which to query. Can also be a selector
  1475. * string in which case the first matching element will be used
  1476. * as context. If missing (or no element matches selector), falls
  1477. * back to `document`.
  1478. *
  1479. * @return {Element|null}
  1480. * The element that was found or null.
  1481. */
  1482. const $ = createQuerier('querySelector');
  1483. /**
  1484. * Finds a all DOM elements matching `selector` within the optional
  1485. * `context` of another DOM element (defaulting to `document`).
  1486. *
  1487. * @param {string} selector
  1488. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1489. *
  1490. * @param {Element|String} [context=document]
  1491. * A DOM element within which to query. Can also be a selector
  1492. * string in which case the first matching element will be used
  1493. * as context. If missing (or no element matches selector), falls
  1494. * back to `document`.
  1495. *
  1496. * @return {NodeList}
  1497. * A element list of elements that were found. Will be empty if none
  1498. * were found.
  1499. *
  1500. */
  1501. const $$ = createQuerier('querySelectorAll');
  1502. /**
  1503. * A safe getComputedStyle.
  1504. *
  1505. * This is needed because in Firefox, if the player is loaded in an iframe with
  1506. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1507. * null-check to make sure that the player doesn't break in these cases.
  1508. *
  1509. * @param {Element} el
  1510. * The element you want the computed style of
  1511. *
  1512. * @param {string} prop
  1513. * The property name you want
  1514. *
  1515. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1516. */
  1517. function computedStyle(el, prop) {
  1518. if (!el || !prop) {
  1519. return '';
  1520. }
  1521. if (typeof window.getComputedStyle === 'function') {
  1522. let computedStyleValue;
  1523. try {
  1524. computedStyleValue = window.getComputedStyle(el);
  1525. } catch (e) {
  1526. return '';
  1527. }
  1528. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1529. }
  1530. return '';
  1531. }
  1532. var Dom = /*#__PURE__*/Object.freeze({
  1533. __proto__: null,
  1534. isReal: isReal,
  1535. isEl: isEl,
  1536. isInFrame: isInFrame,
  1537. createEl: createEl,
  1538. textContent: textContent,
  1539. prependTo: prependTo,
  1540. hasClass: hasClass,
  1541. addClass: addClass,
  1542. removeClass: removeClass,
  1543. toggleClass: toggleClass,
  1544. setAttributes: setAttributes,
  1545. getAttributes: getAttributes,
  1546. getAttribute: getAttribute,
  1547. setAttribute: setAttribute,
  1548. removeAttribute: removeAttribute,
  1549. blockTextSelection: blockTextSelection,
  1550. unblockTextSelection: unblockTextSelection,
  1551. getBoundingClientRect: getBoundingClientRect,
  1552. findPosition: findPosition,
  1553. getPointerPosition: getPointerPosition,
  1554. isTextNode: isTextNode,
  1555. emptyEl: emptyEl,
  1556. normalizeContent: normalizeContent,
  1557. appendContent: appendContent,
  1558. insertContent: insertContent,
  1559. isSingleLeftClick: isSingleLeftClick,
  1560. $: $,
  1561. $$: $$,
  1562. computedStyle: computedStyle
  1563. });
  1564. /**
  1565. * @file setup.js - Functions for setting up a player without
  1566. * user interaction based on the data-setup `attribute` of the video tag.
  1567. *
  1568. * @module setup
  1569. */
  1570. let _windowLoaded = false;
  1571. let videojs$1;
  1572. /**
  1573. * Set up any tags that have a data-setup `attribute` when the player is started.
  1574. */
  1575. const autoSetup = function () {
  1576. if (videojs$1.options.autoSetup === false) {
  1577. return;
  1578. }
  1579. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1580. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1581. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1582. const mediaEls = vids.concat(audios, divs);
  1583. // Check if any media elements exist
  1584. if (mediaEls && mediaEls.length > 0) {
  1585. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1586. const mediaEl = mediaEls[i];
  1587. // Check if element exists, has getAttribute func.
  1588. if (mediaEl && mediaEl.getAttribute) {
  1589. // Make sure this player hasn't already been set up.
  1590. if (mediaEl.player === undefined) {
  1591. const options = mediaEl.getAttribute('data-setup');
  1592. // Check if data-setup attr exists.
  1593. // We only auto-setup if they've added the data-setup attr.
  1594. if (options !== null) {
  1595. // Create new video.js instance.
  1596. videojs$1(mediaEl);
  1597. }
  1598. }
  1599. // If getAttribute isn't defined, we need to wait for the DOM.
  1600. } else {
  1601. autoSetupTimeout(1);
  1602. break;
  1603. }
  1604. }
  1605. // No videos were found, so keep looping unless page is finished loading.
  1606. } else if (!_windowLoaded) {
  1607. autoSetupTimeout(1);
  1608. }
  1609. };
  1610. /**
  1611. * Wait until the page is loaded before running autoSetup. This will be called in
  1612. * autoSetup if `hasLoaded` returns false.
  1613. *
  1614. * @param {number} wait
  1615. * How long to wait in ms
  1616. *
  1617. * @param {module:videojs} [vjs]
  1618. * The videojs library function
  1619. */
  1620. function autoSetupTimeout(wait, vjs) {
  1621. // Protect against breakage in non-browser environments
  1622. if (!isReal()) {
  1623. return;
  1624. }
  1625. if (vjs) {
  1626. videojs$1 = vjs;
  1627. }
  1628. window.setTimeout(autoSetup, wait);
  1629. }
  1630. /**
  1631. * Used to set the internal tracking of window loaded state to true.
  1632. *
  1633. * @private
  1634. */
  1635. function setWindowLoaded() {
  1636. _windowLoaded = true;
  1637. window.removeEventListener('load', setWindowLoaded);
  1638. }
  1639. if (isReal()) {
  1640. if (document.readyState === 'complete') {
  1641. setWindowLoaded();
  1642. } else {
  1643. /**
  1644. * Listen for the load event on window, and set _windowLoaded to true.
  1645. *
  1646. * We use a standard event listener here to avoid incrementing the GUID
  1647. * before any players are created.
  1648. *
  1649. * @listens load
  1650. */
  1651. window.addEventListener('load', setWindowLoaded);
  1652. }
  1653. }
  1654. /**
  1655. * @file stylesheet.js
  1656. * @module stylesheet
  1657. */
  1658. /**
  1659. * Create a DOM style element given a className for it.
  1660. *
  1661. * @param {string} className
  1662. * The className to add to the created style element.
  1663. *
  1664. * @return {Element}
  1665. * The element that was created.
  1666. */
  1667. const createStyleElement = function (className) {
  1668. const style = document.createElement('style');
  1669. style.className = className;
  1670. return style;
  1671. };
  1672. /**
  1673. * Add text to a DOM element.
  1674. *
  1675. * @param {Element} el
  1676. * The Element to add text content to.
  1677. *
  1678. * @param {string} content
  1679. * The text to add to the element.
  1680. */
  1681. const setTextContent = function (el, content) {
  1682. if (el.styleSheet) {
  1683. el.styleSheet.cssText = content;
  1684. } else {
  1685. el.textContent = content;
  1686. }
  1687. };
  1688. /**
  1689. * @file dom-data.js
  1690. * @module dom-data
  1691. */
  1692. /**
  1693. * Element Data Store.
  1694. *
  1695. * Allows for binding data to an element without putting it directly on the
  1696. * element. Ex. Event listeners are stored here.
  1697. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1698. *
  1699. * @type {Object}
  1700. * @private
  1701. */
  1702. var DomData = new WeakMap();
  1703. /**
  1704. * @file guid.js
  1705. * @module guid
  1706. */
  1707. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1708. //
  1709. // The initial GUID is 3 because some users have come to rely on the first
  1710. // default player ID ending up as `vjs_video_3`.
  1711. //
  1712. // See: https://github.com/videojs/video.js/pull/6216
  1713. const _initialGuid = 3;
  1714. /**
  1715. * Unique ID for an element or function
  1716. *
  1717. * @type {Number}
  1718. */
  1719. let _guid = _initialGuid;
  1720. /**
  1721. * Get a unique auto-incrementing ID by number that has not been returned before.
  1722. *
  1723. * @return {number}
  1724. * A new unique ID.
  1725. */
  1726. function newGUID() {
  1727. return _guid++;
  1728. }
  1729. /**
  1730. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1731. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1732. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1733. * robust as jquery's, so there's probably some differences.
  1734. *
  1735. * @file events.js
  1736. * @module events
  1737. */
  1738. /**
  1739. * Clean up the listener cache and dispatchers
  1740. *
  1741. * @param {Element|Object} elem
  1742. * Element to clean up
  1743. *
  1744. * @param {string} type
  1745. * Type of event to clean up
  1746. */
  1747. function _cleanUpEvents(elem, type) {
  1748. if (!DomData.has(elem)) {
  1749. return;
  1750. }
  1751. const data = DomData.get(elem);
  1752. // Remove the events of a particular type if there are none left
  1753. if (data.handlers[type].length === 0) {
  1754. delete data.handlers[type];
  1755. // data.handlers[type] = null;
  1756. // Setting to null was causing an error with data.handlers
  1757. // Remove the meta-handler from the element
  1758. if (elem.removeEventListener) {
  1759. elem.removeEventListener(type, data.dispatcher, false);
  1760. } else if (elem.detachEvent) {
  1761. elem.detachEvent('on' + type, data.dispatcher);
  1762. }
  1763. }
  1764. // Remove the events object if there are no types left
  1765. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1766. delete data.handlers;
  1767. delete data.dispatcher;
  1768. delete data.disabled;
  1769. }
  1770. // Finally remove the element data if there is no data left
  1771. if (Object.getOwnPropertyNames(data).length === 0) {
  1772. DomData.delete(elem);
  1773. }
  1774. }
  1775. /**
  1776. * Loops through an array of event types and calls the requested method for each type.
  1777. *
  1778. * @param {Function} fn
  1779. * The event method we want to use.
  1780. *
  1781. * @param {Element|Object} elem
  1782. * Element or object to bind listeners to
  1783. *
  1784. * @param {string} type
  1785. * Type of event to bind to.
  1786. *
  1787. * @param {Function} callback
  1788. * Event listener.
  1789. */
  1790. function _handleMultipleEvents(fn, elem, types, callback) {
  1791. types.forEach(function (type) {
  1792. // Call the event method for each one of the types
  1793. fn(elem, type, callback);
  1794. });
  1795. }
  1796. /**
  1797. * Fix a native event to have standard property values
  1798. *
  1799. * @param {Object} event
  1800. * Event object to fix.
  1801. *
  1802. * @return {Object}
  1803. * Fixed event object.
  1804. */
  1805. function fixEvent(event) {
  1806. if (event.fixed_) {
  1807. return event;
  1808. }
  1809. function returnTrue() {
  1810. return true;
  1811. }
  1812. function returnFalse() {
  1813. return false;
  1814. }
  1815. // Test if fixing up is needed
  1816. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1817. // But native events return true for stopPropagation, but don't have
  1818. // other expected methods like isPropagationStopped. Seems to be a problem
  1819. // with the Javascript Ninja code. So we're just overriding all events now.
  1820. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1821. const old = event || window.event;
  1822. event = {};
  1823. // Clone the old object so that we can modify the values event = {};
  1824. // IE8 Doesn't like when you mess with native event properties
  1825. // Firefox returns false for event.hasOwnProperty('type') and other props
  1826. // which makes copying more difficult.
  1827. // TODO: Probably best to create a whitelist of event props
  1828. for (const key in old) {
  1829. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1830. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1831. // and webkitMovementX/Y
  1832. // Lighthouse complains if Event.path is copied
  1833. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1834. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1835. // we still want to if preventDefault isn't supported (IE8).
  1836. if (!(key === 'returnValue' && old.preventDefault)) {
  1837. event[key] = old[key];
  1838. }
  1839. }
  1840. }
  1841. // The event occurred on this element
  1842. if (!event.target) {
  1843. event.target = event.srcElement || document;
  1844. }
  1845. // Handle which other element the event is related to
  1846. if (!event.relatedTarget) {
  1847. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1848. }
  1849. // Stop the default browser action
  1850. event.preventDefault = function () {
  1851. if (old.preventDefault) {
  1852. old.preventDefault();
  1853. }
  1854. event.returnValue = false;
  1855. old.returnValue = false;
  1856. event.defaultPrevented = true;
  1857. };
  1858. event.defaultPrevented = false;
  1859. // Stop the event from bubbling
  1860. event.stopPropagation = function () {
  1861. if (old.stopPropagation) {
  1862. old.stopPropagation();
  1863. }
  1864. event.cancelBubble = true;
  1865. old.cancelBubble = true;
  1866. event.isPropagationStopped = returnTrue;
  1867. };
  1868. event.isPropagationStopped = returnFalse;
  1869. // Stop the event from bubbling and executing other handlers
  1870. event.stopImmediatePropagation = function () {
  1871. if (old.stopImmediatePropagation) {
  1872. old.stopImmediatePropagation();
  1873. }
  1874. event.isImmediatePropagationStopped = returnTrue;
  1875. event.stopPropagation();
  1876. };
  1877. event.isImmediatePropagationStopped = returnFalse;
  1878. // Handle mouse position
  1879. if (event.clientX !== null && event.clientX !== undefined) {
  1880. const doc = document.documentElement;
  1881. const body = document.body;
  1882. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1883. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1884. }
  1885. // Handle key presses
  1886. event.which = event.charCode || event.keyCode;
  1887. // Fix button for mouse clicks:
  1888. // 0 == left; 1 == middle; 2 == right
  1889. if (event.button !== null && event.button !== undefined) {
  1890. // The following is disabled because it does not pass videojs-standard
  1891. // and... yikes.
  1892. /* eslint-disable */
  1893. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1894. /* eslint-enable */
  1895. }
  1896. }
  1897. event.fixed_ = true;
  1898. // Returns fixed-up instance
  1899. return event;
  1900. }
  1901. /**
  1902. * Whether passive event listeners are supported
  1903. */
  1904. let _supportsPassive;
  1905. const supportsPassive = function () {
  1906. if (typeof _supportsPassive !== 'boolean') {
  1907. _supportsPassive = false;
  1908. try {
  1909. const opts = Object.defineProperty({}, 'passive', {
  1910. get() {
  1911. _supportsPassive = true;
  1912. }
  1913. });
  1914. window.addEventListener('test', null, opts);
  1915. window.removeEventListener('test', null, opts);
  1916. } catch (e) {
  1917. // disregard
  1918. }
  1919. }
  1920. return _supportsPassive;
  1921. };
  1922. /**
  1923. * Touch events Chrome expects to be passive
  1924. */
  1925. const passiveEvents = ['touchstart', 'touchmove'];
  1926. /**
  1927. * Add an event listener to element
  1928. * It stores the handler function in a separate cache object
  1929. * and adds a generic handler to the element's event,
  1930. * along with a unique id (guid) to the element.
  1931. *
  1932. * @param {Element|Object} elem
  1933. * Element or object to bind listeners to
  1934. *
  1935. * @param {string|string[]} type
  1936. * Type of event to bind to.
  1937. *
  1938. * @param {Function} fn
  1939. * Event listener.
  1940. */
  1941. function on(elem, type, fn) {
  1942. if (Array.isArray(type)) {
  1943. return _handleMultipleEvents(on, elem, type, fn);
  1944. }
  1945. if (!DomData.has(elem)) {
  1946. DomData.set(elem, {});
  1947. }
  1948. const data = DomData.get(elem);
  1949. // We need a place to store all our handler data
  1950. if (!data.handlers) {
  1951. data.handlers = {};
  1952. }
  1953. if (!data.handlers[type]) {
  1954. data.handlers[type] = [];
  1955. }
  1956. if (!fn.guid) {
  1957. fn.guid = newGUID();
  1958. }
  1959. data.handlers[type].push(fn);
  1960. if (!data.dispatcher) {
  1961. data.disabled = false;
  1962. data.dispatcher = function (event, hash) {
  1963. if (data.disabled) {
  1964. return;
  1965. }
  1966. event = fixEvent(event);
  1967. const handlers = data.handlers[event.type];
  1968. if (handlers) {
  1969. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1970. const handlersCopy = handlers.slice(0);
  1971. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1972. if (event.isImmediatePropagationStopped()) {
  1973. break;
  1974. } else {
  1975. try {
  1976. handlersCopy[m].call(elem, event, hash);
  1977. } catch (e) {
  1978. log.error(e);
  1979. }
  1980. }
  1981. }
  1982. }
  1983. };
  1984. }
  1985. if (data.handlers[type].length === 1) {
  1986. if (elem.addEventListener) {
  1987. let options = false;
  1988. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  1989. options = {
  1990. passive: true
  1991. };
  1992. }
  1993. elem.addEventListener(type, data.dispatcher, options);
  1994. } else if (elem.attachEvent) {
  1995. elem.attachEvent('on' + type, data.dispatcher);
  1996. }
  1997. }
  1998. }
  1999. /**
  2000. * Removes event listeners from an element
  2001. *
  2002. * @param {Element|Object} elem
  2003. * Object to remove listeners from.
  2004. *
  2005. * @param {string|string[]} [type]
  2006. * Type of listener to remove. Don't include to remove all events from element.
  2007. *
  2008. * @param {Function} [fn]
  2009. * Specific listener to remove. Don't include to remove listeners for an event
  2010. * type.
  2011. */
  2012. function off(elem, type, fn) {
  2013. // Don't want to add a cache object through getElData if not needed
  2014. if (!DomData.has(elem)) {
  2015. return;
  2016. }
  2017. const data = DomData.get(elem);
  2018. // If no events exist, nothing to unbind
  2019. if (!data.handlers) {
  2020. return;
  2021. }
  2022. if (Array.isArray(type)) {
  2023. return _handleMultipleEvents(off, elem, type, fn);
  2024. }
  2025. // Utility function
  2026. const removeType = function (el, t) {
  2027. data.handlers[t] = [];
  2028. _cleanUpEvents(el, t);
  2029. };
  2030. // Are we removing all bound events?
  2031. if (type === undefined) {
  2032. for (const t in data.handlers) {
  2033. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2034. removeType(elem, t);
  2035. }
  2036. }
  2037. return;
  2038. }
  2039. const handlers = data.handlers[type];
  2040. // If no handlers exist, nothing to unbind
  2041. if (!handlers) {
  2042. return;
  2043. }
  2044. // If no listener was provided, remove all listeners for type
  2045. if (!fn) {
  2046. removeType(elem, type);
  2047. return;
  2048. }
  2049. // We're only removing a single handler
  2050. if (fn.guid) {
  2051. for (let n = 0; n < handlers.length; n++) {
  2052. if (handlers[n].guid === fn.guid) {
  2053. handlers.splice(n--, 1);
  2054. }
  2055. }
  2056. }
  2057. _cleanUpEvents(elem, type);
  2058. }
  2059. /**
  2060. * Trigger an event for an element
  2061. *
  2062. * @param {Element|Object} elem
  2063. * Element to trigger an event on
  2064. *
  2065. * @param {EventTarget~Event|string} event
  2066. * A string (the type) or an event object with a type attribute
  2067. *
  2068. * @param {Object} [hash]
  2069. * data hash to pass along with the event
  2070. *
  2071. * @return {boolean|undefined}
  2072. * Returns the opposite of `defaultPrevented` if default was
  2073. * prevented. Otherwise, returns `undefined`
  2074. */
  2075. function trigger(elem, event, hash) {
  2076. // Fetches element data and a reference to the parent (for bubbling).
  2077. // Don't want to add a data object to cache for every parent,
  2078. // so checking hasElData first.
  2079. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2080. const parent = elem.parentNode || elem.ownerDocument;
  2081. // type = event.type || event,
  2082. // handler;
  2083. // If an event name was passed as a string, creates an event out of it
  2084. if (typeof event === 'string') {
  2085. event = {
  2086. type: event,
  2087. target: elem
  2088. };
  2089. } else if (!event.target) {
  2090. event.target = elem;
  2091. }
  2092. // Normalizes the event properties.
  2093. event = fixEvent(event);
  2094. // If the passed element has a dispatcher, executes the established handlers.
  2095. if (elemData.dispatcher) {
  2096. elemData.dispatcher.call(elem, event, hash);
  2097. }
  2098. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2099. // recursively calls this function to bubble the event up the DOM.
  2100. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2101. trigger.call(null, parent, event, hash);
  2102. // If at the top of the DOM, triggers the default action unless disabled.
  2103. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2104. if (!DomData.has(event.target)) {
  2105. DomData.set(event.target, {});
  2106. }
  2107. const targetData = DomData.get(event.target);
  2108. // Checks if the target has a default action for this event.
  2109. if (event.target[event.type]) {
  2110. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2111. targetData.disabled = true;
  2112. // Executes the default action.
  2113. if (typeof event.target[event.type] === 'function') {
  2114. event.target[event.type]();
  2115. }
  2116. // Re-enables event dispatching.
  2117. targetData.disabled = false;
  2118. }
  2119. }
  2120. // Inform the triggerer if the default was prevented by returning false
  2121. return !event.defaultPrevented;
  2122. }
  2123. /**
  2124. * Trigger a listener only once for an event.
  2125. *
  2126. * @param {Element|Object} elem
  2127. * Element or object to bind to.
  2128. *
  2129. * @param {string|string[]} type
  2130. * Name/type of event
  2131. *
  2132. * @param {Event~EventListener} fn
  2133. * Event listener function
  2134. */
  2135. function one(elem, type, fn) {
  2136. if (Array.isArray(type)) {
  2137. return _handleMultipleEvents(one, elem, type, fn);
  2138. }
  2139. const func = function () {
  2140. off(elem, type, func);
  2141. fn.apply(this, arguments);
  2142. };
  2143. // copy the guid to the new function so it can removed using the original function's ID
  2144. func.guid = fn.guid = fn.guid || newGUID();
  2145. on(elem, type, func);
  2146. }
  2147. /**
  2148. * Trigger a listener only once and then turn if off for all
  2149. * configured events
  2150. *
  2151. * @param {Element|Object} elem
  2152. * Element or object to bind to.
  2153. *
  2154. * @param {string|string[]} type
  2155. * Name/type of event
  2156. *
  2157. * @param {Event~EventListener} fn
  2158. * Event listener function
  2159. */
  2160. function any(elem, type, fn) {
  2161. const func = function () {
  2162. off(elem, type, func);
  2163. fn.apply(this, arguments);
  2164. };
  2165. // copy the guid to the new function so it can removed using the original function's ID
  2166. func.guid = fn.guid = fn.guid || newGUID();
  2167. // multiple ons, but one off for everything
  2168. on(elem, type, func);
  2169. }
  2170. var Events = /*#__PURE__*/Object.freeze({
  2171. __proto__: null,
  2172. fixEvent: fixEvent,
  2173. on: on,
  2174. off: off,
  2175. trigger: trigger,
  2176. one: one,
  2177. any: any
  2178. });
  2179. /**
  2180. * @file fn.js
  2181. * @module fn
  2182. */
  2183. const UPDATE_REFRESH_INTERVAL = 30;
  2184. /**
  2185. * A private, internal-only function for changing the context of a function.
  2186. *
  2187. * It also stores a unique id on the function so it can be easily removed from
  2188. * events.
  2189. *
  2190. * @private
  2191. * @function
  2192. * @param {*} context
  2193. * The object to bind as scope.
  2194. *
  2195. * @param {Function} fn
  2196. * The function to be bound to a scope.
  2197. *
  2198. * @param {number} [uid]
  2199. * An optional unique ID for the function to be set
  2200. *
  2201. * @return {Function}
  2202. * The new function that will be bound into the context given
  2203. */
  2204. const bind_ = function (context, fn, uid) {
  2205. // Make sure the function has a unique ID
  2206. if (!fn.guid) {
  2207. fn.guid = newGUID();
  2208. }
  2209. // Create the new function that changes the context
  2210. const bound = fn.bind(context);
  2211. // Allow for the ability to individualize this function
  2212. // Needed in the case where multiple objects might share the same prototype
  2213. // IF both items add an event listener with the same function, then you try to remove just one
  2214. // it will remove both because they both have the same guid.
  2215. // when using this, you need to use the bind method when you remove the listener as well.
  2216. // currently used in text tracks
  2217. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2218. return bound;
  2219. };
  2220. /**
  2221. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2222. * at most once per every `wait` milliseconds.
  2223. *
  2224. * @function
  2225. * @param {Function} fn
  2226. * The function to be throttled.
  2227. *
  2228. * @param {number} wait
  2229. * The number of milliseconds by which to throttle.
  2230. *
  2231. * @return {Function}
  2232. */
  2233. const throttle = function (fn, wait) {
  2234. let last = window.performance.now();
  2235. const throttled = function (...args) {
  2236. const now = window.performance.now();
  2237. if (now - last >= wait) {
  2238. fn(...args);
  2239. last = now;
  2240. }
  2241. };
  2242. return throttled;
  2243. };
  2244. /**
  2245. * Creates a debounced function that delays invoking `func` until after `wait`
  2246. * milliseconds have elapsed since the last time the debounced function was
  2247. * invoked.
  2248. *
  2249. * Inspired by lodash and underscore implementations.
  2250. *
  2251. * @function
  2252. * @param {Function} func
  2253. * The function to wrap with debounce behavior.
  2254. *
  2255. * @param {number} wait
  2256. * The number of milliseconds to wait after the last invocation.
  2257. *
  2258. * @param {boolean} [immediate]
  2259. * Whether or not to invoke the function immediately upon creation.
  2260. *
  2261. * @param {Object} [context=window]
  2262. * The "context" in which the debounced function should debounce. For
  2263. * example, if this function should be tied to a Video.js player,
  2264. * the player can be passed here. Alternatively, defaults to the
  2265. * global `window` object.
  2266. *
  2267. * @return {Function}
  2268. * A debounced function.
  2269. */
  2270. const debounce = function (func, wait, immediate, context = window) {
  2271. let timeout;
  2272. const cancel = () => {
  2273. context.clearTimeout(timeout);
  2274. timeout = null;
  2275. };
  2276. /* eslint-disable consistent-this */
  2277. const debounced = function () {
  2278. const self = this;
  2279. const args = arguments;
  2280. let later = function () {
  2281. timeout = null;
  2282. later = null;
  2283. if (!immediate) {
  2284. func.apply(self, args);
  2285. }
  2286. };
  2287. if (!timeout && immediate) {
  2288. func.apply(self, args);
  2289. }
  2290. context.clearTimeout(timeout);
  2291. timeout = context.setTimeout(later, wait);
  2292. };
  2293. /* eslint-enable consistent-this */
  2294. debounced.cancel = cancel;
  2295. return debounced;
  2296. };
  2297. var Fn = /*#__PURE__*/Object.freeze({
  2298. __proto__: null,
  2299. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2300. bind_: bind_,
  2301. throttle: throttle,
  2302. debounce: debounce
  2303. });
  2304. /**
  2305. * @file src/js/event-target.js
  2306. */
  2307. let EVENT_MAP;
  2308. /**
  2309. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2310. * adds shorthand functions that wrap around lengthy functions. For example:
  2311. * the `on` function is a wrapper around `addEventListener`.
  2312. *
  2313. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2314. * @class EventTarget
  2315. */
  2316. class EventTarget {
  2317. /**
  2318. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2319. * function that will get called when an event with a certain name gets triggered.
  2320. *
  2321. * @param {string|string[]} type
  2322. * An event name or an array of event names.
  2323. *
  2324. * @param {Function} fn
  2325. * The function to call with `EventTarget`s
  2326. */
  2327. on(type, fn) {
  2328. // Remove the addEventListener alias before calling Events.on
  2329. // so we don't get into an infinite type loop
  2330. const ael = this.addEventListener;
  2331. this.addEventListener = () => {};
  2332. on(this, type, fn);
  2333. this.addEventListener = ael;
  2334. }
  2335. /**
  2336. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2337. * This makes it so that the `event listener` will no longer get called when the
  2338. * named event happens.
  2339. *
  2340. * @param {string|string[]} type
  2341. * An event name or an array of event names.
  2342. *
  2343. * @param {Function} fn
  2344. * The function to remove.
  2345. */
  2346. off(type, fn) {
  2347. off(this, type, fn);
  2348. }
  2349. /**
  2350. * This function will add an `event listener` that gets triggered only once. After the
  2351. * first trigger it will get removed. This is like adding an `event listener`
  2352. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2353. *
  2354. * @param {string|string[]} type
  2355. * An event name or an array of event names.
  2356. *
  2357. * @param {Function} fn
  2358. * The function to be called once for each event name.
  2359. */
  2360. one(type, fn) {
  2361. // Remove the addEventListener aliasing Events.on
  2362. // so we don't get into an infinite type loop
  2363. const ael = this.addEventListener;
  2364. this.addEventListener = () => {};
  2365. one(this, type, fn);
  2366. this.addEventListener = ael;
  2367. }
  2368. /**
  2369. * This function will add an `event listener` that gets triggered only once and is
  2370. * removed from all events. This is like adding an array of `event listener`s
  2371. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2372. * first time it is triggered.
  2373. *
  2374. * @param {string|string[]} type
  2375. * An event name or an array of event names.
  2376. *
  2377. * @param {Function} fn
  2378. * The function to be called once for each event name.
  2379. */
  2380. any(type, fn) {
  2381. // Remove the addEventListener aliasing Events.on
  2382. // so we don't get into an infinite type loop
  2383. const ael = this.addEventListener;
  2384. this.addEventListener = () => {};
  2385. any(this, type, fn);
  2386. this.addEventListener = ael;
  2387. }
  2388. /**
  2389. * This function causes an event to happen. This will then cause any `event listeners`
  2390. * that are waiting for that event, to get called. If there are no `event listeners`
  2391. * for an event then nothing will happen.
  2392. *
  2393. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2394. * Trigger will also call the `on` + `uppercaseEventName` function.
  2395. *
  2396. * Example:
  2397. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2398. * `onClick` if it exists.
  2399. *
  2400. * @param {string|EventTarget~Event|Object} event
  2401. * The name of the event, an `Event`, or an object with a key of type set to
  2402. * an event name.
  2403. */
  2404. trigger(event) {
  2405. const type = event.type || event;
  2406. // deprecation
  2407. // In a future version we should default target to `this`
  2408. // similar to how we default the target to `elem` in
  2409. // `Events.trigger`. Right now the default `target` will be
  2410. // `document` due to the `Event.fixEvent` call.
  2411. if (typeof event === 'string') {
  2412. event = {
  2413. type
  2414. };
  2415. }
  2416. event = fixEvent(event);
  2417. if (this.allowedEvents_[type] && this['on' + type]) {
  2418. this['on' + type](event);
  2419. }
  2420. trigger(this, event);
  2421. }
  2422. queueTrigger(event) {
  2423. // only set up EVENT_MAP if it'll be used
  2424. if (!EVENT_MAP) {
  2425. EVENT_MAP = new Map();
  2426. }
  2427. const type = event.type || event;
  2428. let map = EVENT_MAP.get(this);
  2429. if (!map) {
  2430. map = new Map();
  2431. EVENT_MAP.set(this, map);
  2432. }
  2433. const oldTimeout = map.get(type);
  2434. map.delete(type);
  2435. window.clearTimeout(oldTimeout);
  2436. const timeout = window.setTimeout(() => {
  2437. map.delete(type);
  2438. // if we cleared out all timeouts for the current target, delete its map
  2439. if (map.size === 0) {
  2440. map = null;
  2441. EVENT_MAP.delete(this);
  2442. }
  2443. this.trigger(event);
  2444. }, 0);
  2445. map.set(type, timeout);
  2446. }
  2447. }
  2448. /**
  2449. * A Custom DOM event.
  2450. *
  2451. * @typedef {CustomEvent} Event
  2452. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2453. */
  2454. /**
  2455. * All event listeners should follow the following format.
  2456. *
  2457. * @callback EventTarget~EventListener
  2458. * @this {EventTarget}
  2459. *
  2460. * @param {Event} event
  2461. * the event that triggered this function
  2462. *
  2463. * @param {Object} [hash]
  2464. * hash of data sent during the event
  2465. */
  2466. /**
  2467. * An object containing event names as keys and booleans as values.
  2468. *
  2469. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2470. * will have extra functionality. See that function for more information.
  2471. *
  2472. * @property EventTarget.prototype.allowedEvents_
  2473. * @private
  2474. */
  2475. EventTarget.prototype.allowedEvents_ = {};
  2476. /**
  2477. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2478. * the standard DOM API.
  2479. *
  2480. * @function
  2481. * @see {@link EventTarget#on}
  2482. */
  2483. EventTarget.prototype.addEventListener = EventTarget.prototype.on;
  2484. /**
  2485. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2486. * the standard DOM API.
  2487. *
  2488. * @function
  2489. * @see {@link EventTarget#off}
  2490. */
  2491. EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
  2492. /**
  2493. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2494. * the standard DOM API.
  2495. *
  2496. * @function
  2497. * @see {@link EventTarget#trigger}
  2498. */
  2499. EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
  2500. /**
  2501. * @file mixins/evented.js
  2502. * @module evented
  2503. */
  2504. const objName = obj => {
  2505. if (typeof obj.name === 'function') {
  2506. return obj.name();
  2507. }
  2508. if (typeof obj.name === 'string') {
  2509. return obj.name;
  2510. }
  2511. if (obj.name_) {
  2512. return obj.name_;
  2513. }
  2514. if (obj.constructor && obj.constructor.name) {
  2515. return obj.constructor.name;
  2516. }
  2517. return typeof obj;
  2518. };
  2519. /**
  2520. * Returns whether or not an object has had the evented mixin applied.
  2521. *
  2522. * @param {Object} object
  2523. * An object to test.
  2524. *
  2525. * @return {boolean}
  2526. * Whether or not the object appears to be evented.
  2527. */
  2528. const isEvented = object => object instanceof EventTarget || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2529. /**
  2530. * Adds a callback to run after the evented mixin applied.
  2531. *
  2532. * @param {Object} object
  2533. * An object to Add
  2534. * @param {Function} callback
  2535. * The callback to run.
  2536. */
  2537. const addEventedCallback = (target, callback) => {
  2538. if (isEvented(target)) {
  2539. callback();
  2540. } else {
  2541. if (!target.eventedCallbacks) {
  2542. target.eventedCallbacks = [];
  2543. }
  2544. target.eventedCallbacks.push(callback);
  2545. }
  2546. };
  2547. /**
  2548. * Whether a value is a valid event type - non-empty string or array.
  2549. *
  2550. * @private
  2551. * @param {string|Array} type
  2552. * The type value to test.
  2553. *
  2554. * @return {boolean}
  2555. * Whether or not the type is a valid event type.
  2556. */
  2557. const isValidEventType = type =>
  2558. // The regex here verifies that the `type` contains at least one non-
  2559. // whitespace character.
  2560. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2561. /**
  2562. * Validates a value to determine if it is a valid event target. Throws if not.
  2563. *
  2564. * @private
  2565. * @throws {Error}
  2566. * If the target does not appear to be a valid event target.
  2567. *
  2568. * @param {Object} target
  2569. * The object to test.
  2570. *
  2571. * @param {Object} obj
  2572. * The evented object we are validating for
  2573. *
  2574. * @param {string} fnName
  2575. * The name of the evented mixin function that called this.
  2576. */
  2577. const validateTarget = (target, obj, fnName) => {
  2578. if (!target || !target.nodeName && !isEvented(target)) {
  2579. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2580. }
  2581. };
  2582. /**
  2583. * Validates a value to determine if it is a valid event target. Throws if not.
  2584. *
  2585. * @private
  2586. * @throws {Error}
  2587. * If the type does not appear to be a valid event type.
  2588. *
  2589. * @param {string|Array} type
  2590. * The type to test.
  2591. *
  2592. * @param {Object} obj
  2593. * The evented object we are validating for
  2594. *
  2595. * @param {string} fnName
  2596. * The name of the evented mixin function that called this.
  2597. */
  2598. const validateEventType = (type, obj, fnName) => {
  2599. if (!isValidEventType(type)) {
  2600. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2601. }
  2602. };
  2603. /**
  2604. * Validates a value to determine if it is a valid listener. Throws if not.
  2605. *
  2606. * @private
  2607. * @throws {Error}
  2608. * If the listener is not a function.
  2609. *
  2610. * @param {Function} listener
  2611. * The listener to test.
  2612. *
  2613. * @param {Object} obj
  2614. * The evented object we are validating for
  2615. *
  2616. * @param {string} fnName
  2617. * The name of the evented mixin function that called this.
  2618. */
  2619. const validateListener = (listener, obj, fnName) => {
  2620. if (typeof listener !== 'function') {
  2621. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2622. }
  2623. };
  2624. /**
  2625. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2626. * normalizes them into an object.
  2627. *
  2628. * @private
  2629. * @param {Object} self
  2630. * The evented object on which `on()` or `one()` was called. This
  2631. * object will be bound as the `this` value for the listener.
  2632. *
  2633. * @param {Array} args
  2634. * An array of arguments passed to `on()` or `one()`.
  2635. *
  2636. * @param {string} fnName
  2637. * The name of the evented mixin function that called this.
  2638. *
  2639. * @return {Object}
  2640. * An object containing useful values for `on()` or `one()` calls.
  2641. */
  2642. const normalizeListenArgs = (self, args, fnName) => {
  2643. // If the number of arguments is less than 3, the target is always the
  2644. // evented object itself.
  2645. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2646. let target;
  2647. let type;
  2648. let listener;
  2649. if (isTargetingSelf) {
  2650. target = self.eventBusEl_;
  2651. // Deal with cases where we got 3 arguments, but we are still listening to
  2652. // the evented object itself.
  2653. if (args.length >= 3) {
  2654. args.shift();
  2655. }
  2656. [type, listener] = args;
  2657. } else {
  2658. [target, type, listener] = args;
  2659. }
  2660. validateTarget(target, self, fnName);
  2661. validateEventType(type, self, fnName);
  2662. validateListener(listener, self, fnName);
  2663. listener = bind_(self, listener);
  2664. return {
  2665. isTargetingSelf,
  2666. target,
  2667. type,
  2668. listener
  2669. };
  2670. };
  2671. /**
  2672. * Adds the listener to the event type(s) on the target, normalizing for
  2673. * the type of target.
  2674. *
  2675. * @private
  2676. * @param {Element|Object} target
  2677. * A DOM node or evented object.
  2678. *
  2679. * @param {string} method
  2680. * The event binding method to use ("on" or "one").
  2681. *
  2682. * @param {string|Array} type
  2683. * One or more event type(s).
  2684. *
  2685. * @param {Function} listener
  2686. * A listener function.
  2687. */
  2688. const listen = (target, method, type, listener) => {
  2689. validateTarget(target, target, method);
  2690. if (target.nodeName) {
  2691. Events[method](target, type, listener);
  2692. } else {
  2693. target[method](type, listener);
  2694. }
  2695. };
  2696. /**
  2697. * Contains methods that provide event capabilities to an object which is passed
  2698. * to {@link module:evented|evented}.
  2699. *
  2700. * @mixin EventedMixin
  2701. */
  2702. const EventedMixin = {
  2703. /**
  2704. * Add a listener to an event (or events) on this object or another evented
  2705. * object.
  2706. *
  2707. * @param {string|Array|Element|Object} targetOrType
  2708. * If this is a string or array, it represents the event type(s)
  2709. * that will trigger the listener.
  2710. *
  2711. * Another evented object can be passed here instead, which will
  2712. * cause the listener to listen for events on _that_ object.
  2713. *
  2714. * In either case, the listener's `this` value will be bound to
  2715. * this object.
  2716. *
  2717. * @param {string|Array|Function} typeOrListener
  2718. * If the first argument was a string or array, this should be the
  2719. * listener function. Otherwise, this is a string or array of event
  2720. * type(s).
  2721. *
  2722. * @param {Function} [listener]
  2723. * If the first argument was another evented object, this will be
  2724. * the listener function.
  2725. */
  2726. on(...args) {
  2727. const {
  2728. isTargetingSelf,
  2729. target,
  2730. type,
  2731. listener
  2732. } = normalizeListenArgs(this, args, 'on');
  2733. listen(target, 'on', type, listener);
  2734. // If this object is listening to another evented object.
  2735. if (!isTargetingSelf) {
  2736. // If this object is disposed, remove the listener.
  2737. const removeListenerOnDispose = () => this.off(target, type, listener);
  2738. // Use the same function ID as the listener so we can remove it later it
  2739. // using the ID of the original listener.
  2740. removeListenerOnDispose.guid = listener.guid;
  2741. // Add a listener to the target's dispose event as well. This ensures
  2742. // that if the target is disposed BEFORE this object, we remove the
  2743. // removal listener that was just added. Otherwise, we create a memory leak.
  2744. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2745. // Use the same function ID as the listener so we can remove it later
  2746. // it using the ID of the original listener.
  2747. removeRemoverOnTargetDispose.guid = listener.guid;
  2748. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2749. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2750. }
  2751. },
  2752. /**
  2753. * Add a listener to an event (or events) on this object or another evented
  2754. * object. The listener will be called once per event and then removed.
  2755. *
  2756. * @param {string|Array|Element|Object} targetOrType
  2757. * If this is a string or array, it represents the event type(s)
  2758. * that will trigger the listener.
  2759. *
  2760. * Another evented object can be passed here instead, which will
  2761. * cause the listener to listen for events on _that_ object.
  2762. *
  2763. * In either case, the listener's `this` value will be bound to
  2764. * this object.
  2765. *
  2766. * @param {string|Array|Function} typeOrListener
  2767. * If the first argument was a string or array, this should be the
  2768. * listener function. Otherwise, this is a string or array of event
  2769. * type(s).
  2770. *
  2771. * @param {Function} [listener]
  2772. * If the first argument was another evented object, this will be
  2773. * the listener function.
  2774. */
  2775. one(...args) {
  2776. const {
  2777. isTargetingSelf,
  2778. target,
  2779. type,
  2780. listener
  2781. } = normalizeListenArgs(this, args, 'one');
  2782. // Targeting this evented object.
  2783. if (isTargetingSelf) {
  2784. listen(target, 'one', type, listener);
  2785. // Targeting another evented object.
  2786. } else {
  2787. // TODO: This wrapper is incorrect! It should only
  2788. // remove the wrapper for the event type that called it.
  2789. // Instead all listeners are removed on the first trigger!
  2790. // see https://github.com/videojs/video.js/issues/5962
  2791. const wrapper = (...largs) => {
  2792. this.off(target, type, wrapper);
  2793. listener.apply(null, largs);
  2794. };
  2795. // Use the same function ID as the listener so we can remove it later
  2796. // it using the ID of the original listener.
  2797. wrapper.guid = listener.guid;
  2798. listen(target, 'one', type, wrapper);
  2799. }
  2800. },
  2801. /**
  2802. * Add a listener to an event (or events) on this object or another evented
  2803. * object. The listener will only be called once for the first event that is triggered
  2804. * then removed.
  2805. *
  2806. * @param {string|Array|Element|Object} targetOrType
  2807. * If this is a string or array, it represents the event type(s)
  2808. * that will trigger the listener.
  2809. *
  2810. * Another evented object can be passed here instead, which will
  2811. * cause the listener to listen for events on _that_ object.
  2812. *
  2813. * In either case, the listener's `this` value will be bound to
  2814. * this object.
  2815. *
  2816. * @param {string|Array|Function} typeOrListener
  2817. * If the first argument was a string or array, this should be the
  2818. * listener function. Otherwise, this is a string or array of event
  2819. * type(s).
  2820. *
  2821. * @param {Function} [listener]
  2822. * If the first argument was another evented object, this will be
  2823. * the listener function.
  2824. */
  2825. any(...args) {
  2826. const {
  2827. isTargetingSelf,
  2828. target,
  2829. type,
  2830. listener
  2831. } = normalizeListenArgs(this, args, 'any');
  2832. // Targeting this evented object.
  2833. if (isTargetingSelf) {
  2834. listen(target, 'any', type, listener);
  2835. // Targeting another evented object.
  2836. } else {
  2837. const wrapper = (...largs) => {
  2838. this.off(target, type, wrapper);
  2839. listener.apply(null, largs);
  2840. };
  2841. // Use the same function ID as the listener so we can remove it later
  2842. // it using the ID of the original listener.
  2843. wrapper.guid = listener.guid;
  2844. listen(target, 'any', type, wrapper);
  2845. }
  2846. },
  2847. /**
  2848. * Removes listener(s) from event(s) on an evented object.
  2849. *
  2850. * @param {string|Array|Element|Object} [targetOrType]
  2851. * If this is a string or array, it represents the event type(s).
  2852. *
  2853. * Another evented object can be passed here instead, in which case
  2854. * ALL 3 arguments are _required_.
  2855. *
  2856. * @param {string|Array|Function} [typeOrListener]
  2857. * If the first argument was a string or array, this may be the
  2858. * listener function. Otherwise, this is a string or array of event
  2859. * type(s).
  2860. *
  2861. * @param {Function} [listener]
  2862. * If the first argument was another evented object, this will be
  2863. * the listener function; otherwise, _all_ listeners bound to the
  2864. * event type(s) will be removed.
  2865. */
  2866. off(targetOrType, typeOrListener, listener) {
  2867. // Targeting this evented object.
  2868. if (!targetOrType || isValidEventType(targetOrType)) {
  2869. off(this.eventBusEl_, targetOrType, typeOrListener);
  2870. // Targeting another evented object.
  2871. } else {
  2872. const target = targetOrType;
  2873. const type = typeOrListener;
  2874. // Fail fast and in a meaningful way!
  2875. validateTarget(target, this, 'off');
  2876. validateEventType(type, this, 'off');
  2877. validateListener(listener, this, 'off');
  2878. // Ensure there's at least a guid, even if the function hasn't been used
  2879. listener = bind_(this, listener);
  2880. // Remove the dispose listener on this evented object, which was given
  2881. // the same guid as the event listener in on().
  2882. this.off('dispose', listener);
  2883. if (target.nodeName) {
  2884. off(target, type, listener);
  2885. off(target, 'dispose', listener);
  2886. } else if (isEvented(target)) {
  2887. target.off(type, listener);
  2888. target.off('dispose', listener);
  2889. }
  2890. }
  2891. },
  2892. /**
  2893. * Fire an event on this evented object, causing its listeners to be called.
  2894. *
  2895. * @param {string|Object} event
  2896. * An event type or an object with a type property.
  2897. *
  2898. * @param {Object} [hash]
  2899. * An additional object to pass along to listeners.
  2900. *
  2901. * @return {boolean}
  2902. * Whether or not the default behavior was prevented.
  2903. */
  2904. trigger(event, hash) {
  2905. validateTarget(this.eventBusEl_, this, 'trigger');
  2906. const type = event && typeof event !== 'string' ? event.type : event;
  2907. if (!isValidEventType(type)) {
  2908. throw new Error(`Invalid event type for ${objName(this)}#trigger; ` + 'must be a non-empty string or object with a type key that has a non-empty value.');
  2909. }
  2910. return trigger(this.eventBusEl_, event, hash);
  2911. }
  2912. };
  2913. /**
  2914. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2915. *
  2916. * @param {Object} target
  2917. * The object to which to add event methods.
  2918. *
  2919. * @param {Object} [options={}]
  2920. * Options for customizing the mixin behavior.
  2921. *
  2922. * @param {string} [options.eventBusKey]
  2923. * By default, adds a `eventBusEl_` DOM element to the target object,
  2924. * which is used as an event bus. If the target object already has a
  2925. * DOM element that should be used, pass its key here.
  2926. *
  2927. * @return {Object}
  2928. * The target object.
  2929. */
  2930. function evented(target, options = {}) {
  2931. const {
  2932. eventBusKey
  2933. } = options;
  2934. // Set or create the eventBusEl_.
  2935. if (eventBusKey) {
  2936. if (!target[eventBusKey].nodeName) {
  2937. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2938. }
  2939. target.eventBusEl_ = target[eventBusKey];
  2940. } else {
  2941. target.eventBusEl_ = createEl('span', {
  2942. className: 'vjs-event-bus'
  2943. });
  2944. }
  2945. Object.assign(target, EventedMixin);
  2946. if (target.eventedCallbacks) {
  2947. target.eventedCallbacks.forEach(callback => {
  2948. callback();
  2949. });
  2950. }
  2951. // When any evented object is disposed, it removes all its listeners.
  2952. target.on('dispose', () => {
  2953. target.off();
  2954. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2955. if (val && DomData.has(val)) {
  2956. DomData.delete(val);
  2957. }
  2958. });
  2959. window.setTimeout(() => {
  2960. target.eventBusEl_ = null;
  2961. }, 0);
  2962. });
  2963. return target;
  2964. }
  2965. /**
  2966. * @file mixins/stateful.js
  2967. * @module stateful
  2968. */
  2969. /**
  2970. * Contains methods that provide statefulness to an object which is passed
  2971. * to {@link module:stateful}.
  2972. *
  2973. * @mixin StatefulMixin
  2974. */
  2975. const StatefulMixin = {
  2976. /**
  2977. * A hash containing arbitrary keys and values representing the state of
  2978. * the object.
  2979. *
  2980. * @type {Object}
  2981. */
  2982. state: {},
  2983. /**
  2984. * Set the state of an object by mutating its
  2985. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2986. *
  2987. * @fires module:stateful~StatefulMixin#statechanged
  2988. * @param {Object|Function} stateUpdates
  2989. * A new set of properties to shallow-merge into the plugin state.
  2990. * Can be a plain object or a function returning a plain object.
  2991. *
  2992. * @return {Object|undefined}
  2993. * An object containing changes that occurred. If no changes
  2994. * occurred, returns `undefined`.
  2995. */
  2996. setState(stateUpdates) {
  2997. // Support providing the `stateUpdates` state as a function.
  2998. if (typeof stateUpdates === 'function') {
  2999. stateUpdates = stateUpdates();
  3000. }
  3001. let changes;
  3002. each(stateUpdates, (value, key) => {
  3003. // Record the change if the value is different from what's in the
  3004. // current state.
  3005. if (this.state[key] !== value) {
  3006. changes = changes || {};
  3007. changes[key] = {
  3008. from: this.state[key],
  3009. to: value
  3010. };
  3011. }
  3012. this.state[key] = value;
  3013. });
  3014. // Only trigger "statechange" if there were changes AND we have a trigger
  3015. // function. This allows us to not require that the target object be an
  3016. // evented object.
  3017. if (changes && isEvented(this)) {
  3018. /**
  3019. * An event triggered on an object that is both
  3020. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3021. * indicating that its state has changed.
  3022. *
  3023. * @event module:stateful~StatefulMixin#statechanged
  3024. * @type {Object}
  3025. * @property {Object} changes
  3026. * A hash containing the properties that were changed and
  3027. * the values they were changed `from` and `to`.
  3028. */
  3029. this.trigger({
  3030. changes,
  3031. type: 'statechanged'
  3032. });
  3033. }
  3034. return changes;
  3035. }
  3036. };
  3037. /**
  3038. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3039. * object.
  3040. *
  3041. * If the target object is {@link module:evented|evented} and has a
  3042. * `handleStateChanged` method, that method will be automatically bound to the
  3043. * `statechanged` event on itself.
  3044. *
  3045. * @param {Object} target
  3046. * The object to be made stateful.
  3047. *
  3048. * @param {Object} [defaultState]
  3049. * A default set of properties to populate the newly-stateful object's
  3050. * `state` property.
  3051. *
  3052. * @return {Object}
  3053. * Returns the `target`.
  3054. */
  3055. function stateful(target, defaultState) {
  3056. Object.assign(target, StatefulMixin);
  3057. // This happens after the mixing-in because we need to replace the `state`
  3058. // added in that step.
  3059. target.state = Object.assign({}, target.state, defaultState);
  3060. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3061. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3062. target.on('statechanged', target.handleStateChanged);
  3063. }
  3064. return target;
  3065. }
  3066. /**
  3067. * @file str.js
  3068. * @module to-lower-case
  3069. */
  3070. /**
  3071. * Lowercase the first letter of a string.
  3072. *
  3073. * @param {string} string
  3074. * String to be lowercased
  3075. *
  3076. * @return {string}
  3077. * The string with a lowercased first letter
  3078. */
  3079. const toLowerCase = function (string) {
  3080. if (typeof string !== 'string') {
  3081. return string;
  3082. }
  3083. return string.replace(/./, w => w.toLowerCase());
  3084. };
  3085. /**
  3086. * Uppercase the first letter of a string.
  3087. *
  3088. * @param {string} string
  3089. * String to be uppercased
  3090. *
  3091. * @return {string}
  3092. * The string with an uppercased first letter
  3093. */
  3094. const toTitleCase = function (string) {
  3095. if (typeof string !== 'string') {
  3096. return string;
  3097. }
  3098. return string.replace(/./, w => w.toUpperCase());
  3099. };
  3100. /**
  3101. * Compares the TitleCase versions of the two strings for equality.
  3102. *
  3103. * @param {string} str1
  3104. * The first string to compare
  3105. *
  3106. * @param {string} str2
  3107. * The second string to compare
  3108. *
  3109. * @return {boolean}
  3110. * Whether the TitleCase versions of the strings are equal
  3111. */
  3112. const titleCaseEquals = function (str1, str2) {
  3113. return toTitleCase(str1) === toTitleCase(str2);
  3114. };
  3115. var Str = /*#__PURE__*/Object.freeze({
  3116. __proto__: null,
  3117. toLowerCase: toLowerCase,
  3118. toTitleCase: toTitleCase,
  3119. titleCaseEquals: titleCaseEquals
  3120. });
  3121. /**
  3122. * Player Component - Base class for all UI objects
  3123. *
  3124. * @file component.js
  3125. */
  3126. /**
  3127. * Base class for all UI Components.
  3128. * Components are UI objects which represent both a javascript object and an element
  3129. * in the DOM. They can be children of other components, and can have
  3130. * children themselves.
  3131. *
  3132. * Components can also use methods from {@link EventTarget}
  3133. */
  3134. class Component {
  3135. /**
  3136. * A callback that is called when a component is ready. Does not have any
  3137. * parameters and any callback value will be ignored.
  3138. *
  3139. * @callback ReadyCallback
  3140. * @this Component
  3141. */
  3142. /**
  3143. * Creates an instance of this class.
  3144. *
  3145. * @param { import('./player').default } player
  3146. * The `Player` that this class should be attached to.
  3147. *
  3148. * @param {Object} [options]
  3149. * The key/value store of component options.
  3150. *
  3151. * @param {Object[]} [options.children]
  3152. * An array of children objects to initialize this component with. Children objects have
  3153. * a name property that will be used if more than one component of the same type needs to be
  3154. * added.
  3155. *
  3156. * @param {string} [options.className]
  3157. * A class or space separated list of classes to add the component
  3158. *
  3159. * @param {ReadyCallback} [ready]
  3160. * Function that gets called when the `Component` is ready.
  3161. */
  3162. constructor(player, options, ready) {
  3163. // The component might be the player itself and we can't pass `this` to super
  3164. if (!player && this.play) {
  3165. this.player_ = player = this; // eslint-disable-line
  3166. } else {
  3167. this.player_ = player;
  3168. }
  3169. this.isDisposed_ = false;
  3170. // Hold the reference to the parent component via `addChild` method
  3171. this.parentComponent_ = null;
  3172. // Make a copy of prototype.options_ to protect against overriding defaults
  3173. this.options_ = merge({}, this.options_);
  3174. // Updated options with supplied options
  3175. options = this.options_ = merge(this.options_, options);
  3176. // Get ID from options or options element if one is supplied
  3177. this.id_ = options.id || options.el && options.el.id;
  3178. // If there was no ID from the options, generate one
  3179. if (!this.id_) {
  3180. // Don't require the player ID function in the case of mock players
  3181. const id = player && player.id && player.id() || 'no_player';
  3182. this.id_ = `${id}_component_${newGUID()}`;
  3183. }
  3184. this.name_ = options.name || null;
  3185. // Create element if one wasn't provided in options
  3186. if (options.el) {
  3187. this.el_ = options.el;
  3188. } else if (options.createEl !== false) {
  3189. this.el_ = this.createEl();
  3190. }
  3191. if (options.className && this.el_) {
  3192. options.className.split(' ').forEach(c => this.addClass(c));
  3193. }
  3194. // Remove the placeholder event methods. If the component is evented, the
  3195. // real methods are added next
  3196. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3197. this[fn] = undefined;
  3198. });
  3199. // if evented is anything except false, we want to mixin in evented
  3200. if (options.evented !== false) {
  3201. // Make this an evented object and use `el_`, if available, as its event bus
  3202. evented(this, {
  3203. eventBusKey: this.el_ ? 'el_' : null
  3204. });
  3205. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3206. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3207. }
  3208. stateful(this, this.constructor.defaultState);
  3209. this.children_ = [];
  3210. this.childIndex_ = {};
  3211. this.childNameIndex_ = {};
  3212. this.setTimeoutIds_ = new Set();
  3213. this.setIntervalIds_ = new Set();
  3214. this.rafIds_ = new Set();
  3215. this.namedRafs_ = new Map();
  3216. this.clearingTimersOnDispose_ = false;
  3217. // Add any child components in options
  3218. if (options.initChildren !== false) {
  3219. this.initChildren();
  3220. }
  3221. // Don't want to trigger ready here or it will go before init is actually
  3222. // finished for all children that run this constructor
  3223. this.ready(ready);
  3224. if (options.reportTouchActivity !== false) {
  3225. this.enableTouchActivity();
  3226. }
  3227. }
  3228. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3229. // They are replaced or removed in the constructor
  3230. /**
  3231. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3232. * function that will get called when an event with a certain name gets triggered.
  3233. *
  3234. * @param {string|string[]} type
  3235. * An event name or an array of event names.
  3236. *
  3237. * @param {Function} fn
  3238. * The function to call with `EventTarget`s
  3239. */
  3240. on(type, fn) {}
  3241. /**
  3242. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3243. * This makes it so that the `event listener` will no longer get called when the
  3244. * named event happens.
  3245. *
  3246. * @param {string|string[]} type
  3247. * An event name or an array of event names.
  3248. *
  3249. * @param {Function} fn
  3250. * The function to remove.
  3251. */
  3252. off(type, fn) {}
  3253. /**
  3254. * This function will add an `event listener` that gets triggered only once. After the
  3255. * first trigger it will get removed. This is like adding an `event listener`
  3256. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3257. *
  3258. * @param {string|string[]} type
  3259. * An event name or an array of event names.
  3260. *
  3261. * @param {Function} fn
  3262. * The function to be called once for each event name.
  3263. */
  3264. one(type, fn) {}
  3265. /**
  3266. * This function will add an `event listener` that gets triggered only once and is
  3267. * removed from all events. This is like adding an array of `event listener`s
  3268. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3269. * first time it is triggered.
  3270. *
  3271. * @param {string|string[]} type
  3272. * An event name or an array of event names.
  3273. *
  3274. * @param {Function} fn
  3275. * The function to be called once for each event name.
  3276. */
  3277. any(type, fn) {}
  3278. /**
  3279. * This function causes an event to happen. This will then cause any `event listeners`
  3280. * that are waiting for that event, to get called. If there are no `event listeners`
  3281. * for an event then nothing will happen.
  3282. *
  3283. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3284. * Trigger will also call the `on` + `uppercaseEventName` function.
  3285. *
  3286. * Example:
  3287. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3288. * `onClick` if it exists.
  3289. *
  3290. * @param {string|Event|Object} event
  3291. * The name of the event, an `Event`, or an object with a key of type set to
  3292. * an event name.
  3293. */
  3294. trigger(event) {}
  3295. /**
  3296. * Dispose of the `Component` and all child components.
  3297. *
  3298. * @fires Component#dispose
  3299. *
  3300. * @param {Object} options
  3301. * @param {Element} options.originalEl element with which to replace player element
  3302. */
  3303. dispose(options = {}) {
  3304. // Bail out if the component has already been disposed.
  3305. if (this.isDisposed_) {
  3306. return;
  3307. }
  3308. if (this.readyQueue_) {
  3309. this.readyQueue_.length = 0;
  3310. }
  3311. /**
  3312. * Triggered when a `Component` is disposed.
  3313. *
  3314. * @event Component#dispose
  3315. * @type {Event}
  3316. *
  3317. * @property {boolean} [bubbles=false]
  3318. * set to false so that the dispose event does not
  3319. * bubble up
  3320. */
  3321. this.trigger({
  3322. type: 'dispose',
  3323. bubbles: false
  3324. });
  3325. this.isDisposed_ = true;
  3326. // Dispose all children.
  3327. if (this.children_) {
  3328. for (let i = this.children_.length - 1; i >= 0; i--) {
  3329. if (this.children_[i].dispose) {
  3330. this.children_[i].dispose();
  3331. }
  3332. }
  3333. }
  3334. // Delete child references
  3335. this.children_ = null;
  3336. this.childIndex_ = null;
  3337. this.childNameIndex_ = null;
  3338. this.parentComponent_ = null;
  3339. if (this.el_) {
  3340. // Remove element from DOM
  3341. if (this.el_.parentNode) {
  3342. if (options.restoreEl) {
  3343. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3344. } else {
  3345. this.el_.parentNode.removeChild(this.el_);
  3346. }
  3347. }
  3348. this.el_ = null;
  3349. }
  3350. // remove reference to the player after disposing of the element
  3351. this.player_ = null;
  3352. }
  3353. /**
  3354. * Determine whether or not this component has been disposed.
  3355. *
  3356. * @return {boolean}
  3357. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3358. */
  3359. isDisposed() {
  3360. return Boolean(this.isDisposed_);
  3361. }
  3362. /**
  3363. * Return the {@link Player} that the `Component` has attached to.
  3364. *
  3365. * @return { import('./player').default }
  3366. * The player that this `Component` has attached to.
  3367. */
  3368. player() {
  3369. return this.player_;
  3370. }
  3371. /**
  3372. * Deep merge of options objects with new options.
  3373. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3374. * The two properties get merged using {@link module:obj.merge}
  3375. *
  3376. * @param {Object} obj
  3377. * The object that contains new options.
  3378. *
  3379. * @return {Object}
  3380. * A new object of `this.options_` and `obj` merged together.
  3381. */
  3382. options(obj) {
  3383. if (!obj) {
  3384. return this.options_;
  3385. }
  3386. this.options_ = merge(this.options_, obj);
  3387. return this.options_;
  3388. }
  3389. /**
  3390. * Get the `Component`s DOM element
  3391. *
  3392. * @return {Element}
  3393. * The DOM element for this `Component`.
  3394. */
  3395. el() {
  3396. return this.el_;
  3397. }
  3398. /**
  3399. * Create the `Component`s DOM element.
  3400. *
  3401. * @param {string} [tagName]
  3402. * Element's DOM node type. e.g. 'div'
  3403. *
  3404. * @param {Object} [properties]
  3405. * An object of properties that should be set.
  3406. *
  3407. * @param {Object} [attributes]
  3408. * An object of attributes that should be set.
  3409. *
  3410. * @return {Element}
  3411. * The element that gets created.
  3412. */
  3413. createEl(tagName, properties, attributes) {
  3414. return createEl(tagName, properties, attributes);
  3415. }
  3416. /**
  3417. * Localize a string given the string in english.
  3418. *
  3419. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3420. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3421. *
  3422. * If a `defaultValue` is provided, it'll use that over `string`,
  3423. * if a value isn't found in provided language files.
  3424. * This is useful if you want to have a descriptive key for token replacement
  3425. * but have a succinct localized string and not require `en.json` to be included.
  3426. *
  3427. * Currently, it is used for the progress bar timing.
  3428. * ```js
  3429. * {
  3430. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3431. * }
  3432. * ```
  3433. * It is then used like so:
  3434. * ```js
  3435. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3436. * [this.player_.currentTime(), this.player_.duration()],
  3437. * '{1} of {2}');
  3438. * ```
  3439. *
  3440. * Which outputs something like: `01:23 of 24:56`.
  3441. *
  3442. *
  3443. * @param {string} string
  3444. * The string to localize and the key to lookup in the language files.
  3445. * @param {string[]} [tokens]
  3446. * If the current item has token replacements, provide the tokens here.
  3447. * @param {string} [defaultValue]
  3448. * Defaults to `string`. Can be a default value to use for token replacement
  3449. * if the lookup key is needed to be separate.
  3450. *
  3451. * @return {string}
  3452. * The localized string or if no localization exists the english string.
  3453. */
  3454. localize(string, tokens, defaultValue = string) {
  3455. const code = this.player_.language && this.player_.language();
  3456. const languages = this.player_.languages && this.player_.languages();
  3457. const language = languages && languages[code];
  3458. const primaryCode = code && code.split('-')[0];
  3459. const primaryLang = languages && languages[primaryCode];
  3460. let localizedString = defaultValue;
  3461. if (language && language[string]) {
  3462. localizedString = language[string];
  3463. } else if (primaryLang && primaryLang[string]) {
  3464. localizedString = primaryLang[string];
  3465. }
  3466. if (tokens) {
  3467. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3468. const value = tokens[index - 1];
  3469. let ret = value;
  3470. if (typeof value === 'undefined') {
  3471. ret = match;
  3472. }
  3473. return ret;
  3474. });
  3475. }
  3476. return localizedString;
  3477. }
  3478. /**
  3479. * Handles language change for the player in components. Should be overridden by sub-components.
  3480. *
  3481. * @abstract
  3482. */
  3483. handleLanguagechange() {}
  3484. /**
  3485. * Return the `Component`s DOM element. This is where children get inserted.
  3486. * This will usually be the the same as the element returned in {@link Component#el}.
  3487. *
  3488. * @return {Element}
  3489. * The content element for this `Component`.
  3490. */
  3491. contentEl() {
  3492. return this.contentEl_ || this.el_;
  3493. }
  3494. /**
  3495. * Get this `Component`s ID
  3496. *
  3497. * @return {string}
  3498. * The id of this `Component`
  3499. */
  3500. id() {
  3501. return this.id_;
  3502. }
  3503. /**
  3504. * Get the `Component`s name. The name gets used to reference the `Component`
  3505. * and is set during registration.
  3506. *
  3507. * @return {string}
  3508. * The name of this `Component`.
  3509. */
  3510. name() {
  3511. return this.name_;
  3512. }
  3513. /**
  3514. * Get an array of all child components
  3515. *
  3516. * @return {Array}
  3517. * The children
  3518. */
  3519. children() {
  3520. return this.children_;
  3521. }
  3522. /**
  3523. * Returns the child `Component` with the given `id`.
  3524. *
  3525. * @param {string} id
  3526. * The id of the child `Component` to get.
  3527. *
  3528. * @return {Component|undefined}
  3529. * The child `Component` with the given `id` or undefined.
  3530. */
  3531. getChildById(id) {
  3532. return this.childIndex_[id];
  3533. }
  3534. /**
  3535. * Returns the child `Component` with the given `name`.
  3536. *
  3537. * @param {string} name
  3538. * The name of the child `Component` to get.
  3539. *
  3540. * @return {Component|undefined}
  3541. * The child `Component` with the given `name` or undefined.
  3542. */
  3543. getChild(name) {
  3544. if (!name) {
  3545. return;
  3546. }
  3547. return this.childNameIndex_[name];
  3548. }
  3549. /**
  3550. * Returns the descendant `Component` following the givent
  3551. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3552. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3553. * component and 'baz' on the 'bar' component and return undefined
  3554. * if any of those don't exist.
  3555. *
  3556. * @param {...string[]|...string} names
  3557. * The name of the child `Component` to get.
  3558. *
  3559. * @return {Component|undefined}
  3560. * The descendant `Component` following the given descendant
  3561. * `names` or undefined.
  3562. */
  3563. getDescendant(...names) {
  3564. // flatten array argument into the main array
  3565. names = names.reduce((acc, n) => acc.concat(n), []);
  3566. let currentChild = this;
  3567. for (let i = 0; i < names.length; i++) {
  3568. currentChild = currentChild.getChild(names[i]);
  3569. if (!currentChild || !currentChild.getChild) {
  3570. return;
  3571. }
  3572. }
  3573. return currentChild;
  3574. }
  3575. /**
  3576. * Add a child `Component` inside the current `Component`.
  3577. *
  3578. *
  3579. * @param {string|Component} child
  3580. * The name or instance of a child to add.
  3581. *
  3582. * @param {Object} [options={}]
  3583. * The key/value store of options that will get passed to children of
  3584. * the child.
  3585. *
  3586. * @param {number} [index=this.children_.length]
  3587. * The index to attempt to add a child into.
  3588. *
  3589. * @return {Component}
  3590. * The `Component` that gets added as a child. When using a string the
  3591. * `Component` will get created by this process.
  3592. */
  3593. addChild(child, options = {}, index = this.children_.length) {
  3594. let component;
  3595. let componentName;
  3596. // If child is a string, create component with options
  3597. if (typeof child === 'string') {
  3598. componentName = toTitleCase(child);
  3599. const componentClassName = options.componentClass || componentName;
  3600. // Set name through options
  3601. options.name = componentName;
  3602. // Create a new object & element for this controls set
  3603. // If there's no .player_, this is a player
  3604. const ComponentClass = Component.getComponent(componentClassName);
  3605. if (!ComponentClass) {
  3606. throw new Error(`Component ${componentClassName} does not exist`);
  3607. }
  3608. // data stored directly on the videojs object may be
  3609. // misidentified as a component to retain
  3610. // backwards-compatibility with 4.x. check to make sure the
  3611. // component class can be instantiated.
  3612. if (typeof ComponentClass !== 'function') {
  3613. return null;
  3614. }
  3615. component = new ComponentClass(this.player_ || this, options);
  3616. // child is a component instance
  3617. } else {
  3618. component = child;
  3619. }
  3620. if (component.parentComponent_) {
  3621. component.parentComponent_.removeChild(component);
  3622. }
  3623. this.children_.splice(index, 0, component);
  3624. component.parentComponent_ = this;
  3625. if (typeof component.id === 'function') {
  3626. this.childIndex_[component.id()] = component;
  3627. }
  3628. // If a name wasn't used to create the component, check if we can use the
  3629. // name function of the component
  3630. componentName = componentName || component.name && toTitleCase(component.name());
  3631. if (componentName) {
  3632. this.childNameIndex_[componentName] = component;
  3633. this.childNameIndex_[toLowerCase(componentName)] = component;
  3634. }
  3635. // Add the UI object's element to the container div (box)
  3636. // Having an element is not required
  3637. if (typeof component.el === 'function' && component.el()) {
  3638. // If inserting before a component, insert before that component's element
  3639. let refNode = null;
  3640. if (this.children_[index + 1]) {
  3641. // Most children are components, but the video tech is an HTML element
  3642. if (this.children_[index + 1].el_) {
  3643. refNode = this.children_[index + 1].el_;
  3644. } else if (isEl(this.children_[index + 1])) {
  3645. refNode = this.children_[index + 1];
  3646. }
  3647. }
  3648. this.contentEl().insertBefore(component.el(), refNode);
  3649. }
  3650. // Return so it can stored on parent object if desired.
  3651. return component;
  3652. }
  3653. /**
  3654. * Remove a child `Component` from this `Component`s list of children. Also removes
  3655. * the child `Component`s element from this `Component`s element.
  3656. *
  3657. * @param {Component} component
  3658. * The child `Component` to remove.
  3659. */
  3660. removeChild(component) {
  3661. if (typeof component === 'string') {
  3662. component = this.getChild(component);
  3663. }
  3664. if (!component || !this.children_) {
  3665. return;
  3666. }
  3667. let childFound = false;
  3668. for (let i = this.children_.length - 1; i >= 0; i--) {
  3669. if (this.children_[i] === component) {
  3670. childFound = true;
  3671. this.children_.splice(i, 1);
  3672. break;
  3673. }
  3674. }
  3675. if (!childFound) {
  3676. return;
  3677. }
  3678. component.parentComponent_ = null;
  3679. this.childIndex_[component.id()] = null;
  3680. this.childNameIndex_[toTitleCase(component.name())] = null;
  3681. this.childNameIndex_[toLowerCase(component.name())] = null;
  3682. const compEl = component.el();
  3683. if (compEl && compEl.parentNode === this.contentEl()) {
  3684. this.contentEl().removeChild(component.el());
  3685. }
  3686. }
  3687. /**
  3688. * Add and initialize default child `Component`s based upon options.
  3689. */
  3690. initChildren() {
  3691. const children = this.options_.children;
  3692. if (children) {
  3693. // `this` is `parent`
  3694. const parentOptions = this.options_;
  3695. const handleAdd = child => {
  3696. const name = child.name;
  3697. let opts = child.opts;
  3698. // Allow options for children to be set at the parent options
  3699. // e.g. videojs(id, { controlBar: false });
  3700. // instead of videojs(id, { children: { controlBar: false });
  3701. if (parentOptions[name] !== undefined) {
  3702. opts = parentOptions[name];
  3703. }
  3704. // Allow for disabling default components
  3705. // e.g. options['children']['posterImage'] = false
  3706. if (opts === false) {
  3707. return;
  3708. }
  3709. // Allow options to be passed as a simple boolean if no configuration
  3710. // is necessary.
  3711. if (opts === true) {
  3712. opts = {};
  3713. }
  3714. // We also want to pass the original player options
  3715. // to each component as well so they don't need to
  3716. // reach back into the player for options later.
  3717. opts.playerOptions = this.options_.playerOptions;
  3718. // Create and add the child component.
  3719. // Add a direct reference to the child by name on the parent instance.
  3720. // If two of the same component are used, different names should be supplied
  3721. // for each
  3722. const newChild = this.addChild(name, opts);
  3723. if (newChild) {
  3724. this[name] = newChild;
  3725. }
  3726. };
  3727. // Allow for an array of children details to passed in the options
  3728. let workingChildren;
  3729. const Tech = Component.getComponent('Tech');
  3730. if (Array.isArray(children)) {
  3731. workingChildren = children;
  3732. } else {
  3733. workingChildren = Object.keys(children);
  3734. }
  3735. workingChildren
  3736. // children that are in this.options_ but also in workingChildren would
  3737. // give us extra children we do not want. So, we want to filter them out.
  3738. .concat(Object.keys(this.options_).filter(function (child) {
  3739. return !workingChildren.some(function (wchild) {
  3740. if (typeof wchild === 'string') {
  3741. return child === wchild;
  3742. }
  3743. return child === wchild.name;
  3744. });
  3745. })).map(child => {
  3746. let name;
  3747. let opts;
  3748. if (typeof child === 'string') {
  3749. name = child;
  3750. opts = children[name] || this.options_[name] || {};
  3751. } else {
  3752. name = child.name;
  3753. opts = child;
  3754. }
  3755. return {
  3756. name,
  3757. opts
  3758. };
  3759. }).filter(child => {
  3760. // we have to make sure that child.name isn't in the techOrder since
  3761. // techs are registered as Components but can't aren't compatible
  3762. // See https://github.com/videojs/video.js/issues/2772
  3763. const c = Component.getComponent(child.opts.componentClass || toTitleCase(child.name));
  3764. return c && !Tech.isTech(c);
  3765. }).forEach(handleAdd);
  3766. }
  3767. }
  3768. /**
  3769. * Builds the default DOM class name. Should be overridden by sub-components.
  3770. *
  3771. * @return {string}
  3772. * The DOM class name for this object.
  3773. *
  3774. * @abstract
  3775. */
  3776. buildCSSClass() {
  3777. // Child classes can include a function that does:
  3778. // return 'CLASS NAME' + this._super();
  3779. return '';
  3780. }
  3781. /**
  3782. * Bind a listener to the component's ready state.
  3783. * Different from event listeners in that if the ready event has already happened
  3784. * it will trigger the function immediately.
  3785. *
  3786. * @param {ReadyCallback} fn
  3787. * Function that gets called when the `Component` is ready.
  3788. *
  3789. * @return {Component}
  3790. * Returns itself; method can be chained.
  3791. */
  3792. ready(fn, sync = false) {
  3793. if (!fn) {
  3794. return;
  3795. }
  3796. if (!this.isReady_) {
  3797. this.readyQueue_ = this.readyQueue_ || [];
  3798. this.readyQueue_.push(fn);
  3799. return;
  3800. }
  3801. if (sync) {
  3802. fn.call(this);
  3803. } else {
  3804. // Call the function asynchronously by default for consistency
  3805. this.setTimeout(fn, 1);
  3806. }
  3807. }
  3808. /**
  3809. * Trigger all the ready listeners for this `Component`.
  3810. *
  3811. * @fires Component#ready
  3812. */
  3813. triggerReady() {
  3814. this.isReady_ = true;
  3815. // Ensure ready is triggered asynchronously
  3816. this.setTimeout(function () {
  3817. const readyQueue = this.readyQueue_;
  3818. // Reset Ready Queue
  3819. this.readyQueue_ = [];
  3820. if (readyQueue && readyQueue.length > 0) {
  3821. readyQueue.forEach(function (fn) {
  3822. fn.call(this);
  3823. }, this);
  3824. }
  3825. // Allow for using event listeners also
  3826. /**
  3827. * Triggered when a `Component` is ready.
  3828. *
  3829. * @event Component#ready
  3830. * @type {Event}
  3831. */
  3832. this.trigger('ready');
  3833. }, 1);
  3834. }
  3835. /**
  3836. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  3837. * `contentEl()` or another custom context.
  3838. *
  3839. * @param {string} selector
  3840. * A valid CSS selector, which will be passed to `querySelector`.
  3841. *
  3842. * @param {Element|string} [context=this.contentEl()]
  3843. * A DOM element within which to query. Can also be a selector string in
  3844. * which case the first matching element will get used as context. If
  3845. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3846. * nothing it falls back to `document`.
  3847. *
  3848. * @return {Element|null}
  3849. * the dom element that was found, or null
  3850. *
  3851. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3852. */
  3853. $(selector, context) {
  3854. return $(selector, context || this.contentEl());
  3855. }
  3856. /**
  3857. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  3858. * `contentEl()` or another custom context.
  3859. *
  3860. * @param {string} selector
  3861. * A valid CSS selector, which will be passed to `querySelectorAll`.
  3862. *
  3863. * @param {Element|string} [context=this.contentEl()]
  3864. * A DOM element within which to query. Can also be a selector string in
  3865. * which case the first matching element will get used as context. If
  3866. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3867. * nothing it falls back to `document`.
  3868. *
  3869. * @return {NodeList}
  3870. * a list of dom elements that were found
  3871. *
  3872. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3873. */
  3874. $$(selector, context) {
  3875. return $$(selector, context || this.contentEl());
  3876. }
  3877. /**
  3878. * Check if a component's element has a CSS class name.
  3879. *
  3880. * @param {string} classToCheck
  3881. * CSS class name to check.
  3882. *
  3883. * @return {boolean}
  3884. * - True if the `Component` has the class.
  3885. * - False if the `Component` does not have the class`
  3886. */
  3887. hasClass(classToCheck) {
  3888. return hasClass(this.el_, classToCheck);
  3889. }
  3890. /**
  3891. * Add a CSS class name to the `Component`s element.
  3892. *
  3893. * @param {...string} classesToAdd
  3894. * One or more CSS class name to add.
  3895. */
  3896. addClass(...classesToAdd) {
  3897. addClass(this.el_, ...classesToAdd);
  3898. }
  3899. /**
  3900. * Remove a CSS class name from the `Component`s element.
  3901. *
  3902. * @param {...string} classesToRemove
  3903. * One or more CSS class name to remove.
  3904. */
  3905. removeClass(...classesToRemove) {
  3906. removeClass(this.el_, ...classesToRemove);
  3907. }
  3908. /**
  3909. * Add or remove a CSS class name from the component's element.
  3910. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  3911. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  3912. *
  3913. * @param {string} classToToggle
  3914. * The class to add or remove based on (@link Component#hasClass}
  3915. *
  3916. * @param {boolean|Dom~predicate} [predicate]
  3917. * An {@link Dom~predicate} function or a boolean
  3918. */
  3919. toggleClass(classToToggle, predicate) {
  3920. toggleClass(this.el_, classToToggle, predicate);
  3921. }
  3922. /**
  3923. * Show the `Component`s element if it is hidden by removing the
  3924. * 'vjs-hidden' class name from it.
  3925. */
  3926. show() {
  3927. this.removeClass('vjs-hidden');
  3928. }
  3929. /**
  3930. * Hide the `Component`s element if it is currently showing by adding the
  3931. * 'vjs-hidden` class name to it.
  3932. */
  3933. hide() {
  3934. this.addClass('vjs-hidden');
  3935. }
  3936. /**
  3937. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  3938. * class name to it. Used during fadeIn/fadeOut.
  3939. *
  3940. * @private
  3941. */
  3942. lockShowing() {
  3943. this.addClass('vjs-lock-showing');
  3944. }
  3945. /**
  3946. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  3947. * class name from it. Used during fadeIn/fadeOut.
  3948. *
  3949. * @private
  3950. */
  3951. unlockShowing() {
  3952. this.removeClass('vjs-lock-showing');
  3953. }
  3954. /**
  3955. * Get the value of an attribute on the `Component`s element.
  3956. *
  3957. * @param {string} attribute
  3958. * Name of the attribute to get the value from.
  3959. *
  3960. * @return {string|null}
  3961. * - The value of the attribute that was asked for.
  3962. * - Can be an empty string on some browsers if the attribute does not exist
  3963. * or has no value
  3964. * - Most browsers will return null if the attribute does not exist or has
  3965. * no value.
  3966. *
  3967. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  3968. */
  3969. getAttribute(attribute) {
  3970. return getAttribute(this.el_, attribute);
  3971. }
  3972. /**
  3973. * Set the value of an attribute on the `Component`'s element
  3974. *
  3975. * @param {string} attribute
  3976. * Name of the attribute to set.
  3977. *
  3978. * @param {string} value
  3979. * Value to set the attribute to.
  3980. *
  3981. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  3982. */
  3983. setAttribute(attribute, value) {
  3984. setAttribute(this.el_, attribute, value);
  3985. }
  3986. /**
  3987. * Remove an attribute from the `Component`s element.
  3988. *
  3989. * @param {string} attribute
  3990. * Name of the attribute to remove.
  3991. *
  3992. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  3993. */
  3994. removeAttribute(attribute) {
  3995. removeAttribute(this.el_, attribute);
  3996. }
  3997. /**
  3998. * Get or set the width of the component based upon the CSS styles.
  3999. * See {@link Component#dimension} for more detailed information.
  4000. *
  4001. * @param {number|string} [num]
  4002. * The width that you want to set postfixed with '%', 'px' or nothing.
  4003. *
  4004. * @param {boolean} [skipListeners]
  4005. * Skip the componentresize event trigger
  4006. *
  4007. * @return {number|string}
  4008. * The width when getting, zero if there is no width. Can be a string
  4009. * postpixed with '%' or 'px'.
  4010. */
  4011. width(num, skipListeners) {
  4012. return this.dimension('width', num, skipListeners);
  4013. }
  4014. /**
  4015. * Get or set the height of the component based upon the CSS styles.
  4016. * See {@link Component#dimension} for more detailed information.
  4017. *
  4018. * @param {number|string} [num]
  4019. * The height that you want to set postfixed with '%', 'px' or nothing.
  4020. *
  4021. * @param {boolean} [skipListeners]
  4022. * Skip the componentresize event trigger
  4023. *
  4024. * @return {number|string}
  4025. * The width when getting, zero if there is no width. Can be a string
  4026. * postpixed with '%' or 'px'.
  4027. */
  4028. height(num, skipListeners) {
  4029. return this.dimension('height', num, skipListeners);
  4030. }
  4031. /**
  4032. * Set both the width and height of the `Component` element at the same time.
  4033. *
  4034. * @param {number|string} width
  4035. * Width to set the `Component`s element to.
  4036. *
  4037. * @param {number|string} height
  4038. * Height to set the `Component`s element to.
  4039. */
  4040. dimensions(width, height) {
  4041. // Skip componentresize listeners on width for optimization
  4042. this.width(width, true);
  4043. this.height(height);
  4044. }
  4045. /**
  4046. * Get or set width or height of the `Component` element. This is the shared code
  4047. * for the {@link Component#width} and {@link Component#height}.
  4048. *
  4049. * Things to know:
  4050. * - If the width or height in an number this will return the number postfixed with 'px'.
  4051. * - If the width/height is a percent this will return the percent postfixed with '%'
  4052. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4053. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4054. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4055. * for more information
  4056. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4057. * and {@link {Component#currentHeight}
  4058. *
  4059. * @fires Component#componentresize
  4060. *
  4061. * @param {string} widthOrHeight
  4062. 8 'width' or 'height'
  4063. *
  4064. * @param {number|string} [num]
  4065. 8 New dimension
  4066. *
  4067. * @param {boolean} [skipListeners]
  4068. * Skip componentresize event trigger
  4069. *
  4070. * @return {number}
  4071. * The dimension when getting or 0 if unset
  4072. */
  4073. dimension(widthOrHeight, num, skipListeners) {
  4074. if (num !== undefined) {
  4075. // Set to zero if null or literally NaN (NaN !== NaN)
  4076. if (num === null || num !== num) {
  4077. num = 0;
  4078. }
  4079. // Check if using css width/height (% or px) and adjust
  4080. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4081. this.el_.style[widthOrHeight] = num;
  4082. } else if (num === 'auto') {
  4083. this.el_.style[widthOrHeight] = '';
  4084. } else {
  4085. this.el_.style[widthOrHeight] = num + 'px';
  4086. }
  4087. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4088. if (!skipListeners) {
  4089. /**
  4090. * Triggered when a component is resized.
  4091. *
  4092. * @event Component#componentresize
  4093. * @type {Event}
  4094. */
  4095. this.trigger('componentresize');
  4096. }
  4097. return;
  4098. }
  4099. // Not setting a value, so getting it
  4100. // Make sure element exists
  4101. if (!this.el_) {
  4102. return 0;
  4103. }
  4104. // Get dimension value from style
  4105. const val = this.el_.style[widthOrHeight];
  4106. const pxIndex = val.indexOf('px');
  4107. if (pxIndex !== -1) {
  4108. // Return the pixel value with no 'px'
  4109. return parseInt(val.slice(0, pxIndex), 10);
  4110. }
  4111. // No px so using % or no style was set, so falling back to offsetWidth/height
  4112. // If component has display:none, offset will return 0
  4113. // TODO: handle display:none and no dimension style using px
  4114. return parseInt(this.el_['offset' + toTitleCase(widthOrHeight)], 10);
  4115. }
  4116. /**
  4117. * Get the computed width or the height of the component's element.
  4118. *
  4119. * Uses `window.getComputedStyle`.
  4120. *
  4121. * @param {string} widthOrHeight
  4122. * A string containing 'width' or 'height'. Whichever one you want to get.
  4123. *
  4124. * @return {number}
  4125. * The dimension that gets asked for or 0 if nothing was set
  4126. * for that dimension.
  4127. */
  4128. currentDimension(widthOrHeight) {
  4129. let computedWidthOrHeight = 0;
  4130. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4131. throw new Error('currentDimension only accepts width or height value');
  4132. }
  4133. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4134. // remove 'px' from variable and parse as integer
  4135. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4136. // if the computed value is still 0, it's possible that the browser is lying
  4137. // and we want to check the offset values.
  4138. // This code also runs wherever getComputedStyle doesn't exist.
  4139. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4140. const rule = `offset${toTitleCase(widthOrHeight)}`;
  4141. computedWidthOrHeight = this.el_[rule];
  4142. }
  4143. return computedWidthOrHeight;
  4144. }
  4145. /**
  4146. * An object that contains width and height values of the `Component`s
  4147. * computed style. Uses `window.getComputedStyle`.
  4148. *
  4149. * @typedef {Object} Component~DimensionObject
  4150. *
  4151. * @property {number} width
  4152. * The width of the `Component`s computed style.
  4153. *
  4154. * @property {number} height
  4155. * The height of the `Component`s computed style.
  4156. */
  4157. /**
  4158. * Get an object that contains computed width and height values of the
  4159. * component's element.
  4160. *
  4161. * Uses `window.getComputedStyle`.
  4162. *
  4163. * @return {Component~DimensionObject}
  4164. * The computed dimensions of the component's element.
  4165. */
  4166. currentDimensions() {
  4167. return {
  4168. width: this.currentDimension('width'),
  4169. height: this.currentDimension('height')
  4170. };
  4171. }
  4172. /**
  4173. * Get the computed width of the component's element.
  4174. *
  4175. * Uses `window.getComputedStyle`.
  4176. *
  4177. * @return {number}
  4178. * The computed width of the component's element.
  4179. */
  4180. currentWidth() {
  4181. return this.currentDimension('width');
  4182. }
  4183. /**
  4184. * Get the computed height of the component's element.
  4185. *
  4186. * Uses `window.getComputedStyle`.
  4187. *
  4188. * @return {number}
  4189. * The computed height of the component's element.
  4190. */
  4191. currentHeight() {
  4192. return this.currentDimension('height');
  4193. }
  4194. /**
  4195. * Set the focus to this component
  4196. */
  4197. focus() {
  4198. this.el_.focus();
  4199. }
  4200. /**
  4201. * Remove the focus from this component
  4202. */
  4203. blur() {
  4204. this.el_.blur();
  4205. }
  4206. /**
  4207. * When this Component receives a `keydown` event which it does not process,
  4208. * it passes the event to the Player for handling.
  4209. *
  4210. * @param {KeyboardEvent} event
  4211. * The `keydown` event that caused this function to be called.
  4212. */
  4213. handleKeyDown(event) {
  4214. if (this.player_) {
  4215. // We only stop propagation here because we want unhandled events to fall
  4216. // back to the browser. Exclude Tab for focus trapping.
  4217. if (!keycode.isEventKey(event, 'Tab')) {
  4218. event.stopPropagation();
  4219. }
  4220. this.player_.handleKeyDown(event);
  4221. }
  4222. }
  4223. /**
  4224. * Many components used to have a `handleKeyPress` method, which was poorly
  4225. * named because it listened to a `keydown` event. This method name now
  4226. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4227. * will not see their method calls stop working.
  4228. *
  4229. * @param {Event} event
  4230. * The event that caused this function to be called.
  4231. */
  4232. handleKeyPress(event) {
  4233. this.handleKeyDown(event);
  4234. }
  4235. /**
  4236. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4237. * support toggling the controls through a tap on the video. They get enabled
  4238. * because every sub-component would have extra overhead otherwise.
  4239. *
  4240. * @private
  4241. * @fires Component#tap
  4242. * @listens Component#touchstart
  4243. * @listens Component#touchmove
  4244. * @listens Component#touchleave
  4245. * @listens Component#touchcancel
  4246. * @listens Component#touchend
  4247. */
  4248. emitTapEvents() {
  4249. // Track the start time so we can determine how long the touch lasted
  4250. let touchStart = 0;
  4251. let firstTouch = null;
  4252. // Maximum movement allowed during a touch event to still be considered a tap
  4253. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4254. // so 10 seems like a nice, round number.
  4255. const tapMovementThreshold = 10;
  4256. // The maximum length a touch can be while still being considered a tap
  4257. const touchTimeThreshold = 200;
  4258. let couldBeTap;
  4259. this.on('touchstart', function (event) {
  4260. // If more than one finger, don't consider treating this as a click
  4261. if (event.touches.length === 1) {
  4262. // Copy pageX/pageY from the object
  4263. firstTouch = {
  4264. pageX: event.touches[0].pageX,
  4265. pageY: event.touches[0].pageY
  4266. };
  4267. // Record start time so we can detect a tap vs. "touch and hold"
  4268. touchStart = window.performance.now();
  4269. // Reset couldBeTap tracking
  4270. couldBeTap = true;
  4271. }
  4272. });
  4273. this.on('touchmove', function (event) {
  4274. // If more than one finger, don't consider treating this as a click
  4275. if (event.touches.length > 1) {
  4276. couldBeTap = false;
  4277. } else if (firstTouch) {
  4278. // Some devices will throw touchmoves for all but the slightest of taps.
  4279. // So, if we moved only a small distance, this could still be a tap
  4280. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4281. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4282. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4283. if (touchDistance > tapMovementThreshold) {
  4284. couldBeTap = false;
  4285. }
  4286. }
  4287. });
  4288. const noTap = function () {
  4289. couldBeTap = false;
  4290. };
  4291. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4292. this.on('touchleave', noTap);
  4293. this.on('touchcancel', noTap);
  4294. // When the touch ends, measure how long it took and trigger the appropriate
  4295. // event
  4296. this.on('touchend', function (event) {
  4297. firstTouch = null;
  4298. // Proceed only if the touchmove/leave/cancel event didn't happen
  4299. if (couldBeTap === true) {
  4300. // Measure how long the touch lasted
  4301. const touchTime = window.performance.now() - touchStart;
  4302. // Make sure the touch was less than the threshold to be considered a tap
  4303. if (touchTime < touchTimeThreshold) {
  4304. // Don't let browser turn this into a click
  4305. event.preventDefault();
  4306. /**
  4307. * Triggered when a `Component` is tapped.
  4308. *
  4309. * @event Component#tap
  4310. * @type {MouseEvent}
  4311. */
  4312. this.trigger('tap');
  4313. // It may be good to copy the touchend event object and change the
  4314. // type to tap, if the other event properties aren't exact after
  4315. // Events.fixEvent runs (e.g. event.target)
  4316. }
  4317. }
  4318. });
  4319. }
  4320. /**
  4321. * This function reports user activity whenever touch events happen. This can get
  4322. * turned off by any sub-components that wants touch events to act another way.
  4323. *
  4324. * Report user touch activity when touch events occur. User activity gets used to
  4325. * determine when controls should show/hide. It is simple when it comes to mouse
  4326. * events, because any mouse event should show the controls. So we capture mouse
  4327. * events that bubble up to the player and report activity when that happens.
  4328. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4329. * controls. So touch events can't help us at the player level either.
  4330. *
  4331. * User activity gets checked asynchronously. So what could happen is a tap event
  4332. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4333. * the player. Which, if it reported user activity, would turn the controls right
  4334. * back on. We also don't want to completely block touch events from bubbling up.
  4335. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4336. * controls back on.
  4337. *
  4338. * @listens Component#touchstart
  4339. * @listens Component#touchmove
  4340. * @listens Component#touchend
  4341. * @listens Component#touchcancel
  4342. */
  4343. enableTouchActivity() {
  4344. // Don't continue if the root player doesn't support reporting user activity
  4345. if (!this.player() || !this.player().reportUserActivity) {
  4346. return;
  4347. }
  4348. // listener for reporting that the user is active
  4349. const report = bind_(this.player(), this.player().reportUserActivity);
  4350. let touchHolding;
  4351. this.on('touchstart', function () {
  4352. report();
  4353. // For as long as the they are touching the device or have their mouse down,
  4354. // we consider them active even if they're not moving their finger or mouse.
  4355. // So we want to continue to update that they are active
  4356. this.clearInterval(touchHolding);
  4357. // report at the same interval as activityCheck
  4358. touchHolding = this.setInterval(report, 250);
  4359. });
  4360. const touchEnd = function (event) {
  4361. report();
  4362. // stop the interval that maintains activity if the touch is holding
  4363. this.clearInterval(touchHolding);
  4364. };
  4365. this.on('touchmove', report);
  4366. this.on('touchend', touchEnd);
  4367. this.on('touchcancel', touchEnd);
  4368. }
  4369. /**
  4370. * A callback that has no parameters and is bound into `Component`s context.
  4371. *
  4372. * @callback Component~GenericCallback
  4373. * @this Component
  4374. */
  4375. /**
  4376. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4377. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4378. * instead though:
  4379. * 1. It gets cleared via {@link Component#clearTimeout} when
  4380. * {@link Component#dispose} gets called.
  4381. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4382. *
  4383. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4384. * will cause its dispose listener not to get cleaned up! Please use
  4385. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4386. *
  4387. * @param {Component~GenericCallback} fn
  4388. * The function that will be run after `timeout`.
  4389. *
  4390. * @param {number} timeout
  4391. * Timeout in milliseconds to delay before executing the specified function.
  4392. *
  4393. * @return {number}
  4394. * Returns a timeout ID that gets used to identify the timeout. It can also
  4395. * get used in {@link Component#clearTimeout} to clear the timeout that
  4396. * was set.
  4397. *
  4398. * @listens Component#dispose
  4399. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4400. */
  4401. setTimeout(fn, timeout) {
  4402. // declare as variables so they are properly available in timeout function
  4403. // eslint-disable-next-line
  4404. var timeoutId;
  4405. fn = bind_(this, fn);
  4406. this.clearTimersOnDispose_();
  4407. timeoutId = window.setTimeout(() => {
  4408. if (this.setTimeoutIds_.has(timeoutId)) {
  4409. this.setTimeoutIds_.delete(timeoutId);
  4410. }
  4411. fn();
  4412. }, timeout);
  4413. this.setTimeoutIds_.add(timeoutId);
  4414. return timeoutId;
  4415. }
  4416. /**
  4417. * Clears a timeout that gets created via `window.setTimeout` or
  4418. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4419. * use this function instead of `window.clearTimout`. If you don't your dispose
  4420. * listener will not get cleaned up until {@link Component#dispose}!
  4421. *
  4422. * @param {number} timeoutId
  4423. * The id of the timeout to clear. The return value of
  4424. * {@link Component#setTimeout} or `window.setTimeout`.
  4425. *
  4426. * @return {number}
  4427. * Returns the timeout id that was cleared.
  4428. *
  4429. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4430. */
  4431. clearTimeout(timeoutId) {
  4432. if (this.setTimeoutIds_.has(timeoutId)) {
  4433. this.setTimeoutIds_.delete(timeoutId);
  4434. window.clearTimeout(timeoutId);
  4435. }
  4436. return timeoutId;
  4437. }
  4438. /**
  4439. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4440. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4441. * 1. It gets cleared via {@link Component#clearInterval} when
  4442. * {@link Component#dispose} gets called.
  4443. * 2. The function callback will be a {@link Component~GenericCallback}
  4444. *
  4445. * @param {Component~GenericCallback} fn
  4446. * The function to run every `x` seconds.
  4447. *
  4448. * @param {number} interval
  4449. * Execute the specified function every `x` milliseconds.
  4450. *
  4451. * @return {number}
  4452. * Returns an id that can be used to identify the interval. It can also be be used in
  4453. * {@link Component#clearInterval} to clear the interval.
  4454. *
  4455. * @listens Component#dispose
  4456. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4457. */
  4458. setInterval(fn, interval) {
  4459. fn = bind_(this, fn);
  4460. this.clearTimersOnDispose_();
  4461. const intervalId = window.setInterval(fn, interval);
  4462. this.setIntervalIds_.add(intervalId);
  4463. return intervalId;
  4464. }
  4465. /**
  4466. * Clears an interval that gets created via `window.setInterval` or
  4467. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4468. * use this function instead of `window.clearInterval`. If you don't your dispose
  4469. * listener will not get cleaned up until {@link Component#dispose}!
  4470. *
  4471. * @param {number} intervalId
  4472. * The id of the interval to clear. The return value of
  4473. * {@link Component#setInterval} or `window.setInterval`.
  4474. *
  4475. * @return {number}
  4476. * Returns the interval id that was cleared.
  4477. *
  4478. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4479. */
  4480. clearInterval(intervalId) {
  4481. if (this.setIntervalIds_.has(intervalId)) {
  4482. this.setIntervalIds_.delete(intervalId);
  4483. window.clearInterval(intervalId);
  4484. }
  4485. return intervalId;
  4486. }
  4487. /**
  4488. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4489. * with a few extra bonuses:
  4490. *
  4491. * - Supports browsers that do not support rAF by falling back to
  4492. * {@link Component#setTimeout}.
  4493. *
  4494. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4495. * bound to the component).
  4496. *
  4497. * - Automatic cancellation of the rAF callback is handled if the component
  4498. * is disposed before it is called.
  4499. *
  4500. * @param {Component~GenericCallback} fn
  4501. * A function that will be bound to this component and executed just
  4502. * before the browser's next repaint.
  4503. *
  4504. * @return {number}
  4505. * Returns an rAF ID that gets used to identify the timeout. It can
  4506. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4507. * the animation frame callback.
  4508. *
  4509. * @listens Component#dispose
  4510. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4511. */
  4512. requestAnimationFrame(fn) {
  4513. this.clearTimersOnDispose_();
  4514. // declare as variables so they are properly available in rAF function
  4515. // eslint-disable-next-line
  4516. var id;
  4517. fn = bind_(this, fn);
  4518. id = window.requestAnimationFrame(() => {
  4519. if (this.rafIds_.has(id)) {
  4520. this.rafIds_.delete(id);
  4521. }
  4522. fn();
  4523. });
  4524. this.rafIds_.add(id);
  4525. return id;
  4526. }
  4527. /**
  4528. * Request an animation frame, but only one named animation
  4529. * frame will be queued. Another will never be added until
  4530. * the previous one finishes.
  4531. *
  4532. * @param {string} name
  4533. * The name to give this requestAnimationFrame
  4534. *
  4535. * @param {Component~GenericCallback} fn
  4536. * A function that will be bound to this component and executed just
  4537. * before the browser's next repaint.
  4538. */
  4539. requestNamedAnimationFrame(name, fn) {
  4540. if (this.namedRafs_.has(name)) {
  4541. return;
  4542. }
  4543. this.clearTimersOnDispose_();
  4544. fn = bind_(this, fn);
  4545. const id = this.requestAnimationFrame(() => {
  4546. fn();
  4547. if (this.namedRafs_.has(name)) {
  4548. this.namedRafs_.delete(name);
  4549. }
  4550. });
  4551. this.namedRafs_.set(name, id);
  4552. return name;
  4553. }
  4554. /**
  4555. * Cancels a current named animation frame if it exists.
  4556. *
  4557. * @param {string} name
  4558. * The name of the requestAnimationFrame to cancel.
  4559. */
  4560. cancelNamedAnimationFrame(name) {
  4561. if (!this.namedRafs_.has(name)) {
  4562. return;
  4563. }
  4564. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4565. this.namedRafs_.delete(name);
  4566. }
  4567. /**
  4568. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4569. * (rAF).
  4570. *
  4571. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4572. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4573. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4574. *
  4575. * @param {number} id
  4576. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4577. *
  4578. * @return {number}
  4579. * Returns the rAF ID that was cleared.
  4580. *
  4581. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4582. */
  4583. cancelAnimationFrame(id) {
  4584. if (this.rafIds_.has(id)) {
  4585. this.rafIds_.delete(id);
  4586. window.cancelAnimationFrame(id);
  4587. }
  4588. return id;
  4589. }
  4590. /**
  4591. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4592. * and `setInterval`, clearing on dispose.
  4593. *
  4594. * > Previously each timer added and removed dispose listeners on it's own.
  4595. * For better performance it was decided to batch them all, and use `Set`s
  4596. * to track outstanding timer ids.
  4597. *
  4598. * @private
  4599. */
  4600. clearTimersOnDispose_() {
  4601. if (this.clearingTimersOnDispose_) {
  4602. return;
  4603. }
  4604. this.clearingTimersOnDispose_ = true;
  4605. this.one('dispose', () => {
  4606. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4607. // for a `Set` key will actually be the value again
  4608. // so forEach((val, val) =>` but for maps we want to use
  4609. // the key.
  4610. this[idName].forEach((val, key) => this[cancelName](key));
  4611. });
  4612. this.clearingTimersOnDispose_ = false;
  4613. });
  4614. }
  4615. /**
  4616. * Register a `Component` with `videojs` given the name and the component.
  4617. *
  4618. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4619. * should be registered using {@link Tech.registerTech} or
  4620. * {@link videojs:videojs.registerTech}.
  4621. *
  4622. * > NOTE: This function can also be seen on videojs as
  4623. * {@link videojs:videojs.registerComponent}.
  4624. *
  4625. * @param {string} name
  4626. * The name of the `Component` to register.
  4627. *
  4628. * @param {Component} ComponentToRegister
  4629. * The `Component` class to register.
  4630. *
  4631. * @return {Component}
  4632. * The `Component` that was registered.
  4633. */
  4634. static registerComponent(name, ComponentToRegister) {
  4635. if (typeof name !== 'string' || !name) {
  4636. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4637. }
  4638. const Tech = Component.getComponent('Tech');
  4639. // We need to make sure this check is only done if Tech has been registered.
  4640. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4641. const isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4642. if (isTech || !isComp) {
  4643. let reason;
  4644. if (isTech) {
  4645. reason = 'techs must be registered using Tech.registerTech()';
  4646. } else {
  4647. reason = 'must be a Component subclass';
  4648. }
  4649. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4650. }
  4651. name = toTitleCase(name);
  4652. if (!Component.components_) {
  4653. Component.components_ = {};
  4654. }
  4655. const Player = Component.getComponent('Player');
  4656. if (name === 'Player' && Player && Player.players) {
  4657. const players = Player.players;
  4658. const playerNames = Object.keys(players);
  4659. // If we have players that were disposed, then their name will still be
  4660. // in Players.players. So, we must loop through and verify that the value
  4661. // for each item is not null. This allows registration of the Player component
  4662. // after all players have been disposed or before any were created.
  4663. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4664. throw new Error('Can not register Player component after player has been created.');
  4665. }
  4666. }
  4667. Component.components_[name] = ComponentToRegister;
  4668. Component.components_[toLowerCase(name)] = ComponentToRegister;
  4669. return ComponentToRegister;
  4670. }
  4671. /**
  4672. * Get a `Component` based on the name it was registered with.
  4673. *
  4674. * @param {string} name
  4675. * The Name of the component to get.
  4676. *
  4677. * @return {Component}
  4678. * The `Component` that got registered under the given name.
  4679. */
  4680. static getComponent(name) {
  4681. if (!name || !Component.components_) {
  4682. return;
  4683. }
  4684. return Component.components_[name];
  4685. }
  4686. }
  4687. Component.registerComponent('Component', Component);
  4688. /**
  4689. * @file time.js
  4690. * @module time
  4691. */
  4692. /**
  4693. * Returns the time for the specified index at the start or end
  4694. * of a TimeRange object.
  4695. *
  4696. * @typedef {Function} TimeRangeIndex
  4697. *
  4698. * @param {number} [index=0]
  4699. * The range number to return the time for.
  4700. *
  4701. * @return {number}
  4702. * The time offset at the specified index.
  4703. *
  4704. * @deprecated The index argument must be provided.
  4705. * In the future, leaving it out will throw an error.
  4706. */
  4707. /**
  4708. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4709. *
  4710. * @typedef {Object} TimeRange
  4711. *
  4712. * @property {number} length
  4713. * The number of time ranges represented by this object.
  4714. *
  4715. * @property {module:time~TimeRangeIndex} start
  4716. * Returns the time offset at which a specified time range begins.
  4717. *
  4718. * @property {module:time~TimeRangeIndex} end
  4719. * Returns the time offset at which a specified time range ends.
  4720. *
  4721. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4722. */
  4723. /**
  4724. * Check if any of the time ranges are over the maximum index.
  4725. *
  4726. * @private
  4727. * @param {string} fnName
  4728. * The function name to use for logging
  4729. *
  4730. * @param {number} index
  4731. * The index to check
  4732. *
  4733. * @param {number} maxIndex
  4734. * The maximum possible index
  4735. *
  4736. * @throws {Error} if the timeRanges provided are over the maxIndex
  4737. */
  4738. function rangeCheck(fnName, index, maxIndex) {
  4739. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4740. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4741. }
  4742. }
  4743. /**
  4744. * Get the time for the specified index at the start or end
  4745. * of a TimeRange object.
  4746. *
  4747. * @private
  4748. * @param {string} fnName
  4749. * The function name to use for logging
  4750. *
  4751. * @param {string} valueIndex
  4752. * The property that should be used to get the time. should be
  4753. * 'start' or 'end'
  4754. *
  4755. * @param {Array} ranges
  4756. * An array of time ranges
  4757. *
  4758. * @param {Array} [rangeIndex=0]
  4759. * The index to start the search at
  4760. *
  4761. * @return {number}
  4762. * The time that offset at the specified index.
  4763. *
  4764. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4765. * @throws {Error} if rangeIndex is more than the length of ranges
  4766. */
  4767. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4768. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4769. return ranges[rangeIndex][valueIndex];
  4770. }
  4771. /**
  4772. * Create a time range object given ranges of time.
  4773. *
  4774. * @private
  4775. * @param {Array} [ranges]
  4776. * An array of time ranges.
  4777. *
  4778. * @return {TimeRange}
  4779. */
  4780. function createTimeRangesObj(ranges) {
  4781. let timeRangesObj;
  4782. if (ranges === undefined || ranges.length === 0) {
  4783. timeRangesObj = {
  4784. length: 0,
  4785. start() {
  4786. throw new Error('This TimeRanges object is empty');
  4787. },
  4788. end() {
  4789. throw new Error('This TimeRanges object is empty');
  4790. }
  4791. };
  4792. } else {
  4793. timeRangesObj = {
  4794. length: ranges.length,
  4795. start: getRange.bind(null, 'start', 0, ranges),
  4796. end: getRange.bind(null, 'end', 1, ranges)
  4797. };
  4798. }
  4799. if (window.Symbol && window.Symbol.iterator) {
  4800. timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values();
  4801. }
  4802. return timeRangesObj;
  4803. }
  4804. /**
  4805. * Create a `TimeRange` object which mimics an
  4806. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4807. *
  4808. * @param {number|Array[]} start
  4809. * The start of a single range (a number) or an array of ranges (an
  4810. * array of arrays of two numbers each).
  4811. *
  4812. * @param {number} end
  4813. * The end of a single range. Cannot be used with the array form of
  4814. * the `start` argument.
  4815. *
  4816. * @return {TimeRange}
  4817. */
  4818. function createTimeRanges(start, end) {
  4819. if (Array.isArray(start)) {
  4820. return createTimeRangesObj(start);
  4821. } else if (start === undefined || end === undefined) {
  4822. return createTimeRangesObj();
  4823. }
  4824. return createTimeRangesObj([[start, end]]);
  4825. }
  4826. /**
  4827. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4828. * seconds) will force a number of leading zeros to cover the length of the
  4829. * guide.
  4830. *
  4831. * @private
  4832. * @param {number} seconds
  4833. * Number of seconds to be turned into a string
  4834. *
  4835. * @param {number} guide
  4836. * Number (in seconds) to model the string after
  4837. *
  4838. * @return {string}
  4839. * Time formatted as H:MM:SS or M:SS
  4840. */
  4841. const defaultImplementation = function (seconds, guide) {
  4842. seconds = seconds < 0 ? 0 : seconds;
  4843. let s = Math.floor(seconds % 60);
  4844. let m = Math.floor(seconds / 60 % 60);
  4845. let h = Math.floor(seconds / 3600);
  4846. const gm = Math.floor(guide / 60 % 60);
  4847. const gh = Math.floor(guide / 3600);
  4848. // handle invalid times
  4849. if (isNaN(seconds) || seconds === Infinity) {
  4850. // '-' is false for all relational operators (e.g. <, >=) so this setting
  4851. // will add the minimum number of fields specified by the guide
  4852. h = m = s = '-';
  4853. }
  4854. // Check if we need to show hours
  4855. h = h > 0 || gh > 0 ? h + ':' : '';
  4856. // If hours are showing, we may need to add a leading zero.
  4857. // Always show at least one digit of minutes.
  4858. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  4859. // Check if leading zero is need for seconds
  4860. s = s < 10 ? '0' + s : s;
  4861. return h + m + s;
  4862. };
  4863. // Internal pointer to the current implementation.
  4864. let implementation = defaultImplementation;
  4865. /**
  4866. * Replaces the default formatTime implementation with a custom implementation.
  4867. *
  4868. * @param {Function} customImplementation
  4869. * A function which will be used in place of the default formatTime
  4870. * implementation. Will receive the current time in seconds and the
  4871. * guide (in seconds) as arguments.
  4872. */
  4873. function setFormatTime(customImplementation) {
  4874. implementation = customImplementation;
  4875. }
  4876. /**
  4877. * Resets formatTime to the default implementation.
  4878. */
  4879. function resetFormatTime() {
  4880. implementation = defaultImplementation;
  4881. }
  4882. /**
  4883. * Delegates to either the default time formatting function or a custom
  4884. * function supplied via `setFormatTime`.
  4885. *
  4886. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  4887. * guide (in seconds) will force a number of leading zeros to cover the
  4888. * length of the guide.
  4889. *
  4890. * @example formatTime(125, 600) === "02:05"
  4891. * @param {number} seconds
  4892. * Number of seconds to be turned into a string
  4893. *
  4894. * @param {number} guide
  4895. * Number (in seconds) to model the string after
  4896. *
  4897. * @return {string}
  4898. * Time formatted as H:MM:SS or M:SS
  4899. */
  4900. function formatTime(seconds, guide = seconds) {
  4901. return implementation(seconds, guide);
  4902. }
  4903. var Time = /*#__PURE__*/Object.freeze({
  4904. __proto__: null,
  4905. createTimeRanges: createTimeRanges,
  4906. createTimeRange: createTimeRanges,
  4907. setFormatTime: setFormatTime,
  4908. resetFormatTime: resetFormatTime,
  4909. formatTime: formatTime
  4910. });
  4911. /**
  4912. * @file buffer.js
  4913. * @module buffer
  4914. */
  4915. /**
  4916. * Compute the percentage of the media that has been buffered.
  4917. *
  4918. * @param { import('./time').TimeRange } buffered
  4919. * The current `TimeRanges` object representing buffered time ranges
  4920. *
  4921. * @param {number} duration
  4922. * Total duration of the media
  4923. *
  4924. * @return {number}
  4925. * Percent buffered of the total duration in decimal form.
  4926. */
  4927. function bufferedPercent(buffered, duration) {
  4928. let bufferedDuration = 0;
  4929. let start;
  4930. let end;
  4931. if (!duration) {
  4932. return 0;
  4933. }
  4934. if (!buffered || !buffered.length) {
  4935. buffered = createTimeRanges(0, 0);
  4936. }
  4937. for (let i = 0; i < buffered.length; i++) {
  4938. start = buffered.start(i);
  4939. end = buffered.end(i);
  4940. // buffered end can be bigger than duration by a very small fraction
  4941. if (end > duration) {
  4942. end = duration;
  4943. }
  4944. bufferedDuration += end - start;
  4945. }
  4946. return bufferedDuration / duration;
  4947. }
  4948. /**
  4949. * @file media-error.js
  4950. */
  4951. /**
  4952. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  4953. *
  4954. * @param {number|string|Object|MediaError} value
  4955. * This can be of multiple types:
  4956. * - number: should be a standard error code
  4957. * - string: an error message (the code will be 0)
  4958. * - Object: arbitrary properties
  4959. * - `MediaError` (native): used to populate a video.js `MediaError` object
  4960. * - `MediaError` (video.js): will return itself if it's already a
  4961. * video.js `MediaError` object.
  4962. *
  4963. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  4964. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  4965. *
  4966. * @class MediaError
  4967. */
  4968. function MediaError(value) {
  4969. // Allow redundant calls to this constructor to avoid having `instanceof`
  4970. // checks peppered around the code.
  4971. if (value instanceof MediaError) {
  4972. return value;
  4973. }
  4974. if (typeof value === 'number') {
  4975. this.code = value;
  4976. } else if (typeof value === 'string') {
  4977. // default code is zero, so this is a custom error
  4978. this.message = value;
  4979. } else if (isObject(value)) {
  4980. // We assign the `code` property manually because native `MediaError` objects
  4981. // do not expose it as an own/enumerable property of the object.
  4982. if (typeof value.code === 'number') {
  4983. this.code = value.code;
  4984. }
  4985. Object.assign(this, value);
  4986. }
  4987. if (!this.message) {
  4988. this.message = MediaError.defaultMessages[this.code] || '';
  4989. }
  4990. }
  4991. /**
  4992. * The error code that refers two one of the defined `MediaError` types
  4993. *
  4994. * @type {Number}
  4995. */
  4996. MediaError.prototype.code = 0;
  4997. /**
  4998. * An optional message that to show with the error. Message is not part of the HTML5
  4999. * video spec but allows for more informative custom errors.
  5000. *
  5001. * @type {String}
  5002. */
  5003. MediaError.prototype.message = '';
  5004. /**
  5005. * An optional status code that can be set by plugins to allow even more detail about
  5006. * the error. For example a plugin might provide a specific HTTP status code and an
  5007. * error message for that code. Then when the plugin gets that error this class will
  5008. * know how to display an error message for it. This allows a custom message to show
  5009. * up on the `Player` error overlay.
  5010. *
  5011. * @type {Array}
  5012. */
  5013. MediaError.prototype.status = null;
  5014. /**
  5015. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5016. * specification listed under {@link MediaError} for more information.
  5017. *
  5018. * @enum {array}
  5019. * @readonly
  5020. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5021. * @property {string} 1 - MEDIA_ERR_ABORTED
  5022. * @property {string} 2 - MEDIA_ERR_NETWORK
  5023. * @property {string} 3 - MEDIA_ERR_DECODE
  5024. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5025. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5026. */
  5027. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5028. /**
  5029. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5030. *
  5031. * @type {Array}
  5032. * @constant
  5033. */
  5034. MediaError.defaultMessages = {
  5035. 1: 'You aborted the media playback',
  5036. 2: 'A network error caused the media download to fail part-way.',
  5037. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5038. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5039. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5040. };
  5041. // Add types as properties on MediaError
  5042. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5043. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5044. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5045. // values should be accessible on both the class and instance
  5046. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5047. }
  5048. /**
  5049. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5050. *
  5051. * @param {Object} value
  5052. * An object that may or may not be `Promise`-like.
  5053. *
  5054. * @return {boolean}
  5055. * Whether or not the object is `Promise`-like.
  5056. */
  5057. function isPromise(value) {
  5058. return value !== undefined && value !== null && typeof value.then === 'function';
  5059. }
  5060. /**
  5061. * Silence a Promise-like object.
  5062. *
  5063. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5064. * play promise" rejection error messages.
  5065. *
  5066. * @param {Object} value
  5067. * An object that may or may not be `Promise`-like.
  5068. */
  5069. function silencePromise(value) {
  5070. if (isPromise(value)) {
  5071. value.then(null, e => {});
  5072. }
  5073. }
  5074. /**
  5075. * @file text-track-list-converter.js Utilities for capturing text track state and
  5076. * re-creating tracks based on a capture.
  5077. *
  5078. * @module text-track-list-converter
  5079. */
  5080. /**
  5081. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5082. * represents the {@link TextTrack}'s state.
  5083. *
  5084. * @param {TextTrack} track
  5085. * The text track to query.
  5086. *
  5087. * @return {Object}
  5088. * A serializable javascript representation of the TextTrack.
  5089. * @private
  5090. */
  5091. const trackToJson_ = function (track) {
  5092. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5093. if (track[prop]) {
  5094. acc[prop] = track[prop];
  5095. }
  5096. return acc;
  5097. }, {
  5098. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5099. return {
  5100. startTime: cue.startTime,
  5101. endTime: cue.endTime,
  5102. text: cue.text,
  5103. id: cue.id
  5104. };
  5105. })
  5106. });
  5107. return ret;
  5108. };
  5109. /**
  5110. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5111. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5112. * {@link text-track-list-converter:jsonToTextTracks}.
  5113. *
  5114. * @param { import('../tech/tech').default } tech
  5115. * The tech object to query
  5116. *
  5117. * @return {Array}
  5118. * A serializable javascript representation of the {@link Tech}s
  5119. * {@link TextTrackList}.
  5120. */
  5121. const textTracksToJson = function (tech) {
  5122. const trackEls = tech.$$('track');
  5123. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5124. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5125. const json = trackToJson_(trackEl.track);
  5126. if (trackEl.src) {
  5127. json.src = trackEl.src;
  5128. }
  5129. return json;
  5130. });
  5131. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5132. return trackObjs.indexOf(track) === -1;
  5133. }).map(trackToJson_));
  5134. };
  5135. /**
  5136. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5137. * object {@link TextTrack} representations.
  5138. *
  5139. * @param {Array} json
  5140. * An array of `TextTrack` representation objects, like those that would be
  5141. * produced by `textTracksToJson`.
  5142. *
  5143. * @param {Tech} tech
  5144. * The `Tech` to create the `TextTrack`s on.
  5145. */
  5146. const jsonToTextTracks = function (json, tech) {
  5147. json.forEach(function (track) {
  5148. const addedTrack = tech.addRemoteTextTrack(track).track;
  5149. if (!track.src && track.cues) {
  5150. track.cues.forEach(cue => addedTrack.addCue(cue));
  5151. }
  5152. });
  5153. return tech.textTracks();
  5154. };
  5155. var textTrackConverter = {
  5156. textTracksToJson,
  5157. jsonToTextTracks,
  5158. trackToJson_
  5159. };
  5160. /**
  5161. * @file modal-dialog.js
  5162. */
  5163. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5164. /**
  5165. * The `ModalDialog` displays over the video and its controls, which blocks
  5166. * interaction with the player until it is closed.
  5167. *
  5168. * Modal dialogs include a "Close" button and will close when that button
  5169. * is activated - or when ESC is pressed anywhere.
  5170. *
  5171. * @extends Component
  5172. */
  5173. class ModalDialog extends Component {
  5174. /**
  5175. * Create an instance of this class.
  5176. *
  5177. * @param { import('./player').default } player
  5178. * The `Player` that this class should be attached to.
  5179. *
  5180. * @param {Object} [options]
  5181. * The key/value store of player options.
  5182. *
  5183. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5184. * Provide customized content for this modal.
  5185. *
  5186. * @param {string} [options.description]
  5187. * A text description for the modal, primarily for accessibility.
  5188. *
  5189. * @param {boolean} [options.fillAlways=false]
  5190. * Normally, modals are automatically filled only the first time
  5191. * they open. This tells the modal to refresh its content
  5192. * every time it opens.
  5193. *
  5194. * @param {string} [options.label]
  5195. * A text label for the modal, primarily for accessibility.
  5196. *
  5197. * @param {boolean} [options.pauseOnOpen=true]
  5198. * If `true`, playback will will be paused if playing when
  5199. * the modal opens, and resumed when it closes.
  5200. *
  5201. * @param {boolean} [options.temporary=true]
  5202. * If `true`, the modal can only be opened once; it will be
  5203. * disposed as soon as it's closed.
  5204. *
  5205. * @param {boolean} [options.uncloseable=false]
  5206. * If `true`, the user will not be able to close the modal
  5207. * through the UI in the normal ways. Programmatic closing is
  5208. * still possible.
  5209. */
  5210. constructor(player, options) {
  5211. super(player, options);
  5212. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5213. this.close_ = e => this.close(e);
  5214. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5215. this.closeable(!this.options_.uncloseable);
  5216. this.content(this.options_.content);
  5217. // Make sure the contentEl is defined AFTER any children are initialized
  5218. // because we only want the contents of the modal in the contentEl
  5219. // (not the UI elements like the close button).
  5220. this.contentEl_ = createEl('div', {
  5221. className: `${MODAL_CLASS_NAME}-content`
  5222. }, {
  5223. role: 'document'
  5224. });
  5225. this.descEl_ = createEl('p', {
  5226. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5227. id: this.el().getAttribute('aria-describedby')
  5228. });
  5229. textContent(this.descEl_, this.description());
  5230. this.el_.appendChild(this.descEl_);
  5231. this.el_.appendChild(this.contentEl_);
  5232. }
  5233. /**
  5234. * Create the `ModalDialog`'s DOM element
  5235. *
  5236. * @return {Element}
  5237. * The DOM element that gets created.
  5238. */
  5239. createEl() {
  5240. return super.createEl('div', {
  5241. className: this.buildCSSClass(),
  5242. tabIndex: -1
  5243. }, {
  5244. 'aria-describedby': `${this.id()}_description`,
  5245. 'aria-hidden': 'true',
  5246. 'aria-label': this.label(),
  5247. 'role': 'dialog'
  5248. });
  5249. }
  5250. dispose() {
  5251. this.contentEl_ = null;
  5252. this.descEl_ = null;
  5253. this.previouslyActiveEl_ = null;
  5254. super.dispose();
  5255. }
  5256. /**
  5257. * Builds the default DOM `className`.
  5258. *
  5259. * @return {string}
  5260. * The DOM `className` for this object.
  5261. */
  5262. buildCSSClass() {
  5263. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5264. }
  5265. /**
  5266. * Returns the label string for this modal. Primarily used for accessibility.
  5267. *
  5268. * @return {string}
  5269. * the localized or raw label of this modal.
  5270. */
  5271. label() {
  5272. return this.localize(this.options_.label || 'Modal Window');
  5273. }
  5274. /**
  5275. * Returns the description string for this modal. Primarily used for
  5276. * accessibility.
  5277. *
  5278. * @return {string}
  5279. * The localized or raw description of this modal.
  5280. */
  5281. description() {
  5282. let desc = this.options_.description || this.localize('This is a modal window.');
  5283. // Append a universal closeability message if the modal is closeable.
  5284. if (this.closeable()) {
  5285. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5286. }
  5287. return desc;
  5288. }
  5289. /**
  5290. * Opens the modal.
  5291. *
  5292. * @fires ModalDialog#beforemodalopen
  5293. * @fires ModalDialog#modalopen
  5294. */
  5295. open() {
  5296. if (!this.opened_) {
  5297. const player = this.player();
  5298. /**
  5299. * Fired just before a `ModalDialog` is opened.
  5300. *
  5301. * @event ModalDialog#beforemodalopen
  5302. * @type {Event}
  5303. */
  5304. this.trigger('beforemodalopen');
  5305. this.opened_ = true;
  5306. // Fill content if the modal has never opened before and
  5307. // never been filled.
  5308. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5309. this.fill();
  5310. }
  5311. // If the player was playing, pause it and take note of its previously
  5312. // playing state.
  5313. this.wasPlaying_ = !player.paused();
  5314. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5315. player.pause();
  5316. }
  5317. this.on('keydown', this.handleKeyDown_);
  5318. // Hide controls and note if they were enabled.
  5319. this.hadControls_ = player.controls();
  5320. player.controls(false);
  5321. this.show();
  5322. this.conditionalFocus_();
  5323. this.el().setAttribute('aria-hidden', 'false');
  5324. /**
  5325. * Fired just after a `ModalDialog` is opened.
  5326. *
  5327. * @event ModalDialog#modalopen
  5328. * @type {Event}
  5329. */
  5330. this.trigger('modalopen');
  5331. this.hasBeenOpened_ = true;
  5332. }
  5333. }
  5334. /**
  5335. * If the `ModalDialog` is currently open or closed.
  5336. *
  5337. * @param {boolean} [value]
  5338. * If given, it will open (`true`) or close (`false`) the modal.
  5339. *
  5340. * @return {boolean}
  5341. * the current open state of the modaldialog
  5342. */
  5343. opened(value) {
  5344. if (typeof value === 'boolean') {
  5345. this[value ? 'open' : 'close']();
  5346. }
  5347. return this.opened_;
  5348. }
  5349. /**
  5350. * Closes the modal, does nothing if the `ModalDialog` is
  5351. * not open.
  5352. *
  5353. * @fires ModalDialog#beforemodalclose
  5354. * @fires ModalDialog#modalclose
  5355. */
  5356. close() {
  5357. if (!this.opened_) {
  5358. return;
  5359. }
  5360. const player = this.player();
  5361. /**
  5362. * Fired just before a `ModalDialog` is closed.
  5363. *
  5364. * @event ModalDialog#beforemodalclose
  5365. * @type {Event}
  5366. */
  5367. this.trigger('beforemodalclose');
  5368. this.opened_ = false;
  5369. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5370. player.play();
  5371. }
  5372. this.off('keydown', this.handleKeyDown_);
  5373. if (this.hadControls_) {
  5374. player.controls(true);
  5375. }
  5376. this.hide();
  5377. this.el().setAttribute('aria-hidden', 'true');
  5378. /**
  5379. * Fired just after a `ModalDialog` is closed.
  5380. *
  5381. * @event ModalDialog#modalclose
  5382. * @type {Event}
  5383. */
  5384. this.trigger('modalclose');
  5385. this.conditionalBlur_();
  5386. if (this.options_.temporary) {
  5387. this.dispose();
  5388. }
  5389. }
  5390. /**
  5391. * Check to see if the `ModalDialog` is closeable via the UI.
  5392. *
  5393. * @param {boolean} [value]
  5394. * If given as a boolean, it will set the `closeable` option.
  5395. *
  5396. * @return {boolean}
  5397. * Returns the final value of the closable option.
  5398. */
  5399. closeable(value) {
  5400. if (typeof value === 'boolean') {
  5401. const closeable = this.closeable_ = !!value;
  5402. let close = this.getChild('closeButton');
  5403. // If this is being made closeable and has no close button, add one.
  5404. if (closeable && !close) {
  5405. // The close button should be a child of the modal - not its
  5406. // content element, so temporarily change the content element.
  5407. const temp = this.contentEl_;
  5408. this.contentEl_ = this.el_;
  5409. close = this.addChild('closeButton', {
  5410. controlText: 'Close Modal Dialog'
  5411. });
  5412. this.contentEl_ = temp;
  5413. this.on(close, 'close', this.close_);
  5414. }
  5415. // If this is being made uncloseable and has a close button, remove it.
  5416. if (!closeable && close) {
  5417. this.off(close, 'close', this.close_);
  5418. this.removeChild(close);
  5419. close.dispose();
  5420. }
  5421. }
  5422. return this.closeable_;
  5423. }
  5424. /**
  5425. * Fill the modal's content element with the modal's "content" option.
  5426. * The content element will be emptied before this change takes place.
  5427. */
  5428. fill() {
  5429. this.fillWith(this.content());
  5430. }
  5431. /**
  5432. * Fill the modal's content element with arbitrary content.
  5433. * The content element will be emptied before this change takes place.
  5434. *
  5435. * @fires ModalDialog#beforemodalfill
  5436. * @fires ModalDialog#modalfill
  5437. *
  5438. * @param { import('./utils/dom').ContentDescriptor} [content]
  5439. * The same rules apply to this as apply to the `content` option.
  5440. */
  5441. fillWith(content) {
  5442. const contentEl = this.contentEl();
  5443. const parentEl = contentEl.parentNode;
  5444. const nextSiblingEl = contentEl.nextSibling;
  5445. /**
  5446. * Fired just before a `ModalDialog` is filled with content.
  5447. *
  5448. * @event ModalDialog#beforemodalfill
  5449. * @type {Event}
  5450. */
  5451. this.trigger('beforemodalfill');
  5452. this.hasBeenFilled_ = true;
  5453. // Detach the content element from the DOM before performing
  5454. // manipulation to avoid modifying the live DOM multiple times.
  5455. parentEl.removeChild(contentEl);
  5456. this.empty();
  5457. insertContent(contentEl, content);
  5458. /**
  5459. * Fired just after a `ModalDialog` is filled with content.
  5460. *
  5461. * @event ModalDialog#modalfill
  5462. * @type {Event}
  5463. */
  5464. this.trigger('modalfill');
  5465. // Re-inject the re-filled content element.
  5466. if (nextSiblingEl) {
  5467. parentEl.insertBefore(contentEl, nextSiblingEl);
  5468. } else {
  5469. parentEl.appendChild(contentEl);
  5470. }
  5471. // make sure that the close button is last in the dialog DOM
  5472. const closeButton = this.getChild('closeButton');
  5473. if (closeButton) {
  5474. parentEl.appendChild(closeButton.el_);
  5475. }
  5476. }
  5477. /**
  5478. * Empties the content element. This happens anytime the modal is filled.
  5479. *
  5480. * @fires ModalDialog#beforemodalempty
  5481. * @fires ModalDialog#modalempty
  5482. */
  5483. empty() {
  5484. /**
  5485. * Fired just before a `ModalDialog` is emptied.
  5486. *
  5487. * @event ModalDialog#beforemodalempty
  5488. * @type {Event}
  5489. */
  5490. this.trigger('beforemodalempty');
  5491. emptyEl(this.contentEl());
  5492. /**
  5493. * Fired just after a `ModalDialog` is emptied.
  5494. *
  5495. * @event ModalDialog#modalempty
  5496. * @type {Event}
  5497. */
  5498. this.trigger('modalempty');
  5499. }
  5500. /**
  5501. * Gets or sets the modal content, which gets normalized before being
  5502. * rendered into the DOM.
  5503. *
  5504. * This does not update the DOM or fill the modal, but it is called during
  5505. * that process.
  5506. *
  5507. * @param { import('./utils/dom').ContentDescriptor} [value]
  5508. * If defined, sets the internal content value to be used on the
  5509. * next call(s) to `fill`. This value is normalized before being
  5510. * inserted. To "clear" the internal content value, pass `null`.
  5511. *
  5512. * @return { import('./utils/dom').ContentDescriptor}
  5513. * The current content of the modal dialog
  5514. */
  5515. content(value) {
  5516. if (typeof value !== 'undefined') {
  5517. this.content_ = value;
  5518. }
  5519. return this.content_;
  5520. }
  5521. /**
  5522. * conditionally focus the modal dialog if focus was previously on the player.
  5523. *
  5524. * @private
  5525. */
  5526. conditionalFocus_() {
  5527. const activeEl = document.activeElement;
  5528. const playerEl = this.player_.el_;
  5529. this.previouslyActiveEl_ = null;
  5530. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5531. this.previouslyActiveEl_ = activeEl;
  5532. this.focus();
  5533. }
  5534. }
  5535. /**
  5536. * conditionally blur the element and refocus the last focused element
  5537. *
  5538. * @private
  5539. */
  5540. conditionalBlur_() {
  5541. if (this.previouslyActiveEl_) {
  5542. this.previouslyActiveEl_.focus();
  5543. this.previouslyActiveEl_ = null;
  5544. }
  5545. }
  5546. /**
  5547. * Keydown handler. Attached when modal is focused.
  5548. *
  5549. * @listens keydown
  5550. */
  5551. handleKeyDown(event) {
  5552. // Do not allow keydowns to reach out of the modal dialog.
  5553. event.stopPropagation();
  5554. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5555. event.preventDefault();
  5556. this.close();
  5557. return;
  5558. }
  5559. // exit early if it isn't a tab key
  5560. if (!keycode.isEventKey(event, 'Tab')) {
  5561. return;
  5562. }
  5563. const focusableEls = this.focusableEls_();
  5564. const activeEl = this.el_.querySelector(':focus');
  5565. let focusIndex;
  5566. for (let i = 0; i < focusableEls.length; i++) {
  5567. if (activeEl === focusableEls[i]) {
  5568. focusIndex = i;
  5569. break;
  5570. }
  5571. }
  5572. if (document.activeElement === this.el_) {
  5573. focusIndex = 0;
  5574. }
  5575. if (event.shiftKey && focusIndex === 0) {
  5576. focusableEls[focusableEls.length - 1].focus();
  5577. event.preventDefault();
  5578. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5579. focusableEls[0].focus();
  5580. event.preventDefault();
  5581. }
  5582. }
  5583. /**
  5584. * get all focusable elements
  5585. *
  5586. * @private
  5587. */
  5588. focusableEls_() {
  5589. const allChildren = this.el_.querySelectorAll('*');
  5590. return Array.prototype.filter.call(allChildren, child => {
  5591. return (child instanceof window.HTMLAnchorElement || child instanceof window.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window.HTMLInputElement || child instanceof window.HTMLSelectElement || child instanceof window.HTMLTextAreaElement || child instanceof window.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window.HTMLIFrameElement || child instanceof window.HTMLObjectElement || child instanceof window.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  5592. });
  5593. }
  5594. }
  5595. /**
  5596. * Default options for `ModalDialog` default options.
  5597. *
  5598. * @type {Object}
  5599. * @private
  5600. */
  5601. ModalDialog.prototype.options_ = {
  5602. pauseOnOpen: true,
  5603. temporary: true
  5604. };
  5605. Component.registerComponent('ModalDialog', ModalDialog);
  5606. /**
  5607. * @file track-list.js
  5608. */
  5609. /**
  5610. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5611. * {@link VideoTrackList}
  5612. *
  5613. * @extends EventTarget
  5614. */
  5615. class TrackList extends EventTarget {
  5616. /**
  5617. * Create an instance of this class
  5618. *
  5619. * @param { import('./track').default[] } tracks
  5620. * A list of tracks to initialize the list with.
  5621. *
  5622. * @abstract
  5623. */
  5624. constructor(tracks = []) {
  5625. super();
  5626. this.tracks_ = [];
  5627. /**
  5628. * @memberof TrackList
  5629. * @member {number} length
  5630. * The current number of `Track`s in the this Trackist.
  5631. * @instance
  5632. */
  5633. Object.defineProperty(this, 'length', {
  5634. get() {
  5635. return this.tracks_.length;
  5636. }
  5637. });
  5638. for (let i = 0; i < tracks.length; i++) {
  5639. this.addTrack(tracks[i]);
  5640. }
  5641. }
  5642. /**
  5643. * Add a {@link Track} to the `TrackList`
  5644. *
  5645. * @param { import('./track').default } track
  5646. * The audio, video, or text track to add to the list.
  5647. *
  5648. * @fires TrackList#addtrack
  5649. */
  5650. addTrack(track) {
  5651. const index = this.tracks_.length;
  5652. if (!('' + index in this)) {
  5653. Object.defineProperty(this, index, {
  5654. get() {
  5655. return this.tracks_[index];
  5656. }
  5657. });
  5658. }
  5659. // Do not add duplicate tracks
  5660. if (this.tracks_.indexOf(track) === -1) {
  5661. this.tracks_.push(track);
  5662. /**
  5663. * Triggered when a track is added to a track list.
  5664. *
  5665. * @event TrackList#addtrack
  5666. * @type {Event}
  5667. * @property {Track} track
  5668. * A reference to track that was added.
  5669. */
  5670. this.trigger({
  5671. track,
  5672. type: 'addtrack',
  5673. target: this
  5674. });
  5675. }
  5676. /**
  5677. * Triggered when a track label is changed.
  5678. *
  5679. * @event TrackList#addtrack
  5680. * @type {Event}
  5681. * @property {Track} track
  5682. * A reference to track that was added.
  5683. */
  5684. track.labelchange_ = () => {
  5685. this.trigger({
  5686. track,
  5687. type: 'labelchange',
  5688. target: this
  5689. });
  5690. };
  5691. if (isEvented(track)) {
  5692. track.addEventListener('labelchange', track.labelchange_);
  5693. }
  5694. }
  5695. /**
  5696. * Remove a {@link Track} from the `TrackList`
  5697. *
  5698. * @param { import('./track').default } rtrack
  5699. * The audio, video, or text track to remove from the list.
  5700. *
  5701. * @fires TrackList#removetrack
  5702. */
  5703. removeTrack(rtrack) {
  5704. let track;
  5705. for (let i = 0, l = this.length; i < l; i++) {
  5706. if (this[i] === rtrack) {
  5707. track = this[i];
  5708. if (track.off) {
  5709. track.off();
  5710. }
  5711. this.tracks_.splice(i, 1);
  5712. break;
  5713. }
  5714. }
  5715. if (!track) {
  5716. return;
  5717. }
  5718. /**
  5719. * Triggered when a track is removed from track list.
  5720. *
  5721. * @event TrackList#removetrack
  5722. * @type {Event}
  5723. * @property {Track} track
  5724. * A reference to track that was removed.
  5725. */
  5726. this.trigger({
  5727. track,
  5728. type: 'removetrack',
  5729. target: this
  5730. });
  5731. }
  5732. /**
  5733. * Get a Track from the TrackList by a tracks id
  5734. *
  5735. * @param {string} id - the id of the track to get
  5736. * @method getTrackById
  5737. * @return { import('./track').default }
  5738. * @private
  5739. */
  5740. getTrackById(id) {
  5741. let result = null;
  5742. for (let i = 0, l = this.length; i < l; i++) {
  5743. const track = this[i];
  5744. if (track.id === id) {
  5745. result = track;
  5746. break;
  5747. }
  5748. }
  5749. return result;
  5750. }
  5751. }
  5752. /**
  5753. * Triggered when a different track is selected/enabled.
  5754. *
  5755. * @event TrackList#change
  5756. * @type {Event}
  5757. */
  5758. /**
  5759. * Events that can be called with on + eventName. See {@link EventHandler}.
  5760. *
  5761. * @property {Object} TrackList#allowedEvents_
  5762. * @private
  5763. */
  5764. TrackList.prototype.allowedEvents_ = {
  5765. change: 'change',
  5766. addtrack: 'addtrack',
  5767. removetrack: 'removetrack',
  5768. labelchange: 'labelchange'
  5769. };
  5770. // emulate attribute EventHandler support to allow for feature detection
  5771. for (const event in TrackList.prototype.allowedEvents_) {
  5772. TrackList.prototype['on' + event] = null;
  5773. }
  5774. /**
  5775. * @file audio-track-list.js
  5776. */
  5777. /**
  5778. * Anywhere we call this function we diverge from the spec
  5779. * as we only support one enabled audiotrack at a time
  5780. *
  5781. * @param {AudioTrackList} list
  5782. * list to work on
  5783. *
  5784. * @param { import('./audio-track').default } track
  5785. * The track to skip
  5786. *
  5787. * @private
  5788. */
  5789. const disableOthers$1 = function (list, track) {
  5790. for (let i = 0; i < list.length; i++) {
  5791. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5792. continue;
  5793. }
  5794. // another audio track is enabled, disable it
  5795. list[i].enabled = false;
  5796. }
  5797. };
  5798. /**
  5799. * The current list of {@link AudioTrack} for a media file.
  5800. *
  5801. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5802. * @extends TrackList
  5803. */
  5804. class AudioTrackList extends TrackList {
  5805. /**
  5806. * Create an instance of this class.
  5807. *
  5808. * @param {AudioTrack[]} [tracks=[]]
  5809. * A list of `AudioTrack` to instantiate the list with.
  5810. */
  5811. constructor(tracks = []) {
  5812. // make sure only 1 track is enabled
  5813. // sorted from last index to first index
  5814. for (let i = tracks.length - 1; i >= 0; i--) {
  5815. if (tracks[i].enabled) {
  5816. disableOthers$1(tracks, tracks[i]);
  5817. break;
  5818. }
  5819. }
  5820. super(tracks);
  5821. this.changing_ = false;
  5822. }
  5823. /**
  5824. * Add an {@link AudioTrack} to the `AudioTrackList`.
  5825. *
  5826. * @param { import('./audio-track').default } track
  5827. * The AudioTrack to add to the list
  5828. *
  5829. * @fires TrackList#addtrack
  5830. */
  5831. addTrack(track) {
  5832. if (track.enabled) {
  5833. disableOthers$1(this, track);
  5834. }
  5835. super.addTrack(track);
  5836. // native tracks don't have this
  5837. if (!track.addEventListener) {
  5838. return;
  5839. }
  5840. track.enabledChange_ = () => {
  5841. // when we are disabling other tracks (since we don't support
  5842. // more than one track at a time) we will set changing_
  5843. // to true so that we don't trigger additional change events
  5844. if (this.changing_) {
  5845. return;
  5846. }
  5847. this.changing_ = true;
  5848. disableOthers$1(this, track);
  5849. this.changing_ = false;
  5850. this.trigger('change');
  5851. };
  5852. /**
  5853. * @listens AudioTrack#enabledchange
  5854. * @fires TrackList#change
  5855. */
  5856. track.addEventListener('enabledchange', track.enabledChange_);
  5857. }
  5858. removeTrack(rtrack) {
  5859. super.removeTrack(rtrack);
  5860. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  5861. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  5862. rtrack.enabledChange_ = null;
  5863. }
  5864. }
  5865. }
  5866. /**
  5867. * @file video-track-list.js
  5868. */
  5869. /**
  5870. * Un-select all other {@link VideoTrack}s that are selected.
  5871. *
  5872. * @param {VideoTrackList} list
  5873. * list to work on
  5874. *
  5875. * @param { import('./video-track').default } track
  5876. * The track to skip
  5877. *
  5878. * @private
  5879. */
  5880. const disableOthers = function (list, track) {
  5881. for (let i = 0; i < list.length; i++) {
  5882. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5883. continue;
  5884. }
  5885. // another video track is enabled, disable it
  5886. list[i].selected = false;
  5887. }
  5888. };
  5889. /**
  5890. * The current list of {@link VideoTrack} for a video.
  5891. *
  5892. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  5893. * @extends TrackList
  5894. */
  5895. class VideoTrackList extends TrackList {
  5896. /**
  5897. * Create an instance of this class.
  5898. *
  5899. * @param {VideoTrack[]} [tracks=[]]
  5900. * A list of `VideoTrack` to instantiate the list with.
  5901. */
  5902. constructor(tracks = []) {
  5903. // make sure only 1 track is enabled
  5904. // sorted from last index to first index
  5905. for (let i = tracks.length - 1; i >= 0; i--) {
  5906. if (tracks[i].selected) {
  5907. disableOthers(tracks, tracks[i]);
  5908. break;
  5909. }
  5910. }
  5911. super(tracks);
  5912. this.changing_ = false;
  5913. /**
  5914. * @member {number} VideoTrackList#selectedIndex
  5915. * The current index of the selected {@link VideoTrack`}.
  5916. */
  5917. Object.defineProperty(this, 'selectedIndex', {
  5918. get() {
  5919. for (let i = 0; i < this.length; i++) {
  5920. if (this[i].selected) {
  5921. return i;
  5922. }
  5923. }
  5924. return -1;
  5925. },
  5926. set() {}
  5927. });
  5928. }
  5929. /**
  5930. * Add a {@link VideoTrack} to the `VideoTrackList`.
  5931. *
  5932. * @param { import('./video-track').default } track
  5933. * The VideoTrack to add to the list
  5934. *
  5935. * @fires TrackList#addtrack
  5936. */
  5937. addTrack(track) {
  5938. if (track.selected) {
  5939. disableOthers(this, track);
  5940. }
  5941. super.addTrack(track);
  5942. // native tracks don't have this
  5943. if (!track.addEventListener) {
  5944. return;
  5945. }
  5946. track.selectedChange_ = () => {
  5947. if (this.changing_) {
  5948. return;
  5949. }
  5950. this.changing_ = true;
  5951. disableOthers(this, track);
  5952. this.changing_ = false;
  5953. this.trigger('change');
  5954. };
  5955. /**
  5956. * @listens VideoTrack#selectedchange
  5957. * @fires TrackList#change
  5958. */
  5959. track.addEventListener('selectedchange', track.selectedChange_);
  5960. }
  5961. removeTrack(rtrack) {
  5962. super.removeTrack(rtrack);
  5963. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  5964. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  5965. rtrack.selectedChange_ = null;
  5966. }
  5967. }
  5968. }
  5969. /**
  5970. * @file text-track-list.js
  5971. */
  5972. /**
  5973. * The current list of {@link TextTrack} for a media file.
  5974. *
  5975. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  5976. * @extends TrackList
  5977. */
  5978. class TextTrackList extends TrackList {
  5979. /**
  5980. * Add a {@link TextTrack} to the `TextTrackList`
  5981. *
  5982. * @param { import('./text-track').default } track
  5983. * The text track to add to the list.
  5984. *
  5985. * @fires TrackList#addtrack
  5986. */
  5987. addTrack(track) {
  5988. super.addTrack(track);
  5989. if (!this.queueChange_) {
  5990. this.queueChange_ = () => this.queueTrigger('change');
  5991. }
  5992. if (!this.triggerSelectedlanguagechange) {
  5993. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  5994. }
  5995. /**
  5996. * @listens TextTrack#modechange
  5997. * @fires TrackList#change
  5998. */
  5999. track.addEventListener('modechange', this.queueChange_);
  6000. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6001. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6002. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6003. }
  6004. }
  6005. removeTrack(rtrack) {
  6006. super.removeTrack(rtrack);
  6007. // manually remove the event handlers we added
  6008. if (rtrack.removeEventListener) {
  6009. if (this.queueChange_) {
  6010. rtrack.removeEventListener('modechange', this.queueChange_);
  6011. }
  6012. if (this.selectedlanguagechange_) {
  6013. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6014. }
  6015. }
  6016. }
  6017. }
  6018. /**
  6019. * @file html-track-element-list.js
  6020. */
  6021. /**
  6022. * The current list of {@link HtmlTrackElement}s.
  6023. */
  6024. class HtmlTrackElementList {
  6025. /**
  6026. * Create an instance of this class.
  6027. *
  6028. * @param {HtmlTrackElement[]} [tracks=[]]
  6029. * A list of `HtmlTrackElement` to instantiate the list with.
  6030. */
  6031. constructor(trackElements = []) {
  6032. this.trackElements_ = [];
  6033. /**
  6034. * @memberof HtmlTrackElementList
  6035. * @member {number} length
  6036. * The current number of `Track`s in the this Trackist.
  6037. * @instance
  6038. */
  6039. Object.defineProperty(this, 'length', {
  6040. get() {
  6041. return this.trackElements_.length;
  6042. }
  6043. });
  6044. for (let i = 0, length = trackElements.length; i < length; i++) {
  6045. this.addTrackElement_(trackElements[i]);
  6046. }
  6047. }
  6048. /**
  6049. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6050. *
  6051. * @param {HtmlTrackElement} trackElement
  6052. * The track element to add to the list.
  6053. *
  6054. * @private
  6055. */
  6056. addTrackElement_(trackElement) {
  6057. const index = this.trackElements_.length;
  6058. if (!('' + index in this)) {
  6059. Object.defineProperty(this, index, {
  6060. get() {
  6061. return this.trackElements_[index];
  6062. }
  6063. });
  6064. }
  6065. // Do not add duplicate elements
  6066. if (this.trackElements_.indexOf(trackElement) === -1) {
  6067. this.trackElements_.push(trackElement);
  6068. }
  6069. }
  6070. /**
  6071. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6072. * {@link TextTrack}.
  6073. *
  6074. * @param {TextTrack} track
  6075. * The track associated with a track element.
  6076. *
  6077. * @return {HtmlTrackElement|undefined}
  6078. * The track element that was found or undefined.
  6079. *
  6080. * @private
  6081. */
  6082. getTrackElementByTrack_(track) {
  6083. let trackElement_;
  6084. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6085. if (track === this.trackElements_[i].track) {
  6086. trackElement_ = this.trackElements_[i];
  6087. break;
  6088. }
  6089. }
  6090. return trackElement_;
  6091. }
  6092. /**
  6093. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6094. *
  6095. * @param {HtmlTrackElement} trackElement
  6096. * The track element to remove from the list.
  6097. *
  6098. * @private
  6099. */
  6100. removeTrackElement_(trackElement) {
  6101. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6102. if (trackElement === this.trackElements_[i]) {
  6103. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6104. this.trackElements_[i].track.off();
  6105. }
  6106. if (typeof this.trackElements_[i].off === 'function') {
  6107. this.trackElements_[i].off();
  6108. }
  6109. this.trackElements_.splice(i, 1);
  6110. break;
  6111. }
  6112. }
  6113. }
  6114. }
  6115. /**
  6116. * @file text-track-cue-list.js
  6117. */
  6118. /**
  6119. * @typedef {Object} TextTrackCueList~TextTrackCue
  6120. *
  6121. * @property {string} id
  6122. * The unique id for this text track cue
  6123. *
  6124. * @property {number} startTime
  6125. * The start time for this text track cue
  6126. *
  6127. * @property {number} endTime
  6128. * The end time for this text track cue
  6129. *
  6130. * @property {boolean} pauseOnExit
  6131. * Pause when the end time is reached if true.
  6132. *
  6133. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6134. */
  6135. /**
  6136. * A List of TextTrackCues.
  6137. *
  6138. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6139. */
  6140. class TextTrackCueList {
  6141. /**
  6142. * Create an instance of this class..
  6143. *
  6144. * @param {Array} cues
  6145. * A list of cues to be initialized with
  6146. */
  6147. constructor(cues) {
  6148. TextTrackCueList.prototype.setCues_.call(this, cues);
  6149. /**
  6150. * @memberof TextTrackCueList
  6151. * @member {number} length
  6152. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6153. * @instance
  6154. */
  6155. Object.defineProperty(this, 'length', {
  6156. get() {
  6157. return this.length_;
  6158. }
  6159. });
  6160. }
  6161. /**
  6162. * A setter for cues in this list. Creates getters
  6163. * an an index for the cues.
  6164. *
  6165. * @param {Array} cues
  6166. * An array of cues to set
  6167. *
  6168. * @private
  6169. */
  6170. setCues_(cues) {
  6171. const oldLength = this.length || 0;
  6172. let i = 0;
  6173. const l = cues.length;
  6174. this.cues_ = cues;
  6175. this.length_ = cues.length;
  6176. const defineProp = function (index) {
  6177. if (!('' + index in this)) {
  6178. Object.defineProperty(this, '' + index, {
  6179. get() {
  6180. return this.cues_[index];
  6181. }
  6182. });
  6183. }
  6184. };
  6185. if (oldLength < l) {
  6186. i = oldLength;
  6187. for (; i < l; i++) {
  6188. defineProp.call(this, i);
  6189. }
  6190. }
  6191. }
  6192. /**
  6193. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6194. *
  6195. * @param {string} id
  6196. * The id of the cue that should be searched for.
  6197. *
  6198. * @return {TextTrackCueList~TextTrackCue|null}
  6199. * A single cue or null if none was found.
  6200. */
  6201. getCueById(id) {
  6202. let result = null;
  6203. for (let i = 0, l = this.length; i < l; i++) {
  6204. const cue = this[i];
  6205. if (cue.id === id) {
  6206. result = cue;
  6207. break;
  6208. }
  6209. }
  6210. return result;
  6211. }
  6212. }
  6213. /**
  6214. * @file track-kinds.js
  6215. */
  6216. /**
  6217. * All possible `VideoTrackKind`s
  6218. *
  6219. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6220. * @typedef VideoTrack~Kind
  6221. * @enum
  6222. */
  6223. const VideoTrackKind = {
  6224. alternative: 'alternative',
  6225. captions: 'captions',
  6226. main: 'main',
  6227. sign: 'sign',
  6228. subtitles: 'subtitles',
  6229. commentary: 'commentary'
  6230. };
  6231. /**
  6232. * All possible `AudioTrackKind`s
  6233. *
  6234. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6235. * @typedef AudioTrack~Kind
  6236. * @enum
  6237. */
  6238. const AudioTrackKind = {
  6239. 'alternative': 'alternative',
  6240. 'descriptions': 'descriptions',
  6241. 'main': 'main',
  6242. 'main-desc': 'main-desc',
  6243. 'translation': 'translation',
  6244. 'commentary': 'commentary'
  6245. };
  6246. /**
  6247. * All possible `TextTrackKind`s
  6248. *
  6249. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6250. * @typedef TextTrack~Kind
  6251. * @enum
  6252. */
  6253. const TextTrackKind = {
  6254. subtitles: 'subtitles',
  6255. captions: 'captions',
  6256. descriptions: 'descriptions',
  6257. chapters: 'chapters',
  6258. metadata: 'metadata'
  6259. };
  6260. /**
  6261. * All possible `TextTrackMode`s
  6262. *
  6263. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6264. * @typedef TextTrack~Mode
  6265. * @enum
  6266. */
  6267. const TextTrackMode = {
  6268. disabled: 'disabled',
  6269. hidden: 'hidden',
  6270. showing: 'showing'
  6271. };
  6272. /**
  6273. * @file track.js
  6274. */
  6275. /**
  6276. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6277. * {@link VideoTrack}, and {@link TextTrack}.
  6278. *
  6279. * > Note: This class should not be used directly
  6280. *
  6281. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6282. * @extends EventTarget
  6283. * @abstract
  6284. */
  6285. class Track extends EventTarget {
  6286. /**
  6287. * Create an instance of this class.
  6288. *
  6289. * @param {Object} [options={}]
  6290. * Object of option names and values
  6291. *
  6292. * @param {string} [options.kind='']
  6293. * A valid kind for the track type you are creating.
  6294. *
  6295. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6296. * A unique id for this AudioTrack.
  6297. *
  6298. * @param {string} [options.label='']
  6299. * The menu label for this track.
  6300. *
  6301. * @param {string} [options.language='']
  6302. * A valid two character language code.
  6303. *
  6304. * @abstract
  6305. */
  6306. constructor(options = {}) {
  6307. super();
  6308. const trackProps = {
  6309. id: options.id || 'vjs_track_' + newGUID(),
  6310. kind: options.kind || '',
  6311. language: options.language || ''
  6312. };
  6313. let label = options.label || '';
  6314. /**
  6315. * @memberof Track
  6316. * @member {string} id
  6317. * The id of this track. Cannot be changed after creation.
  6318. * @instance
  6319. *
  6320. * @readonly
  6321. */
  6322. /**
  6323. * @memberof Track
  6324. * @member {string} kind
  6325. * The kind of track that this is. Cannot be changed after creation.
  6326. * @instance
  6327. *
  6328. * @readonly
  6329. */
  6330. /**
  6331. * @memberof Track
  6332. * @member {string} language
  6333. * The two letter language code for this track. Cannot be changed after
  6334. * creation.
  6335. * @instance
  6336. *
  6337. * @readonly
  6338. */
  6339. for (const key in trackProps) {
  6340. Object.defineProperty(this, key, {
  6341. get() {
  6342. return trackProps[key];
  6343. },
  6344. set() {}
  6345. });
  6346. }
  6347. /**
  6348. * @memberof Track
  6349. * @member {string} label
  6350. * The label of this track. Cannot be changed after creation.
  6351. * @instance
  6352. *
  6353. * @fires Track#labelchange
  6354. */
  6355. Object.defineProperty(this, 'label', {
  6356. get() {
  6357. return label;
  6358. },
  6359. set(newLabel) {
  6360. if (newLabel !== label) {
  6361. label = newLabel;
  6362. /**
  6363. * An event that fires when label changes on this track.
  6364. *
  6365. * > Note: This is not part of the spec!
  6366. *
  6367. * @event Track#labelchange
  6368. * @type {Event}
  6369. */
  6370. this.trigger('labelchange');
  6371. }
  6372. }
  6373. });
  6374. }
  6375. }
  6376. /**
  6377. * @file url.js
  6378. * @module url
  6379. */
  6380. /**
  6381. * @typedef {Object} url:URLObject
  6382. *
  6383. * @property {string} protocol
  6384. * The protocol of the url that was parsed.
  6385. *
  6386. * @property {string} hostname
  6387. * The hostname of the url that was parsed.
  6388. *
  6389. * @property {string} port
  6390. * The port of the url that was parsed.
  6391. *
  6392. * @property {string} pathname
  6393. * The pathname of the url that was parsed.
  6394. *
  6395. * @property {string} search
  6396. * The search query of the url that was parsed.
  6397. *
  6398. * @property {string} hash
  6399. * The hash of the url that was parsed.
  6400. *
  6401. * @property {string} host
  6402. * The host of the url that was parsed.
  6403. */
  6404. /**
  6405. * Resolve and parse the elements of a URL.
  6406. *
  6407. * @function
  6408. * @param {String} url
  6409. * The url to parse
  6410. *
  6411. * @return {url:URLObject}
  6412. * An object of url details
  6413. */
  6414. const parseUrl = function (url) {
  6415. // This entire method can be replace with URL once we are able to drop IE11
  6416. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6417. // add the url to an anchor and let the browser parse the URL
  6418. const a = document.createElement('a');
  6419. a.href = url;
  6420. // Copy the specific URL properties to a new object
  6421. // This is also needed for IE because the anchor loses its
  6422. // properties when it's removed from the dom
  6423. const details = {};
  6424. for (let i = 0; i < props.length; i++) {
  6425. details[props[i]] = a[props[i]];
  6426. }
  6427. // IE adds the port to the host property unlike everyone else. If
  6428. // a port identifier is added for standard ports, strip it.
  6429. if (details.protocol === 'http:') {
  6430. details.host = details.host.replace(/:80$/, '');
  6431. }
  6432. if (details.protocol === 'https:') {
  6433. details.host = details.host.replace(/:443$/, '');
  6434. }
  6435. if (!details.protocol) {
  6436. details.protocol = window.location.protocol;
  6437. }
  6438. /* istanbul ignore if */
  6439. if (!details.host) {
  6440. details.host = window.location.host;
  6441. }
  6442. return details;
  6443. };
  6444. /**
  6445. * Get absolute version of relative URL.
  6446. *
  6447. * @function
  6448. * @param {string} url
  6449. * URL to make absolute
  6450. *
  6451. * @return {string}
  6452. * Absolute URL
  6453. *
  6454. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6455. */
  6456. const getAbsoluteURL = function (url) {
  6457. // Check if absolute URL
  6458. if (!url.match(/^https?:\/\//)) {
  6459. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6460. const a = document.createElement('a');
  6461. a.href = url;
  6462. url = a.href;
  6463. }
  6464. return url;
  6465. };
  6466. /**
  6467. * Returns the extension of the passed file name. It will return an empty string
  6468. * if passed an invalid path.
  6469. *
  6470. * @function
  6471. * @param {string} path
  6472. * The fileName path like '/path/to/file.mp4'
  6473. *
  6474. * @return {string}
  6475. * The extension in lower case or an empty string if no
  6476. * extension could be found.
  6477. */
  6478. const getFileExtension = function (path) {
  6479. if (typeof path === 'string') {
  6480. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6481. const pathParts = splitPathRe.exec(path);
  6482. if (pathParts) {
  6483. return pathParts.pop().toLowerCase();
  6484. }
  6485. }
  6486. return '';
  6487. };
  6488. /**
  6489. * Returns whether the url passed is a cross domain request or not.
  6490. *
  6491. * @function
  6492. * @param {string} url
  6493. * The url to check.
  6494. *
  6495. * @param {Object} [winLoc]
  6496. * the domain to check the url against, defaults to window.location
  6497. *
  6498. * @param {string} [winLoc.protocol]
  6499. * The window location protocol defaults to window.location.protocol
  6500. *
  6501. * @param {string} [winLoc.host]
  6502. * The window location host defaults to window.location.host
  6503. *
  6504. * @return {boolean}
  6505. * Whether it is a cross domain request or not.
  6506. */
  6507. const isCrossOrigin = function (url, winLoc = window.location) {
  6508. const urlInfo = parseUrl(url);
  6509. // IE8 protocol relative urls will return ':' for protocol
  6510. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6511. // Check if url is for another domain/origin
  6512. // IE8 doesn't know location.origin, so we won't rely on it here
  6513. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6514. return crossOrigin;
  6515. };
  6516. var Url = /*#__PURE__*/Object.freeze({
  6517. __proto__: null,
  6518. parseUrl: parseUrl,
  6519. getAbsoluteURL: getAbsoluteURL,
  6520. getFileExtension: getFileExtension,
  6521. isCrossOrigin: isCrossOrigin
  6522. });
  6523. /**
  6524. * @file text-track.js
  6525. */
  6526. /**
  6527. * Takes a webvtt file contents and parses it into cues
  6528. *
  6529. * @param {string} srcContent
  6530. * webVTT file contents
  6531. *
  6532. * @param {TextTrack} track
  6533. * TextTrack to add cues to. Cues come from the srcContent.
  6534. *
  6535. * @private
  6536. */
  6537. const parseCues = function (srcContent, track) {
  6538. const parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  6539. const errors = [];
  6540. parser.oncue = function (cue) {
  6541. track.addCue(cue);
  6542. };
  6543. parser.onparsingerror = function (error) {
  6544. errors.push(error);
  6545. };
  6546. parser.onflush = function () {
  6547. track.trigger({
  6548. type: 'loadeddata',
  6549. target: track
  6550. });
  6551. };
  6552. parser.parse(srcContent);
  6553. if (errors.length > 0) {
  6554. if (window.console && window.console.groupCollapsed) {
  6555. window.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  6556. }
  6557. errors.forEach(error => log.error(error));
  6558. if (window.console && window.console.groupEnd) {
  6559. window.console.groupEnd();
  6560. }
  6561. }
  6562. parser.flush();
  6563. };
  6564. /**
  6565. * Load a `TextTrack` from a specified url.
  6566. *
  6567. * @param {string} src
  6568. * Url to load track from.
  6569. *
  6570. * @param {TextTrack} track
  6571. * Track to add cues to. Comes from the content at the end of `url`.
  6572. *
  6573. * @private
  6574. */
  6575. const loadTrack = function (src, track) {
  6576. const opts = {
  6577. uri: src
  6578. };
  6579. const crossOrigin = isCrossOrigin(src);
  6580. if (crossOrigin) {
  6581. opts.cors = crossOrigin;
  6582. }
  6583. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  6584. if (withCredentials) {
  6585. opts.withCredentials = withCredentials;
  6586. }
  6587. XHR(opts, bind_(this, function (err, response, responseBody) {
  6588. if (err) {
  6589. return log.error(err, response);
  6590. }
  6591. track.loaded_ = true;
  6592. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  6593. // NOTE: this is only used for the alt/video.novtt.js build
  6594. if (typeof window.WebVTT !== 'function') {
  6595. if (track.tech_) {
  6596. // to prevent use before define eslint error, we define loadHandler
  6597. // as a let here
  6598. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  6599. if (event.type === 'vttjserror') {
  6600. log.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  6601. return;
  6602. }
  6603. return parseCues(responseBody, track);
  6604. });
  6605. }
  6606. } else {
  6607. parseCues(responseBody, track);
  6608. }
  6609. }));
  6610. };
  6611. /**
  6612. * A representation of a single `TextTrack`.
  6613. *
  6614. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  6615. * @extends Track
  6616. */
  6617. class TextTrack extends Track {
  6618. /**
  6619. * Create an instance of this class.
  6620. *
  6621. * @param {Object} options={}
  6622. * Object of option names and values
  6623. *
  6624. * @param { import('../tech/tech').default } options.tech
  6625. * A reference to the tech that owns this TextTrack.
  6626. *
  6627. * @param {TextTrack~Kind} [options.kind='subtitles']
  6628. * A valid text track kind.
  6629. *
  6630. * @param {TextTrack~Mode} [options.mode='disabled']
  6631. * A valid text track mode.
  6632. *
  6633. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6634. * A unique id for this TextTrack.
  6635. *
  6636. * @param {string} [options.label='']
  6637. * The menu label for this track.
  6638. *
  6639. * @param {string} [options.language='']
  6640. * A valid two character language code.
  6641. *
  6642. * @param {string} [options.srclang='']
  6643. * A valid two character language code. An alternative, but deprioritized
  6644. * version of `options.language`
  6645. *
  6646. * @param {string} [options.src]
  6647. * A url to TextTrack cues.
  6648. *
  6649. * @param {boolean} [options.default]
  6650. * If this track should default to on or off.
  6651. */
  6652. constructor(options = {}) {
  6653. if (!options.tech) {
  6654. throw new Error('A tech was not provided.');
  6655. }
  6656. const settings = merge(options, {
  6657. kind: TextTrackKind[options.kind] || 'subtitles',
  6658. language: options.language || options.srclang || ''
  6659. });
  6660. let mode = TextTrackMode[settings.mode] || 'disabled';
  6661. const default_ = settings.default;
  6662. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  6663. mode = 'hidden';
  6664. }
  6665. super(settings);
  6666. this.tech_ = settings.tech;
  6667. this.cues_ = [];
  6668. this.activeCues_ = [];
  6669. this.preload_ = this.tech_.preloadTextTracks !== false;
  6670. const cues = new TextTrackCueList(this.cues_);
  6671. const activeCues = new TextTrackCueList(this.activeCues_);
  6672. let changed = false;
  6673. this.timeupdateHandler = bind_(this, function (event = {}) {
  6674. if (this.tech_.isDisposed()) {
  6675. return;
  6676. }
  6677. if (!this.tech_.isReady_) {
  6678. if (event.type !== 'timeupdate') {
  6679. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6680. }
  6681. return;
  6682. }
  6683. // Accessing this.activeCues for the side-effects of updating itself
  6684. // due to its nature as a getter function. Do not remove or cues will
  6685. // stop updating!
  6686. // Use the setter to prevent deletion from uglify (pure_getters rule)
  6687. this.activeCues = this.activeCues;
  6688. if (changed) {
  6689. this.trigger('cuechange');
  6690. changed = false;
  6691. }
  6692. if (event.type !== 'timeupdate') {
  6693. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6694. }
  6695. });
  6696. const disposeHandler = () => {
  6697. this.stopTracking();
  6698. };
  6699. this.tech_.one('dispose', disposeHandler);
  6700. if (mode !== 'disabled') {
  6701. this.startTracking();
  6702. }
  6703. Object.defineProperties(this, {
  6704. /**
  6705. * @memberof TextTrack
  6706. * @member {boolean} default
  6707. * If this track was set to be on or off by default. Cannot be changed after
  6708. * creation.
  6709. * @instance
  6710. *
  6711. * @readonly
  6712. */
  6713. default: {
  6714. get() {
  6715. return default_;
  6716. },
  6717. set() {}
  6718. },
  6719. /**
  6720. * @memberof TextTrack
  6721. * @member {string} mode
  6722. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  6723. * not be set if setting to an invalid mode.
  6724. * @instance
  6725. *
  6726. * @fires TextTrack#modechange
  6727. */
  6728. mode: {
  6729. get() {
  6730. return mode;
  6731. },
  6732. set(newMode) {
  6733. if (!TextTrackMode[newMode]) {
  6734. return;
  6735. }
  6736. if (mode === newMode) {
  6737. return;
  6738. }
  6739. mode = newMode;
  6740. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  6741. // On-demand load.
  6742. loadTrack(this.src, this);
  6743. }
  6744. this.stopTracking();
  6745. if (mode !== 'disabled') {
  6746. this.startTracking();
  6747. }
  6748. /**
  6749. * An event that fires when mode changes on this track. This allows
  6750. * the TextTrackList that holds this track to act accordingly.
  6751. *
  6752. * > Note: This is not part of the spec!
  6753. *
  6754. * @event TextTrack#modechange
  6755. * @type {Event}
  6756. */
  6757. this.trigger('modechange');
  6758. }
  6759. },
  6760. /**
  6761. * @memberof TextTrack
  6762. * @member {TextTrackCueList} cues
  6763. * The text track cue list for this TextTrack.
  6764. * @instance
  6765. */
  6766. cues: {
  6767. get() {
  6768. if (!this.loaded_) {
  6769. return null;
  6770. }
  6771. return cues;
  6772. },
  6773. set() {}
  6774. },
  6775. /**
  6776. * @memberof TextTrack
  6777. * @member {TextTrackCueList} activeCues
  6778. * The list text track cues that are currently active for this TextTrack.
  6779. * @instance
  6780. */
  6781. activeCues: {
  6782. get() {
  6783. if (!this.loaded_) {
  6784. return null;
  6785. }
  6786. // nothing to do
  6787. if (this.cues.length === 0) {
  6788. return activeCues;
  6789. }
  6790. const ct = this.tech_.currentTime();
  6791. const active = [];
  6792. for (let i = 0, l = this.cues.length; i < l; i++) {
  6793. const cue = this.cues[i];
  6794. if (cue.startTime <= ct && cue.endTime >= ct) {
  6795. active.push(cue);
  6796. }
  6797. }
  6798. changed = false;
  6799. if (active.length !== this.activeCues_.length) {
  6800. changed = true;
  6801. } else {
  6802. for (let i = 0; i < active.length; i++) {
  6803. if (this.activeCues_.indexOf(active[i]) === -1) {
  6804. changed = true;
  6805. }
  6806. }
  6807. }
  6808. this.activeCues_ = active;
  6809. activeCues.setCues_(this.activeCues_);
  6810. return activeCues;
  6811. },
  6812. // /!\ Keep this setter empty (see the timeupdate handler above)
  6813. set() {}
  6814. }
  6815. });
  6816. if (settings.src) {
  6817. this.src = settings.src;
  6818. if (!this.preload_) {
  6819. // Tracks will load on-demand.
  6820. // Act like we're loaded for other purposes.
  6821. this.loaded_ = true;
  6822. }
  6823. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  6824. loadTrack(this.src, this);
  6825. }
  6826. } else {
  6827. this.loaded_ = true;
  6828. }
  6829. }
  6830. startTracking() {
  6831. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  6832. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6833. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  6834. this.tech_.on('timeupdate', this.timeupdateHandler);
  6835. }
  6836. stopTracking() {
  6837. if (this.rvf_) {
  6838. this.tech_.cancelVideoFrameCallback(this.rvf_);
  6839. this.rvf_ = undefined;
  6840. }
  6841. this.tech_.off('timeupdate', this.timeupdateHandler);
  6842. }
  6843. /**
  6844. * Add a cue to the internal list of cues.
  6845. *
  6846. * @param {TextTrack~Cue} cue
  6847. * The cue to add to our internal list
  6848. */
  6849. addCue(originalCue) {
  6850. let cue = originalCue;
  6851. if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
  6852. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  6853. for (const prop in originalCue) {
  6854. if (!(prop in cue)) {
  6855. cue[prop] = originalCue[prop];
  6856. }
  6857. }
  6858. // make sure that `id` is copied over
  6859. cue.id = originalCue.id;
  6860. cue.originalCue_ = originalCue;
  6861. }
  6862. const tracks = this.tech_.textTracks();
  6863. for (let i = 0; i < tracks.length; i++) {
  6864. if (tracks[i] !== this) {
  6865. tracks[i].removeCue(cue);
  6866. }
  6867. }
  6868. this.cues_.push(cue);
  6869. this.cues.setCues_(this.cues_);
  6870. }
  6871. /**
  6872. * Remove a cue from our internal list
  6873. *
  6874. * @param {TextTrack~Cue} removeCue
  6875. * The cue to remove from our internal list
  6876. */
  6877. removeCue(removeCue) {
  6878. let i = this.cues_.length;
  6879. while (i--) {
  6880. const cue = this.cues_[i];
  6881. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  6882. this.cues_.splice(i, 1);
  6883. this.cues.setCues_(this.cues_);
  6884. break;
  6885. }
  6886. }
  6887. }
  6888. }
  6889. /**
  6890. * cuechange - One or more cues in the track have become active or stopped being active.
  6891. */
  6892. TextTrack.prototype.allowedEvents_ = {
  6893. cuechange: 'cuechange'
  6894. };
  6895. /**
  6896. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  6897. * only one `AudioTrack` in the list will be enabled at a time.
  6898. *
  6899. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  6900. * @extends Track
  6901. */
  6902. class AudioTrack extends Track {
  6903. /**
  6904. * Create an instance of this class.
  6905. *
  6906. * @param {Object} [options={}]
  6907. * Object of option names and values
  6908. *
  6909. * @param {AudioTrack~Kind} [options.kind='']
  6910. * A valid audio track kind
  6911. *
  6912. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6913. * A unique id for this AudioTrack.
  6914. *
  6915. * @param {string} [options.label='']
  6916. * The menu label for this track.
  6917. *
  6918. * @param {string} [options.language='']
  6919. * A valid two character language code.
  6920. *
  6921. * @param {boolean} [options.enabled]
  6922. * If this track is the one that is currently playing. If this track is part of
  6923. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  6924. */
  6925. constructor(options = {}) {
  6926. const settings = merge(options, {
  6927. kind: AudioTrackKind[options.kind] || ''
  6928. });
  6929. super(settings);
  6930. let enabled = false;
  6931. /**
  6932. * @memberof AudioTrack
  6933. * @member {boolean} enabled
  6934. * If this `AudioTrack` is enabled or not. When setting this will
  6935. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  6936. * @instance
  6937. *
  6938. * @fires VideoTrack#selectedchange
  6939. */
  6940. Object.defineProperty(this, 'enabled', {
  6941. get() {
  6942. return enabled;
  6943. },
  6944. set(newEnabled) {
  6945. // an invalid or unchanged value
  6946. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  6947. return;
  6948. }
  6949. enabled = newEnabled;
  6950. /**
  6951. * An event that fires when enabled changes on this track. This allows
  6952. * the AudioTrackList that holds this track to act accordingly.
  6953. *
  6954. * > Note: This is not part of the spec! Native tracks will do
  6955. * this internally without an event.
  6956. *
  6957. * @event AudioTrack#enabledchange
  6958. * @type {Event}
  6959. */
  6960. this.trigger('enabledchange');
  6961. }
  6962. });
  6963. // if the user sets this track to selected then
  6964. // set selected to that true value otherwise
  6965. // we keep it false
  6966. if (settings.enabled) {
  6967. this.enabled = settings.enabled;
  6968. }
  6969. this.loaded_ = true;
  6970. }
  6971. }
  6972. /**
  6973. * A representation of a single `VideoTrack`.
  6974. *
  6975. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  6976. * @extends Track
  6977. */
  6978. class VideoTrack extends Track {
  6979. /**
  6980. * Create an instance of this class.
  6981. *
  6982. * @param {Object} [options={}]
  6983. * Object of option names and values
  6984. *
  6985. * @param {string} [options.kind='']
  6986. * A valid {@link VideoTrack~Kind}
  6987. *
  6988. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6989. * A unique id for this AudioTrack.
  6990. *
  6991. * @param {string} [options.label='']
  6992. * The menu label for this track.
  6993. *
  6994. * @param {string} [options.language='']
  6995. * A valid two character language code.
  6996. *
  6997. * @param {boolean} [options.selected]
  6998. * If this track is the one that is currently playing.
  6999. */
  7000. constructor(options = {}) {
  7001. const settings = merge(options, {
  7002. kind: VideoTrackKind[options.kind] || ''
  7003. });
  7004. super(settings);
  7005. let selected = false;
  7006. /**
  7007. * @memberof VideoTrack
  7008. * @member {boolean} selected
  7009. * If this `VideoTrack` is selected or not. When setting this will
  7010. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7011. * @instance
  7012. *
  7013. * @fires VideoTrack#selectedchange
  7014. */
  7015. Object.defineProperty(this, 'selected', {
  7016. get() {
  7017. return selected;
  7018. },
  7019. set(newSelected) {
  7020. // an invalid or unchanged value
  7021. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7022. return;
  7023. }
  7024. selected = newSelected;
  7025. /**
  7026. * An event that fires when selected changes on this track. This allows
  7027. * the VideoTrackList that holds this track to act accordingly.
  7028. *
  7029. * > Note: This is not part of the spec! Native tracks will do
  7030. * this internally without an event.
  7031. *
  7032. * @event VideoTrack#selectedchange
  7033. * @type {Event}
  7034. */
  7035. this.trigger('selectedchange');
  7036. }
  7037. });
  7038. // if the user sets this track to selected then
  7039. // set selected to that true value otherwise
  7040. // we keep it false
  7041. if (settings.selected) {
  7042. this.selected = settings.selected;
  7043. }
  7044. }
  7045. }
  7046. /**
  7047. * @file html-track-element.js
  7048. */
  7049. /**
  7050. * A single track represented in the DOM.
  7051. *
  7052. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7053. * @extends EventTarget
  7054. */
  7055. class HTMLTrackElement extends EventTarget {
  7056. /**
  7057. * Create an instance of this class.
  7058. *
  7059. * @param {Object} options={}
  7060. * Object of option names and values
  7061. *
  7062. * @param { import('../tech/tech').default } options.tech
  7063. * A reference to the tech that owns this HTMLTrackElement.
  7064. *
  7065. * @param {TextTrack~Kind} [options.kind='subtitles']
  7066. * A valid text track kind.
  7067. *
  7068. * @param {TextTrack~Mode} [options.mode='disabled']
  7069. * A valid text track mode.
  7070. *
  7071. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7072. * A unique id for this TextTrack.
  7073. *
  7074. * @param {string} [options.label='']
  7075. * The menu label for this track.
  7076. *
  7077. * @param {string} [options.language='']
  7078. * A valid two character language code.
  7079. *
  7080. * @param {string} [options.srclang='']
  7081. * A valid two character language code. An alternative, but deprioritized
  7082. * version of `options.language`
  7083. *
  7084. * @param {string} [options.src]
  7085. * A url to TextTrack cues.
  7086. *
  7087. * @param {boolean} [options.default]
  7088. * If this track should default to on or off.
  7089. */
  7090. constructor(options = {}) {
  7091. super();
  7092. let readyState;
  7093. const track = new TextTrack(options);
  7094. this.kind = track.kind;
  7095. this.src = track.src;
  7096. this.srclang = track.language;
  7097. this.label = track.label;
  7098. this.default = track.default;
  7099. Object.defineProperties(this, {
  7100. /**
  7101. * @memberof HTMLTrackElement
  7102. * @member {HTMLTrackElement~ReadyState} readyState
  7103. * The current ready state of the track element.
  7104. * @instance
  7105. */
  7106. readyState: {
  7107. get() {
  7108. return readyState;
  7109. }
  7110. },
  7111. /**
  7112. * @memberof HTMLTrackElement
  7113. * @member {TextTrack} track
  7114. * The underlying TextTrack object.
  7115. * @instance
  7116. *
  7117. */
  7118. track: {
  7119. get() {
  7120. return track;
  7121. }
  7122. }
  7123. });
  7124. readyState = HTMLTrackElement.NONE;
  7125. /**
  7126. * @listens TextTrack#loadeddata
  7127. * @fires HTMLTrackElement#load
  7128. */
  7129. track.addEventListener('loadeddata', () => {
  7130. readyState = HTMLTrackElement.LOADED;
  7131. this.trigger({
  7132. type: 'load',
  7133. target: this
  7134. });
  7135. });
  7136. }
  7137. }
  7138. HTMLTrackElement.prototype.allowedEvents_ = {
  7139. load: 'load'
  7140. };
  7141. /**
  7142. * The text track not loaded state.
  7143. *
  7144. * @type {number}
  7145. * @static
  7146. */
  7147. HTMLTrackElement.NONE = 0;
  7148. /**
  7149. * The text track loading state.
  7150. *
  7151. * @type {number}
  7152. * @static
  7153. */
  7154. HTMLTrackElement.LOADING = 1;
  7155. /**
  7156. * The text track loaded state.
  7157. *
  7158. * @type {number}
  7159. * @static
  7160. */
  7161. HTMLTrackElement.LOADED = 2;
  7162. /**
  7163. * The text track failed to load state.
  7164. *
  7165. * @type {number}
  7166. * @static
  7167. */
  7168. HTMLTrackElement.ERROR = 3;
  7169. /*
  7170. * This file contains all track properties that are used in
  7171. * player.js, tech.js, html5.js and possibly other techs in the future.
  7172. */
  7173. const NORMAL = {
  7174. audio: {
  7175. ListClass: AudioTrackList,
  7176. TrackClass: AudioTrack,
  7177. capitalName: 'Audio'
  7178. },
  7179. video: {
  7180. ListClass: VideoTrackList,
  7181. TrackClass: VideoTrack,
  7182. capitalName: 'Video'
  7183. },
  7184. text: {
  7185. ListClass: TextTrackList,
  7186. TrackClass: TextTrack,
  7187. capitalName: 'Text'
  7188. }
  7189. };
  7190. Object.keys(NORMAL).forEach(function (type) {
  7191. NORMAL[type].getterName = `${type}Tracks`;
  7192. NORMAL[type].privateName = `${type}Tracks_`;
  7193. });
  7194. const REMOTE = {
  7195. remoteText: {
  7196. ListClass: TextTrackList,
  7197. TrackClass: TextTrack,
  7198. capitalName: 'RemoteText',
  7199. getterName: 'remoteTextTracks',
  7200. privateName: 'remoteTextTracks_'
  7201. },
  7202. remoteTextEl: {
  7203. ListClass: HtmlTrackElementList,
  7204. TrackClass: HTMLTrackElement,
  7205. capitalName: 'RemoteTextTrackEls',
  7206. getterName: 'remoteTextTrackEls',
  7207. privateName: 'remoteTextTrackEls_'
  7208. }
  7209. };
  7210. const ALL = Object.assign({}, NORMAL, REMOTE);
  7211. REMOTE.names = Object.keys(REMOTE);
  7212. NORMAL.names = Object.keys(NORMAL);
  7213. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7214. /**
  7215. * @file tech.js
  7216. */
  7217. /**
  7218. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7219. * that just contains the src url alone.
  7220. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7221. * `var SourceString = 'http://example.com/some-video.mp4';`
  7222. *
  7223. * @typedef {Object|string} Tech~SourceObject
  7224. *
  7225. * @property {string} src
  7226. * The url to the source
  7227. *
  7228. * @property {string} type
  7229. * The mime type of the source
  7230. */
  7231. /**
  7232. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7233. *
  7234. * @private
  7235. *
  7236. * @param {Tech} self
  7237. * An instance of the Tech class.
  7238. *
  7239. * @param {string} kind
  7240. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7241. *
  7242. * @param {string} [label]
  7243. * Label to identify the text track
  7244. *
  7245. * @param {string} [language]
  7246. * Two letter language abbreviation
  7247. *
  7248. * @param {Object} [options={}]
  7249. * An object with additional text track options
  7250. *
  7251. * @return {TextTrack}
  7252. * The text track that was created.
  7253. */
  7254. function createTrackHelper(self, kind, label, language, options = {}) {
  7255. const tracks = self.textTracks();
  7256. options.kind = kind;
  7257. if (label) {
  7258. options.label = label;
  7259. }
  7260. if (language) {
  7261. options.language = language;
  7262. }
  7263. options.tech = self;
  7264. const track = new ALL.text.TrackClass(options);
  7265. tracks.addTrack(track);
  7266. return track;
  7267. }
  7268. /**
  7269. * This is the base class for media playback technology controllers, such as
  7270. * {@link HTML5}
  7271. *
  7272. * @extends Component
  7273. */
  7274. class Tech extends Component {
  7275. /**
  7276. * Create an instance of this Tech.
  7277. *
  7278. * @param {Object} [options]
  7279. * The key/value store of player options.
  7280. *
  7281. * @param {Function} [ready]
  7282. * Callback function to call when the `HTML5` Tech is ready.
  7283. */
  7284. constructor(options = {}, ready = function () {}) {
  7285. // we don't want the tech to report user activity automatically.
  7286. // This is done manually in addControlsListeners
  7287. options.reportTouchActivity = false;
  7288. super(null, options, ready);
  7289. this.onDurationChange_ = e => this.onDurationChange(e);
  7290. this.trackProgress_ = e => this.trackProgress(e);
  7291. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  7292. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  7293. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  7294. this.queuedHanders_ = new Set();
  7295. // keep track of whether the current source has played at all to
  7296. // implement a very limited played()
  7297. this.hasStarted_ = false;
  7298. this.on('playing', function () {
  7299. this.hasStarted_ = true;
  7300. });
  7301. this.on('loadstart', function () {
  7302. this.hasStarted_ = false;
  7303. });
  7304. ALL.names.forEach(name => {
  7305. const props = ALL[name];
  7306. if (options && options[props.getterName]) {
  7307. this[props.privateName] = options[props.getterName];
  7308. }
  7309. });
  7310. // Manually track progress in cases where the browser/tech doesn't report it.
  7311. if (!this.featuresProgressEvents) {
  7312. this.manualProgressOn();
  7313. }
  7314. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7315. if (!this.featuresTimeupdateEvents) {
  7316. this.manualTimeUpdatesOn();
  7317. }
  7318. ['Text', 'Audio', 'Video'].forEach(track => {
  7319. if (options[`native${track}Tracks`] === false) {
  7320. this[`featuresNative${track}Tracks`] = false;
  7321. }
  7322. });
  7323. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7324. this.featuresNativeTextTracks = false;
  7325. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7326. this.featuresNativeTextTracks = true;
  7327. }
  7328. if (!this.featuresNativeTextTracks) {
  7329. this.emulateTextTracks();
  7330. }
  7331. this.preloadTextTracks = options.preloadTextTracks !== false;
  7332. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7333. this.initTrackListeners();
  7334. // Turn on component tap events only if not using native controls
  7335. if (!options.nativeControlsForTouch) {
  7336. this.emitTapEvents();
  7337. }
  7338. if (this.constructor) {
  7339. this.name_ = this.constructor.name || 'Unknown Tech';
  7340. }
  7341. }
  7342. /**
  7343. * A special function to trigger source set in a way that will allow player
  7344. * to re-trigger if the player or tech are not ready yet.
  7345. *
  7346. * @fires Tech#sourceset
  7347. * @param {string} src The source string at the time of the source changing.
  7348. */
  7349. triggerSourceset(src) {
  7350. if (!this.isReady_) {
  7351. // on initial ready we have to trigger source set
  7352. // 1ms after ready so that player can watch for it.
  7353. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  7354. }
  7355. /**
  7356. * Fired when the source is set on the tech causing the media element
  7357. * to reload.
  7358. *
  7359. * @see {@link Player#event:sourceset}
  7360. * @event Tech#sourceset
  7361. * @type {Event}
  7362. */
  7363. this.trigger({
  7364. src,
  7365. type: 'sourceset'
  7366. });
  7367. }
  7368. /* Fallbacks for unsupported event types
  7369. ================================================================================ */
  7370. /**
  7371. * Polyfill the `progress` event for browsers that don't support it natively.
  7372. *
  7373. * @see {@link Tech#trackProgress}
  7374. */
  7375. manualProgressOn() {
  7376. this.on('durationchange', this.onDurationChange_);
  7377. this.manualProgress = true;
  7378. // Trigger progress watching when a source begins loading
  7379. this.one('ready', this.trackProgress_);
  7380. }
  7381. /**
  7382. * Turn off the polyfill for `progress` events that was created in
  7383. * {@link Tech#manualProgressOn}
  7384. */
  7385. manualProgressOff() {
  7386. this.manualProgress = false;
  7387. this.stopTrackingProgress();
  7388. this.off('durationchange', this.onDurationChange_);
  7389. }
  7390. /**
  7391. * This is used to trigger a `progress` event when the buffered percent changes. It
  7392. * sets an interval function that will be called every 500 milliseconds to check if the
  7393. * buffer end percent has changed.
  7394. *
  7395. * > This function is called by {@link Tech#manualProgressOn}
  7396. *
  7397. * @param {Event} event
  7398. * The `ready` event that caused this to run.
  7399. *
  7400. * @listens Tech#ready
  7401. * @fires Tech#progress
  7402. */
  7403. trackProgress(event) {
  7404. this.stopTrackingProgress();
  7405. this.progressInterval = this.setInterval(bind_(this, function () {
  7406. // Don't trigger unless buffered amount is greater than last time
  7407. const numBufferedPercent = this.bufferedPercent();
  7408. if (this.bufferedPercent_ !== numBufferedPercent) {
  7409. /**
  7410. * See {@link Player#progress}
  7411. *
  7412. * @event Tech#progress
  7413. * @type {Event}
  7414. */
  7415. this.trigger('progress');
  7416. }
  7417. this.bufferedPercent_ = numBufferedPercent;
  7418. if (numBufferedPercent === 1) {
  7419. this.stopTrackingProgress();
  7420. }
  7421. }), 500);
  7422. }
  7423. /**
  7424. * Update our internal duration on a `durationchange` event by calling
  7425. * {@link Tech#duration}.
  7426. *
  7427. * @param {Event} event
  7428. * The `durationchange` event that caused this to run.
  7429. *
  7430. * @listens Tech#durationchange
  7431. */
  7432. onDurationChange(event) {
  7433. this.duration_ = this.duration();
  7434. }
  7435. /**
  7436. * Get and create a `TimeRange` object for buffering.
  7437. *
  7438. * @return { import('../utils/time').TimeRange }
  7439. * The time range object that was created.
  7440. */
  7441. buffered() {
  7442. return createTimeRanges(0, 0);
  7443. }
  7444. /**
  7445. * Get the percentage of the current video that is currently buffered.
  7446. *
  7447. * @return {number}
  7448. * A number from 0 to 1 that represents the decimal percentage of the
  7449. * video that is buffered.
  7450. *
  7451. */
  7452. bufferedPercent() {
  7453. return bufferedPercent(this.buffered(), this.duration_);
  7454. }
  7455. /**
  7456. * Turn off the polyfill for `progress` events that was created in
  7457. * {@link Tech#manualProgressOn}
  7458. * Stop manually tracking progress events by clearing the interval that was set in
  7459. * {@link Tech#trackProgress}.
  7460. */
  7461. stopTrackingProgress() {
  7462. this.clearInterval(this.progressInterval);
  7463. }
  7464. /**
  7465. * Polyfill the `timeupdate` event for browsers that don't support it.
  7466. *
  7467. * @see {@link Tech#trackCurrentTime}
  7468. */
  7469. manualTimeUpdatesOn() {
  7470. this.manualTimeUpdates = true;
  7471. this.on('play', this.trackCurrentTime_);
  7472. this.on('pause', this.stopTrackingCurrentTime_);
  7473. }
  7474. /**
  7475. * Turn off the polyfill for `timeupdate` events that was created in
  7476. * {@link Tech#manualTimeUpdatesOn}
  7477. */
  7478. manualTimeUpdatesOff() {
  7479. this.manualTimeUpdates = false;
  7480. this.stopTrackingCurrentTime();
  7481. this.off('play', this.trackCurrentTime_);
  7482. this.off('pause', this.stopTrackingCurrentTime_);
  7483. }
  7484. /**
  7485. * Sets up an interval function to track current time and trigger `timeupdate` every
  7486. * 250 milliseconds.
  7487. *
  7488. * @listens Tech#play
  7489. * @triggers Tech#timeupdate
  7490. */
  7491. trackCurrentTime() {
  7492. if (this.currentTimeInterval) {
  7493. this.stopTrackingCurrentTime();
  7494. }
  7495. this.currentTimeInterval = this.setInterval(function () {
  7496. /**
  7497. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  7498. *
  7499. * @event Tech#timeupdate
  7500. * @type {Event}
  7501. */
  7502. this.trigger({
  7503. type: 'timeupdate',
  7504. target: this,
  7505. manuallyTriggered: true
  7506. });
  7507. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  7508. }, 250);
  7509. }
  7510. /**
  7511. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  7512. * `timeupdate` event is no longer triggered.
  7513. *
  7514. * @listens {Tech#pause}
  7515. */
  7516. stopTrackingCurrentTime() {
  7517. this.clearInterval(this.currentTimeInterval);
  7518. // #1002 - if the video ends right before the next timeupdate would happen,
  7519. // the progress bar won't make it all the way to the end
  7520. this.trigger({
  7521. type: 'timeupdate',
  7522. target: this,
  7523. manuallyTriggered: true
  7524. });
  7525. }
  7526. /**
  7527. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  7528. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  7529. *
  7530. * @fires Component#dispose
  7531. */
  7532. dispose() {
  7533. // clear out all tracks because we can't reuse them between techs
  7534. this.clearTracks(NORMAL.names);
  7535. // Turn off any manual progress or timeupdate tracking
  7536. if (this.manualProgress) {
  7537. this.manualProgressOff();
  7538. }
  7539. if (this.manualTimeUpdates) {
  7540. this.manualTimeUpdatesOff();
  7541. }
  7542. super.dispose();
  7543. }
  7544. /**
  7545. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  7546. *
  7547. * > Note: Techs without source handlers should call this between sources for `video`
  7548. * & `audio` tracks. You don't want to use them between tracks!
  7549. *
  7550. * @param {string[]|string} types
  7551. * TrackList names to clear, valid names are `video`, `audio`, and
  7552. * `text`.
  7553. */
  7554. clearTracks(types) {
  7555. types = [].concat(types);
  7556. // clear out all tracks because we can't reuse them between techs
  7557. types.forEach(type => {
  7558. const list = this[`${type}Tracks`]() || [];
  7559. let i = list.length;
  7560. while (i--) {
  7561. const track = list[i];
  7562. if (type === 'text') {
  7563. this.removeRemoteTextTrack(track);
  7564. }
  7565. list.removeTrack(track);
  7566. }
  7567. });
  7568. }
  7569. /**
  7570. * Remove any TextTracks added via addRemoteTextTrack that are
  7571. * flagged for automatic garbage collection
  7572. */
  7573. cleanupAutoTextTracks() {
  7574. const list = this.autoRemoteTextTracks_ || [];
  7575. let i = list.length;
  7576. while (i--) {
  7577. const track = list[i];
  7578. this.removeRemoteTextTrack(track);
  7579. }
  7580. }
  7581. /**
  7582. * Reset the tech, which will removes all sources and reset the internal readyState.
  7583. *
  7584. * @abstract
  7585. */
  7586. reset() {}
  7587. /**
  7588. * Get the value of `crossOrigin` from the tech.
  7589. *
  7590. * @abstract
  7591. *
  7592. * @see {Html5#crossOrigin}
  7593. */
  7594. crossOrigin() {}
  7595. /**
  7596. * Set the value of `crossOrigin` on the tech.
  7597. *
  7598. * @abstract
  7599. *
  7600. * @param {string} crossOrigin the crossOrigin value
  7601. * @see {Html5#setCrossOrigin}
  7602. */
  7603. setCrossOrigin() {}
  7604. /**
  7605. * Get or set an error on the Tech.
  7606. *
  7607. * @param {MediaError} [err]
  7608. * Error to set on the Tech
  7609. *
  7610. * @return {MediaError|null}
  7611. * The current error object on the tech, or null if there isn't one.
  7612. */
  7613. error(err) {
  7614. if (err !== undefined) {
  7615. this.error_ = new MediaError(err);
  7616. this.trigger('error');
  7617. }
  7618. return this.error_;
  7619. }
  7620. /**
  7621. * Returns the `TimeRange`s that have been played through for the current source.
  7622. *
  7623. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  7624. * It only checks whether the source has played at all or not.
  7625. *
  7626. * @return {TimeRange}
  7627. * - A single time range if this video has played
  7628. * - An empty set of ranges if not.
  7629. */
  7630. played() {
  7631. if (this.hasStarted_) {
  7632. return createTimeRanges(0, 0);
  7633. }
  7634. return createTimeRanges();
  7635. }
  7636. /**
  7637. * Start playback
  7638. *
  7639. * @abstract
  7640. *
  7641. * @see {Html5#play}
  7642. */
  7643. play() {}
  7644. /**
  7645. * Set whether we are scrubbing or not
  7646. *
  7647. * @abstract
  7648. * @param {boolean} _isScrubbing
  7649. * - true for we are currently scrubbing
  7650. * - false for we are no longer scrubbing
  7651. *
  7652. * @see {Html5#setScrubbing}
  7653. */
  7654. setScrubbing(_isScrubbing) {}
  7655. /**
  7656. * Get whether we are scrubbing or not
  7657. *
  7658. * @abstract
  7659. *
  7660. * @see {Html5#scrubbing}
  7661. */
  7662. scrubbing() {}
  7663. /**
  7664. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  7665. * previously called.
  7666. *
  7667. * @param {number} _seconds
  7668. * Set the current time of the media to this.
  7669. * @fires Tech#timeupdate
  7670. */
  7671. setCurrentTime(_seconds) {
  7672. // improve the accuracy of manual timeupdates
  7673. if (this.manualTimeUpdates) {
  7674. /**
  7675. * A manual `timeupdate` event.
  7676. *
  7677. * @event Tech#timeupdate
  7678. * @type {Event}
  7679. */
  7680. this.trigger({
  7681. type: 'timeupdate',
  7682. target: this,
  7683. manuallyTriggered: true
  7684. });
  7685. }
  7686. }
  7687. /**
  7688. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  7689. * {@link TextTrackList} events.
  7690. *
  7691. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  7692. *
  7693. * @fires Tech#audiotrackchange
  7694. * @fires Tech#videotrackchange
  7695. * @fires Tech#texttrackchange
  7696. */
  7697. initTrackListeners() {
  7698. /**
  7699. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  7700. *
  7701. * @event Tech#audiotrackchange
  7702. * @type {Event}
  7703. */
  7704. /**
  7705. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  7706. *
  7707. * @event Tech#videotrackchange
  7708. * @type {Event}
  7709. */
  7710. /**
  7711. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  7712. *
  7713. * @event Tech#texttrackchange
  7714. * @type {Event}
  7715. */
  7716. NORMAL.names.forEach(name => {
  7717. const props = NORMAL[name];
  7718. const trackListChanges = () => {
  7719. this.trigger(`${name}trackchange`);
  7720. };
  7721. const tracks = this[props.getterName]();
  7722. tracks.addEventListener('removetrack', trackListChanges);
  7723. tracks.addEventListener('addtrack', trackListChanges);
  7724. this.on('dispose', () => {
  7725. tracks.removeEventListener('removetrack', trackListChanges);
  7726. tracks.removeEventListener('addtrack', trackListChanges);
  7727. });
  7728. });
  7729. }
  7730. /**
  7731. * Emulate TextTracks using vtt.js if necessary
  7732. *
  7733. * @fires Tech#vttjsloaded
  7734. * @fires Tech#vttjserror
  7735. */
  7736. addWebVttScript_() {
  7737. if (window.WebVTT) {
  7738. return;
  7739. }
  7740. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  7741. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  7742. // before inserting the WebVTT script
  7743. if (document.body.contains(this.el())) {
  7744. // load via require if available and vtt.js script location was not passed in
  7745. // as an option. novtt builds will turn the above require call into an empty object
  7746. // which will cause this if check to always fail.
  7747. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
  7748. this.trigger('vttjsloaded');
  7749. return;
  7750. }
  7751. // load vtt.js via the script location option or the cdn of no location was
  7752. // passed in
  7753. const script = document.createElement('script');
  7754. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  7755. script.onload = () => {
  7756. /**
  7757. * Fired when vtt.js is loaded.
  7758. *
  7759. * @event Tech#vttjsloaded
  7760. * @type {Event}
  7761. */
  7762. this.trigger('vttjsloaded');
  7763. };
  7764. script.onerror = () => {
  7765. /**
  7766. * Fired when vtt.js was not loaded due to an error
  7767. *
  7768. * @event Tech#vttjsloaded
  7769. * @type {Event}
  7770. */
  7771. this.trigger('vttjserror');
  7772. };
  7773. this.on('dispose', () => {
  7774. script.onload = null;
  7775. script.onerror = null;
  7776. });
  7777. // but have not loaded yet and we set it to true before the inject so that
  7778. // we don't overwrite the injected window.WebVTT if it loads right away
  7779. window.WebVTT = true;
  7780. this.el().parentNode.appendChild(script);
  7781. } else {
  7782. this.ready(this.addWebVttScript_);
  7783. }
  7784. }
  7785. /**
  7786. * Emulate texttracks
  7787. *
  7788. */
  7789. emulateTextTracks() {
  7790. const tracks = this.textTracks();
  7791. const remoteTracks = this.remoteTextTracks();
  7792. const handleAddTrack = e => tracks.addTrack(e.track);
  7793. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  7794. remoteTracks.on('addtrack', handleAddTrack);
  7795. remoteTracks.on('removetrack', handleRemoveTrack);
  7796. this.addWebVttScript_();
  7797. const updateDisplay = () => this.trigger('texttrackchange');
  7798. const textTracksChanges = () => {
  7799. updateDisplay();
  7800. for (let i = 0; i < tracks.length; i++) {
  7801. const track = tracks[i];
  7802. track.removeEventListener('cuechange', updateDisplay);
  7803. if (track.mode === 'showing') {
  7804. track.addEventListener('cuechange', updateDisplay);
  7805. }
  7806. }
  7807. };
  7808. textTracksChanges();
  7809. tracks.addEventListener('change', textTracksChanges);
  7810. tracks.addEventListener('addtrack', textTracksChanges);
  7811. tracks.addEventListener('removetrack', textTracksChanges);
  7812. this.on('dispose', function () {
  7813. remoteTracks.off('addtrack', handleAddTrack);
  7814. remoteTracks.off('removetrack', handleRemoveTrack);
  7815. tracks.removeEventListener('change', textTracksChanges);
  7816. tracks.removeEventListener('addtrack', textTracksChanges);
  7817. tracks.removeEventListener('removetrack', textTracksChanges);
  7818. for (let i = 0; i < tracks.length; i++) {
  7819. const track = tracks[i];
  7820. track.removeEventListener('cuechange', updateDisplay);
  7821. }
  7822. });
  7823. }
  7824. /**
  7825. * Create and returns a remote {@link TextTrack} object.
  7826. *
  7827. * @param {string} kind
  7828. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7829. *
  7830. * @param {string} [label]
  7831. * Label to identify the text track
  7832. *
  7833. * @param {string} [language]
  7834. * Two letter language abbreviation
  7835. *
  7836. * @return {TextTrack}
  7837. * The TextTrack that gets created.
  7838. */
  7839. addTextTrack(kind, label, language) {
  7840. if (!kind) {
  7841. throw new Error('TextTrack kind is required but was not provided');
  7842. }
  7843. return createTrackHelper(this, kind, label, language);
  7844. }
  7845. /**
  7846. * Create an emulated TextTrack for use by addRemoteTextTrack
  7847. *
  7848. * This is intended to be overridden by classes that inherit from
  7849. * Tech in order to create native or custom TextTracks.
  7850. *
  7851. * @param {Object} options
  7852. * The object should contain the options to initialize the TextTrack with.
  7853. *
  7854. * @param {string} [options.kind]
  7855. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  7856. *
  7857. * @param {string} [options.label].
  7858. * Label to identify the text track
  7859. *
  7860. * @param {string} [options.language]
  7861. * Two letter language abbreviation.
  7862. *
  7863. * @return {HTMLTrackElement}
  7864. * The track element that gets created.
  7865. */
  7866. createRemoteTextTrack(options) {
  7867. const track = merge(options, {
  7868. tech: this
  7869. });
  7870. return new REMOTE.remoteTextEl.TrackClass(track);
  7871. }
  7872. /**
  7873. * Creates a remote text track object and returns an html track element.
  7874. *
  7875. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  7876. *
  7877. * @param {Object} options
  7878. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  7879. *
  7880. * @param {boolean} [manualCleanup=false]
  7881. * - When false: the TextTrack will be automatically removed from the video
  7882. * element whenever the source changes
  7883. * - When True: The TextTrack will have to be cleaned up manually
  7884. *
  7885. * @return {HTMLTrackElement}
  7886. * An Html Track Element.
  7887. *
  7888. */
  7889. addRemoteTextTrack(options = {}, manualCleanup) {
  7890. const htmlTrackElement = this.createRemoteTextTrack(options);
  7891. if (typeof manualCleanup !== 'boolean') {
  7892. manualCleanup = false;
  7893. }
  7894. // store HTMLTrackElement and TextTrack to remote list
  7895. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  7896. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  7897. if (manualCleanup === false) {
  7898. // create the TextTrackList if it doesn't exist
  7899. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  7900. }
  7901. return htmlTrackElement;
  7902. }
  7903. /**
  7904. * Remove a remote text track from the remote `TextTrackList`.
  7905. *
  7906. * @param {TextTrack} track
  7907. * `TextTrack` to remove from the `TextTrackList`
  7908. */
  7909. removeRemoteTextTrack(track) {
  7910. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  7911. // remove HTMLTrackElement and TextTrack from remote list
  7912. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  7913. this.remoteTextTracks().removeTrack(track);
  7914. this.autoRemoteTextTracks_.removeTrack(track);
  7915. }
  7916. /**
  7917. * Gets available media playback quality metrics as specified by the W3C's Media
  7918. * Playback Quality API.
  7919. *
  7920. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  7921. *
  7922. * @return {Object}
  7923. * An object with supported media playback quality metrics
  7924. *
  7925. * @abstract
  7926. */
  7927. getVideoPlaybackQuality() {
  7928. return {};
  7929. }
  7930. /**
  7931. * Attempt to create a floating video window always on top of other windows
  7932. * so that users may continue consuming media while they interact with other
  7933. * content sites, or applications on their device.
  7934. *
  7935. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  7936. *
  7937. * @return {Promise|undefined}
  7938. * A promise with a Picture-in-Picture window if the browser supports
  7939. * Promises (or one was passed in as an option). It returns undefined
  7940. * otherwise.
  7941. *
  7942. * @abstract
  7943. */
  7944. requestPictureInPicture() {
  7945. return Promise.reject();
  7946. }
  7947. /**
  7948. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  7949. * Defaults to true, as it should be considered disabled if the tech does not support pip
  7950. *
  7951. * @abstract
  7952. */
  7953. disablePictureInPicture() {
  7954. return true;
  7955. }
  7956. /**
  7957. * A method to set or unset the 'disablePictureInPicture' <video> property.
  7958. *
  7959. * @abstract
  7960. */
  7961. setDisablePictureInPicture() {}
  7962. /**
  7963. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  7964. *
  7965. * @param {function} cb
  7966. * @return {number} request id
  7967. */
  7968. requestVideoFrameCallback(cb) {
  7969. const id = newGUID();
  7970. if (!this.isReady_ || this.paused()) {
  7971. this.queuedHanders_.add(id);
  7972. this.one('playing', () => {
  7973. if (this.queuedHanders_.has(id)) {
  7974. this.queuedHanders_.delete(id);
  7975. cb();
  7976. }
  7977. });
  7978. } else {
  7979. this.requestNamedAnimationFrame(id, cb);
  7980. }
  7981. return id;
  7982. }
  7983. /**
  7984. * A fallback implementation of cancelVideoFrameCallback
  7985. *
  7986. * @param {number} id id of callback to be cancelled
  7987. */
  7988. cancelVideoFrameCallback(id) {
  7989. if (this.queuedHanders_.has(id)) {
  7990. this.queuedHanders_.delete(id);
  7991. } else {
  7992. this.cancelNamedAnimationFrame(id);
  7993. }
  7994. }
  7995. /**
  7996. * A method to set a poster from a `Tech`.
  7997. *
  7998. * @abstract
  7999. */
  8000. setPoster() {}
  8001. /**
  8002. * A method to check for the presence of the 'playsinline' <video> attribute.
  8003. *
  8004. * @abstract
  8005. */
  8006. playsinline() {}
  8007. /**
  8008. * A method to set or unset the 'playsinline' <video> attribute.
  8009. *
  8010. * @abstract
  8011. */
  8012. setPlaysinline() {}
  8013. /**
  8014. * Attempt to force override of native audio tracks.
  8015. *
  8016. * @param {boolean} override - If set to true native audio will be overridden,
  8017. * otherwise native audio will potentially be used.
  8018. *
  8019. * @abstract
  8020. */
  8021. overrideNativeAudioTracks(override) {}
  8022. /**
  8023. * Attempt to force override of native video tracks.
  8024. *
  8025. * @param {boolean} override - If set to true native video will be overridden,
  8026. * otherwise native video will potentially be used.
  8027. *
  8028. * @abstract
  8029. */
  8030. overrideNativeVideoTracks(override) {}
  8031. /**
  8032. * Check if the tech can support the given mime-type.
  8033. *
  8034. * The base tech does not support any type, but source handlers might
  8035. * overwrite this.
  8036. *
  8037. * @param {string} _type
  8038. * The mimetype to check for support
  8039. *
  8040. * @return {string}
  8041. * 'probably', 'maybe', or empty string
  8042. *
  8043. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8044. *
  8045. * @abstract
  8046. */
  8047. canPlayType(_type) {
  8048. return '';
  8049. }
  8050. /**
  8051. * Check if the type is supported by this tech.
  8052. *
  8053. * The base tech does not support any type, but source handlers might
  8054. * overwrite this.
  8055. *
  8056. * @param {string} _type
  8057. * The media type to check
  8058. * @return {string} Returns the native video element's response
  8059. */
  8060. static canPlayType(_type) {
  8061. return '';
  8062. }
  8063. /**
  8064. * Check if the tech can support the given source
  8065. *
  8066. * @param {Object} srcObj
  8067. * The source object
  8068. * @param {Object} options
  8069. * The options passed to the tech
  8070. * @return {string} 'probably', 'maybe', or '' (empty string)
  8071. */
  8072. static canPlaySource(srcObj, options) {
  8073. return Tech.canPlayType(srcObj.type);
  8074. }
  8075. /*
  8076. * Return whether the argument is a Tech or not.
  8077. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8078. *
  8079. * @param {Object} component
  8080. * The item to check
  8081. *
  8082. * @return {boolean}
  8083. * Whether it is a tech or not
  8084. * - True if it is a tech
  8085. * - False if it is not
  8086. */
  8087. static isTech(component) {
  8088. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8089. }
  8090. /**
  8091. * Registers a `Tech` into a shared list for videojs.
  8092. *
  8093. * @param {string} name
  8094. * Name of the `Tech` to register.
  8095. *
  8096. * @param {Object} tech
  8097. * The `Tech` class to register.
  8098. */
  8099. static registerTech(name, tech) {
  8100. if (!Tech.techs_) {
  8101. Tech.techs_ = {};
  8102. }
  8103. if (!Tech.isTech(tech)) {
  8104. throw new Error(`Tech ${name} must be a Tech`);
  8105. }
  8106. if (!Tech.canPlayType) {
  8107. throw new Error('Techs must have a static canPlayType method on them');
  8108. }
  8109. if (!Tech.canPlaySource) {
  8110. throw new Error('Techs must have a static canPlaySource method on them');
  8111. }
  8112. name = toTitleCase(name);
  8113. Tech.techs_[name] = tech;
  8114. Tech.techs_[toLowerCase(name)] = tech;
  8115. if (name !== 'Tech') {
  8116. // camel case the techName for use in techOrder
  8117. Tech.defaultTechOrder_.push(name);
  8118. }
  8119. return tech;
  8120. }
  8121. /**
  8122. * Get a `Tech` from the shared list by name.
  8123. *
  8124. * @param {string} name
  8125. * `camelCase` or `TitleCase` name of the Tech to get
  8126. *
  8127. * @return {Tech|undefined}
  8128. * The `Tech` or undefined if there was no tech with the name requested.
  8129. */
  8130. static getTech(name) {
  8131. if (!name) {
  8132. return;
  8133. }
  8134. if (Tech.techs_ && Tech.techs_[name]) {
  8135. return Tech.techs_[name];
  8136. }
  8137. name = toTitleCase(name);
  8138. if (window && window.videojs && window.videojs[name]) {
  8139. log.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  8140. return window.videojs[name];
  8141. }
  8142. }
  8143. }
  8144. /**
  8145. * Get the {@link VideoTrackList}
  8146. *
  8147. * @returns {VideoTrackList}
  8148. * @method Tech.prototype.videoTracks
  8149. */
  8150. /**
  8151. * Get the {@link AudioTrackList}
  8152. *
  8153. * @returns {AudioTrackList}
  8154. * @method Tech.prototype.audioTracks
  8155. */
  8156. /**
  8157. * Get the {@link TextTrackList}
  8158. *
  8159. * @returns {TextTrackList}
  8160. * @method Tech.prototype.textTracks
  8161. */
  8162. /**
  8163. * Get the remote element {@link TextTrackList}
  8164. *
  8165. * @returns {TextTrackList}
  8166. * @method Tech.prototype.remoteTextTracks
  8167. */
  8168. /**
  8169. * Get the remote element {@link HtmlTrackElementList}
  8170. *
  8171. * @returns {HtmlTrackElementList}
  8172. * @method Tech.prototype.remoteTextTrackEls
  8173. */
  8174. ALL.names.forEach(function (name) {
  8175. const props = ALL[name];
  8176. Tech.prototype[props.getterName] = function () {
  8177. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8178. return this[props.privateName];
  8179. };
  8180. });
  8181. /**
  8182. * List of associated text tracks
  8183. *
  8184. * @type {TextTrackList}
  8185. * @private
  8186. * @property Tech#textTracks_
  8187. */
  8188. /**
  8189. * List of associated audio tracks.
  8190. *
  8191. * @type {AudioTrackList}
  8192. * @private
  8193. * @property Tech#audioTracks_
  8194. */
  8195. /**
  8196. * List of associated video tracks.
  8197. *
  8198. * @type {VideoTrackList}
  8199. * @private
  8200. * @property Tech#videoTracks_
  8201. */
  8202. /**
  8203. * Boolean indicating whether the `Tech` supports volume control.
  8204. *
  8205. * @type {boolean}
  8206. * @default
  8207. */
  8208. Tech.prototype.featuresVolumeControl = true;
  8209. /**
  8210. * Boolean indicating whether the `Tech` supports muting volume.
  8211. *
  8212. * @type {boolean}
  8213. * @default
  8214. */
  8215. Tech.prototype.featuresMuteControl = true;
  8216. /**
  8217. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8218. * Resizing plugins using request fullscreen reloads the plugin
  8219. *
  8220. * @type {boolean}
  8221. * @default
  8222. */
  8223. Tech.prototype.featuresFullscreenResize = false;
  8224. /**
  8225. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8226. * plays. Examples:
  8227. * - Set player to play 2x (twice) as fast
  8228. * - Set player to play 0.5x (half) as fast
  8229. *
  8230. * @type {boolean}
  8231. * @default
  8232. */
  8233. Tech.prototype.featuresPlaybackRate = false;
  8234. /**
  8235. * Boolean indicating whether the `Tech` supports the `progress` event.
  8236. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  8237. *
  8238. * @type {boolean}
  8239. * @default
  8240. */
  8241. Tech.prototype.featuresProgressEvents = false;
  8242. /**
  8243. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8244. *
  8245. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8246. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8247. * a new source.
  8248. *
  8249. * @type {boolean}
  8250. * @default
  8251. */
  8252. Tech.prototype.featuresSourceset = false;
  8253. /**
  8254. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  8255. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  8256. *
  8257. * @type {boolean}
  8258. * @default
  8259. */
  8260. Tech.prototype.featuresTimeupdateEvents = false;
  8261. /**
  8262. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8263. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8264. *
  8265. * @type {boolean}
  8266. * @default
  8267. */
  8268. Tech.prototype.featuresNativeTextTracks = false;
  8269. /**
  8270. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8271. *
  8272. * @type {boolean}
  8273. * @default
  8274. */
  8275. Tech.prototype.featuresVideoFrameCallback = false;
  8276. /**
  8277. * A functional mixin for techs that want to use the Source Handler pattern.
  8278. * Source handlers are scripts for handling specific formats.
  8279. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8280. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8281. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8282. *
  8283. * @param {Tech} _Tech
  8284. * The tech to add source handler functions to.
  8285. *
  8286. * @mixes Tech~SourceHandlerAdditions
  8287. */
  8288. Tech.withSourceHandlers = function (_Tech) {
  8289. /**
  8290. * Register a source handler
  8291. *
  8292. * @param {Function} handler
  8293. * The source handler class
  8294. *
  8295. * @param {number} [index]
  8296. * Register it at the following index
  8297. */
  8298. _Tech.registerSourceHandler = function (handler, index) {
  8299. let handlers = _Tech.sourceHandlers;
  8300. if (!handlers) {
  8301. handlers = _Tech.sourceHandlers = [];
  8302. }
  8303. if (index === undefined) {
  8304. // add to the end of the list
  8305. index = handlers.length;
  8306. }
  8307. handlers.splice(index, 0, handler);
  8308. };
  8309. /**
  8310. * Check if the tech can support the given type. Also checks the
  8311. * Techs sourceHandlers.
  8312. *
  8313. * @param {string} type
  8314. * The mimetype to check.
  8315. *
  8316. * @return {string}
  8317. * 'probably', 'maybe', or '' (empty string)
  8318. */
  8319. _Tech.canPlayType = function (type) {
  8320. const handlers = _Tech.sourceHandlers || [];
  8321. let can;
  8322. for (let i = 0; i < handlers.length; i++) {
  8323. can = handlers[i].canPlayType(type);
  8324. if (can) {
  8325. return can;
  8326. }
  8327. }
  8328. return '';
  8329. };
  8330. /**
  8331. * Returns the first source handler that supports the source.
  8332. *
  8333. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8334. *
  8335. * @param {Tech~SourceObject} source
  8336. * The source object
  8337. *
  8338. * @param {Object} options
  8339. * The options passed to the tech
  8340. *
  8341. * @return {SourceHandler|null}
  8342. * The first source handler that supports the source or null if
  8343. * no SourceHandler supports the source
  8344. */
  8345. _Tech.selectSourceHandler = function (source, options) {
  8346. const handlers = _Tech.sourceHandlers || [];
  8347. let can;
  8348. for (let i = 0; i < handlers.length; i++) {
  8349. can = handlers[i].canHandleSource(source, options);
  8350. if (can) {
  8351. return handlers[i];
  8352. }
  8353. }
  8354. return null;
  8355. };
  8356. /**
  8357. * Check if the tech can support the given source.
  8358. *
  8359. * @param {Tech~SourceObject} srcObj
  8360. * The source object
  8361. *
  8362. * @param {Object} options
  8363. * The options passed to the tech
  8364. *
  8365. * @return {string}
  8366. * 'probably', 'maybe', or '' (empty string)
  8367. */
  8368. _Tech.canPlaySource = function (srcObj, options) {
  8369. const sh = _Tech.selectSourceHandler(srcObj, options);
  8370. if (sh) {
  8371. return sh.canHandleSource(srcObj, options);
  8372. }
  8373. return '';
  8374. };
  8375. /**
  8376. * When using a source handler, prefer its implementation of
  8377. * any function normally provided by the tech.
  8378. */
  8379. const deferrable = ['seekable', 'seeking', 'duration'];
  8380. /**
  8381. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  8382. * function if it exists, with a fallback to the Techs seekable function.
  8383. *
  8384. * @method _Tech.seekable
  8385. */
  8386. /**
  8387. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  8388. * function if it exists, otherwise it will fallback to the techs duration function.
  8389. *
  8390. * @method _Tech.duration
  8391. */
  8392. deferrable.forEach(function (fnName) {
  8393. const originalFn = this[fnName];
  8394. if (typeof originalFn !== 'function') {
  8395. return;
  8396. }
  8397. this[fnName] = function () {
  8398. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  8399. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  8400. }
  8401. return originalFn.apply(this, arguments);
  8402. };
  8403. }, _Tech.prototype);
  8404. /**
  8405. * Create a function for setting the source using a source object
  8406. * and source handlers.
  8407. * Should never be called unless a source handler was found.
  8408. *
  8409. * @param {Tech~SourceObject} source
  8410. * A source object with src and type keys
  8411. */
  8412. _Tech.prototype.setSource = function (source) {
  8413. let sh = _Tech.selectSourceHandler(source, this.options_);
  8414. if (!sh) {
  8415. // Fall back to a native source handler when unsupported sources are
  8416. // deliberately set
  8417. if (_Tech.nativeSourceHandler) {
  8418. sh = _Tech.nativeSourceHandler;
  8419. } else {
  8420. log.error('No source handler found for the current source.');
  8421. }
  8422. }
  8423. // Dispose any existing source handler
  8424. this.disposeSourceHandler();
  8425. this.off('dispose', this.disposeSourceHandler_);
  8426. if (sh !== _Tech.nativeSourceHandler) {
  8427. this.currentSource_ = source;
  8428. }
  8429. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  8430. this.one('dispose', this.disposeSourceHandler_);
  8431. };
  8432. /**
  8433. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  8434. *
  8435. * @listens Tech#dispose
  8436. */
  8437. _Tech.prototype.disposeSourceHandler = function () {
  8438. // if we have a source and get another one
  8439. // then we are loading something new
  8440. // than clear all of our current tracks
  8441. if (this.currentSource_) {
  8442. this.clearTracks(['audio', 'video']);
  8443. this.currentSource_ = null;
  8444. }
  8445. // always clean up auto-text tracks
  8446. this.cleanupAutoTextTracks();
  8447. if (this.sourceHandler_) {
  8448. if (this.sourceHandler_.dispose) {
  8449. this.sourceHandler_.dispose();
  8450. }
  8451. this.sourceHandler_ = null;
  8452. }
  8453. };
  8454. };
  8455. // The base Tech class needs to be registered as a Component. It is the only
  8456. // Tech that can be registered as a Component.
  8457. Component.registerComponent('Tech', Tech);
  8458. Tech.registerTech('Tech', Tech);
  8459. /**
  8460. * A list of techs that should be added to techOrder on Players
  8461. *
  8462. * @private
  8463. */
  8464. Tech.defaultTechOrder_ = [];
  8465. /**
  8466. * @file middleware.js
  8467. * @module middleware
  8468. */
  8469. const middlewares = {};
  8470. const middlewareInstances = {};
  8471. const TERMINATOR = {};
  8472. /**
  8473. * A middleware object is a plain JavaScript object that has methods that
  8474. * match the {@link Tech} methods found in the lists of allowed
  8475. * {@link module:middleware.allowedGetters|getters},
  8476. * {@link module:middleware.allowedSetters|setters}, and
  8477. * {@link module:middleware.allowedMediators|mediators}.
  8478. *
  8479. * @typedef {Object} MiddlewareObject
  8480. */
  8481. /**
  8482. * A middleware factory function that should return a
  8483. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  8484. *
  8485. * This factory will be called for each player when needed, with the player
  8486. * passed in as an argument.
  8487. *
  8488. * @callback MiddlewareFactory
  8489. * @param { import('../player').default } player
  8490. * A Video.js player.
  8491. */
  8492. /**
  8493. * Define a middleware that the player should use by way of a factory function
  8494. * that returns a middleware object.
  8495. *
  8496. * @param {string} type
  8497. * The MIME type to match or `"*"` for all MIME types.
  8498. *
  8499. * @param {MiddlewareFactory} middleware
  8500. * A middleware factory function that will be executed for
  8501. * matching types.
  8502. */
  8503. function use(type, middleware) {
  8504. middlewares[type] = middlewares[type] || [];
  8505. middlewares[type].push(middleware);
  8506. }
  8507. /**
  8508. * Asynchronously sets a source using middleware by recursing through any
  8509. * matching middlewares and calling `setSource` on each, passing along the
  8510. * previous returned value each time.
  8511. *
  8512. * @param { import('../player').default } player
  8513. * A {@link Player} instance.
  8514. *
  8515. * @param {Tech~SourceObject} src
  8516. * A source object.
  8517. *
  8518. * @param {Function}
  8519. * The next middleware to run.
  8520. */
  8521. function setSource(player, src, next) {
  8522. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  8523. }
  8524. /**
  8525. * When the tech is set, passes the tech to each middleware's `setTech` method.
  8526. *
  8527. * @param {Object[]} middleware
  8528. * An array of middleware instances.
  8529. *
  8530. * @param { import('../tech/tech').default } tech
  8531. * A Video.js tech.
  8532. */
  8533. function setTech(middleware, tech) {
  8534. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  8535. }
  8536. /**
  8537. * Calls a getter on the tech first, through each middleware
  8538. * from right to left to the player.
  8539. *
  8540. * @param {Object[]} middleware
  8541. * An array of middleware instances.
  8542. *
  8543. * @param { import('../tech/tech').default } tech
  8544. * The current tech.
  8545. *
  8546. * @param {string} method
  8547. * A method name.
  8548. *
  8549. * @return {*}
  8550. * The final value from the tech after middleware has intercepted it.
  8551. */
  8552. function get(middleware, tech, method) {
  8553. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  8554. }
  8555. /**
  8556. * Takes the argument given to the player and calls the setter method on each
  8557. * middleware from left to right to the tech.
  8558. *
  8559. * @param {Object[]} middleware
  8560. * An array of middleware instances.
  8561. *
  8562. * @param { import('../tech/tech').default } tech
  8563. * The current tech.
  8564. *
  8565. * @param {string} method
  8566. * A method name.
  8567. *
  8568. * @param {*} arg
  8569. * The value to set on the tech.
  8570. *
  8571. * @return {*}
  8572. * The return value of the `method` of the `tech`.
  8573. */
  8574. function set(middleware, tech, method, arg) {
  8575. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  8576. }
  8577. /**
  8578. * Takes the argument given to the player and calls the `call` version of the
  8579. * method on each middleware from left to right.
  8580. *
  8581. * Then, call the passed in method on the tech and return the result unchanged
  8582. * back to the player, through middleware, this time from right to left.
  8583. *
  8584. * @param {Object[]} middleware
  8585. * An array of middleware instances.
  8586. *
  8587. * @param { import('../tech/tech').default } tech
  8588. * The current tech.
  8589. *
  8590. * @param {string} method
  8591. * A method name.
  8592. *
  8593. * @param {*} arg
  8594. * The value to set on the tech.
  8595. *
  8596. * @return {*}
  8597. * The return value of the `method` of the `tech`, regardless of the
  8598. * return values of middlewares.
  8599. */
  8600. function mediate(middleware, tech, method, arg = null) {
  8601. const callMethod = 'call' + toTitleCase(method);
  8602. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  8603. const terminated = middlewareValue === TERMINATOR;
  8604. // deprecated. The `null` return value should instead return TERMINATOR to
  8605. // prevent confusion if a techs method actually returns null.
  8606. const returnValue = terminated ? null : tech[method](middlewareValue);
  8607. executeRight(middleware, method, returnValue, terminated);
  8608. return returnValue;
  8609. }
  8610. /**
  8611. * Enumeration of allowed getters where the keys are method names.
  8612. *
  8613. * @type {Object}
  8614. */
  8615. const allowedGetters = {
  8616. buffered: 1,
  8617. currentTime: 1,
  8618. duration: 1,
  8619. muted: 1,
  8620. played: 1,
  8621. paused: 1,
  8622. seekable: 1,
  8623. volume: 1,
  8624. ended: 1
  8625. };
  8626. /**
  8627. * Enumeration of allowed setters where the keys are method names.
  8628. *
  8629. * @type {Object}
  8630. */
  8631. const allowedSetters = {
  8632. setCurrentTime: 1,
  8633. setMuted: 1,
  8634. setVolume: 1
  8635. };
  8636. /**
  8637. * Enumeration of allowed mediators where the keys are method names.
  8638. *
  8639. * @type {Object}
  8640. */
  8641. const allowedMediators = {
  8642. play: 1,
  8643. pause: 1
  8644. };
  8645. function middlewareIterator(method) {
  8646. return (value, mw) => {
  8647. // if the previous middleware terminated, pass along the termination
  8648. if (value === TERMINATOR) {
  8649. return TERMINATOR;
  8650. }
  8651. if (mw[method]) {
  8652. return mw[method](value);
  8653. }
  8654. return value;
  8655. };
  8656. }
  8657. function executeRight(mws, method, value, terminated) {
  8658. for (let i = mws.length - 1; i >= 0; i--) {
  8659. const mw = mws[i];
  8660. if (mw[method]) {
  8661. mw[method](terminated, value);
  8662. }
  8663. }
  8664. }
  8665. /**
  8666. * Clear the middleware cache for a player.
  8667. *
  8668. * @param { import('../player').default } player
  8669. * A {@link Player} instance.
  8670. */
  8671. function clearCacheForPlayer(player) {
  8672. middlewareInstances[player.id()] = null;
  8673. }
  8674. /**
  8675. * {
  8676. * [playerId]: [[mwFactory, mwInstance], ...]
  8677. * }
  8678. *
  8679. * @private
  8680. */
  8681. function getOrCreateFactory(player, mwFactory) {
  8682. const mws = middlewareInstances[player.id()];
  8683. let mw = null;
  8684. if (mws === undefined || mws === null) {
  8685. mw = mwFactory(player);
  8686. middlewareInstances[player.id()] = [[mwFactory, mw]];
  8687. return mw;
  8688. }
  8689. for (let i = 0; i < mws.length; i++) {
  8690. const [mwf, mwi] = mws[i];
  8691. if (mwf !== mwFactory) {
  8692. continue;
  8693. }
  8694. mw = mwi;
  8695. }
  8696. if (mw === null) {
  8697. mw = mwFactory(player);
  8698. mws.push([mwFactory, mw]);
  8699. }
  8700. return mw;
  8701. }
  8702. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  8703. const [mwFactory, ...mwrest] = middleware;
  8704. // if mwFactory is a string, then we're at a fork in the road
  8705. if (typeof mwFactory === 'string') {
  8706. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  8707. // if we have an mwFactory, call it with the player to get the mw,
  8708. // then call the mw's setSource method
  8709. } else if (mwFactory) {
  8710. const mw = getOrCreateFactory(player, mwFactory);
  8711. // if setSource isn't present, implicitly select this middleware
  8712. if (!mw.setSource) {
  8713. acc.push(mw);
  8714. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8715. }
  8716. mw.setSource(Object.assign({}, src), function (err, _src) {
  8717. // something happened, try the next middleware on the current level
  8718. // make sure to use the old src
  8719. if (err) {
  8720. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8721. }
  8722. // we've succeeded, now we need to go deeper
  8723. acc.push(mw);
  8724. // if it's the same type, continue down the current chain
  8725. // otherwise, we want to go down the new chain
  8726. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  8727. });
  8728. } else if (mwrest.length) {
  8729. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8730. } else if (lastRun) {
  8731. next(src, acc);
  8732. } else {
  8733. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  8734. }
  8735. }
  8736. /**
  8737. * Mimetypes
  8738. *
  8739. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  8740. * @typedef Mimetypes~Kind
  8741. * @enum
  8742. */
  8743. const MimetypesKind = {
  8744. opus: 'video/ogg',
  8745. ogv: 'video/ogg',
  8746. mp4: 'video/mp4',
  8747. mov: 'video/mp4',
  8748. m4v: 'video/mp4',
  8749. mkv: 'video/x-matroska',
  8750. m4a: 'audio/mp4',
  8751. mp3: 'audio/mpeg',
  8752. aac: 'audio/aac',
  8753. caf: 'audio/x-caf',
  8754. flac: 'audio/flac',
  8755. oga: 'audio/ogg',
  8756. wav: 'audio/wav',
  8757. m3u8: 'application/x-mpegURL',
  8758. mpd: 'application/dash+xml',
  8759. jpg: 'image/jpeg',
  8760. jpeg: 'image/jpeg',
  8761. gif: 'image/gif',
  8762. png: 'image/png',
  8763. svg: 'image/svg+xml',
  8764. webp: 'image/webp'
  8765. };
  8766. /**
  8767. * Get the mimetype of a given src url if possible
  8768. *
  8769. * @param {string} src
  8770. * The url to the src
  8771. *
  8772. * @return {string}
  8773. * return the mimetype if it was known or empty string otherwise
  8774. */
  8775. const getMimetype = function (src = '') {
  8776. const ext = getFileExtension(src);
  8777. const mimetype = MimetypesKind[ext.toLowerCase()];
  8778. return mimetype || '';
  8779. };
  8780. /**
  8781. * Find the mime type of a given source string if possible. Uses the player
  8782. * source cache.
  8783. *
  8784. * @param { import('../player').default } player
  8785. * The player object
  8786. *
  8787. * @param {string} src
  8788. * The source string
  8789. *
  8790. * @return {string}
  8791. * The type that was found
  8792. */
  8793. const findMimetype = (player, src) => {
  8794. if (!src) {
  8795. return '';
  8796. }
  8797. // 1. check for the type in the `source` cache
  8798. if (player.cache_.source.src === src && player.cache_.source.type) {
  8799. return player.cache_.source.type;
  8800. }
  8801. // 2. see if we have this source in our `currentSources` cache
  8802. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  8803. if (matchingSources.length) {
  8804. return matchingSources[0].type;
  8805. }
  8806. // 3. look for the src url in source elements and use the type there
  8807. const sources = player.$$('source');
  8808. for (let i = 0; i < sources.length; i++) {
  8809. const s = sources[i];
  8810. if (s.type && s.src && s.src === src) {
  8811. return s.type;
  8812. }
  8813. }
  8814. // 4. finally fallback to our list of mime types based on src url extension
  8815. return getMimetype(src);
  8816. };
  8817. /**
  8818. * @module filter-source
  8819. */
  8820. /**
  8821. * Filter out single bad source objects or multiple source objects in an
  8822. * array. Also flattens nested source object arrays into a 1 dimensional
  8823. * array of source objects.
  8824. *
  8825. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  8826. * The src object to filter
  8827. *
  8828. * @return {Tech~SourceObject[]}
  8829. * An array of sourceobjects containing only valid sources
  8830. *
  8831. * @private
  8832. */
  8833. const filterSource = function (src) {
  8834. // traverse array
  8835. if (Array.isArray(src)) {
  8836. let newsrc = [];
  8837. src.forEach(function (srcobj) {
  8838. srcobj = filterSource(srcobj);
  8839. if (Array.isArray(srcobj)) {
  8840. newsrc = newsrc.concat(srcobj);
  8841. } else if (isObject(srcobj)) {
  8842. newsrc.push(srcobj);
  8843. }
  8844. });
  8845. src = newsrc;
  8846. } else if (typeof src === 'string' && src.trim()) {
  8847. // convert string into object
  8848. src = [fixSource({
  8849. src
  8850. })];
  8851. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  8852. // src is already valid
  8853. src = [fixSource(src)];
  8854. } else {
  8855. // invalid source, turn it into an empty array
  8856. src = [];
  8857. }
  8858. return src;
  8859. };
  8860. /**
  8861. * Checks src mimetype, adding it when possible
  8862. *
  8863. * @param {Tech~SourceObject} src
  8864. * The src object to check
  8865. * @return {Tech~SourceObject}
  8866. * src Object with known type
  8867. */
  8868. function fixSource(src) {
  8869. if (!src.type) {
  8870. const mimetype = getMimetype(src.src);
  8871. if (mimetype) {
  8872. src.type = mimetype;
  8873. }
  8874. }
  8875. return src;
  8876. }
  8877. /**
  8878. * @file loader.js
  8879. */
  8880. /**
  8881. * The `MediaLoader` is the `Component` that decides which playback technology to load
  8882. * when a player is initialized.
  8883. *
  8884. * @extends Component
  8885. */
  8886. class MediaLoader extends Component {
  8887. /**
  8888. * Create an instance of this class.
  8889. *
  8890. * @param { import('../player').default } player
  8891. * The `Player` that this class should attach to.
  8892. *
  8893. * @param {Object} [options]
  8894. * The key/value store of player options.
  8895. *
  8896. * @param {Function} [ready]
  8897. * The function that is run when this component is ready.
  8898. */
  8899. constructor(player, options, ready) {
  8900. // MediaLoader has no element
  8901. const options_ = merge({
  8902. createEl: false
  8903. }, options);
  8904. super(player, options_, ready);
  8905. // If there are no sources when the player is initialized,
  8906. // load the first supported playback technology.
  8907. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  8908. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  8909. const techName = toTitleCase(j[i]);
  8910. let tech = Tech.getTech(techName);
  8911. // Support old behavior of techs being registered as components.
  8912. // Remove once that deprecated behavior is removed.
  8913. if (!techName) {
  8914. tech = Component.getComponent(techName);
  8915. }
  8916. // Check if the browser supports this technology
  8917. if (tech && tech.isSupported()) {
  8918. player.loadTech_(techName);
  8919. break;
  8920. }
  8921. }
  8922. } else {
  8923. // Loop through playback technologies (e.g. HTML5) and check for support.
  8924. // Then load the best source.
  8925. // A few assumptions here:
  8926. // All playback technologies respect preload false.
  8927. player.src(options.playerOptions.sources);
  8928. }
  8929. }
  8930. }
  8931. Component.registerComponent('MediaLoader', MediaLoader);
  8932. /**
  8933. * @file clickable-component.js
  8934. */
  8935. /**
  8936. * Component which is clickable or keyboard actionable, but is not a
  8937. * native HTML button.
  8938. *
  8939. * @extends Component
  8940. */
  8941. class ClickableComponent extends Component {
  8942. /**
  8943. * Creates an instance of this class.
  8944. *
  8945. * @param { import('./player').default } player
  8946. * The `Player` that this class should be attached to.
  8947. *
  8948. * @param {Object} [options]
  8949. * The key/value store of component options.
  8950. *
  8951. * @param {function} [options.clickHandler]
  8952. * The function to call when the button is clicked / activated
  8953. *
  8954. * @param {string} [options.controlText]
  8955. * The text to set on the button
  8956. *
  8957. * @param {string} [options.className]
  8958. * A class or space separated list of classes to add the component
  8959. *
  8960. */
  8961. constructor(player, options) {
  8962. super(player, options);
  8963. if (this.options_.controlText) {
  8964. this.controlText(this.options_.controlText);
  8965. }
  8966. this.handleMouseOver_ = e => this.handleMouseOver(e);
  8967. this.handleMouseOut_ = e => this.handleMouseOut(e);
  8968. this.handleClick_ = e => this.handleClick(e);
  8969. this.handleKeyDown_ = e => this.handleKeyDown(e);
  8970. this.emitTapEvents();
  8971. this.enable();
  8972. }
  8973. /**
  8974. * Create the `ClickableComponent`s DOM element.
  8975. *
  8976. * @param {string} [tag=div]
  8977. * The element's node type.
  8978. *
  8979. * @param {Object} [props={}]
  8980. * An object of properties that should be set on the element.
  8981. *
  8982. * @param {Object} [attributes={}]
  8983. * An object of attributes that should be set on the element.
  8984. *
  8985. * @return {Element}
  8986. * The element that gets created.
  8987. */
  8988. createEl(tag = 'div', props = {}, attributes = {}) {
  8989. props = Object.assign({
  8990. className: this.buildCSSClass(),
  8991. tabIndex: 0
  8992. }, props);
  8993. if (tag === 'button') {
  8994. log.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  8995. }
  8996. // Add ARIA attributes for clickable element which is not a native HTML button
  8997. attributes = Object.assign({
  8998. role: 'button'
  8999. }, attributes);
  9000. this.tabIndex_ = props.tabIndex;
  9001. const el = createEl(tag, props, attributes);
  9002. el.appendChild(createEl('span', {
  9003. className: 'vjs-icon-placeholder'
  9004. }, {
  9005. 'aria-hidden': true
  9006. }));
  9007. this.createControlTextEl(el);
  9008. return el;
  9009. }
  9010. dispose() {
  9011. // remove controlTextEl_ on dispose
  9012. this.controlTextEl_ = null;
  9013. super.dispose();
  9014. }
  9015. /**
  9016. * Create a control text element on this `ClickableComponent`
  9017. *
  9018. * @param {Element} [el]
  9019. * Parent element for the control text.
  9020. *
  9021. * @return {Element}
  9022. * The control text element that gets created.
  9023. */
  9024. createControlTextEl(el) {
  9025. this.controlTextEl_ = createEl('span', {
  9026. className: 'vjs-control-text'
  9027. }, {
  9028. // let the screen reader user know that the text of the element may change
  9029. 'aria-live': 'polite'
  9030. });
  9031. if (el) {
  9032. el.appendChild(this.controlTextEl_);
  9033. }
  9034. this.controlText(this.controlText_, el);
  9035. return this.controlTextEl_;
  9036. }
  9037. /**
  9038. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9039. *
  9040. * @param {string} [text]
  9041. * Control text for element.
  9042. *
  9043. * @param {Element} [el=this.el()]
  9044. * Element to set the title on.
  9045. *
  9046. * @return {string}
  9047. * - The control text when getting
  9048. */
  9049. controlText(text, el = this.el()) {
  9050. if (text === undefined) {
  9051. return this.controlText_ || 'Need Text';
  9052. }
  9053. const localizedText = this.localize(text);
  9054. /** @protected */
  9055. this.controlText_ = text;
  9056. textContent(this.controlTextEl_, localizedText);
  9057. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9058. // Set title attribute if only an icon is shown
  9059. el.setAttribute('title', localizedText);
  9060. }
  9061. }
  9062. /**
  9063. * Builds the default DOM `className`.
  9064. *
  9065. * @return {string}
  9066. * The DOM `className` for this object.
  9067. */
  9068. buildCSSClass() {
  9069. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  9070. }
  9071. /**
  9072. * Enable this `ClickableComponent`
  9073. */
  9074. enable() {
  9075. if (!this.enabled_) {
  9076. this.enabled_ = true;
  9077. this.removeClass('vjs-disabled');
  9078. this.el_.setAttribute('aria-disabled', 'false');
  9079. if (typeof this.tabIndex_ !== 'undefined') {
  9080. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9081. }
  9082. this.on(['tap', 'click'], this.handleClick_);
  9083. this.on('keydown', this.handleKeyDown_);
  9084. }
  9085. }
  9086. /**
  9087. * Disable this `ClickableComponent`
  9088. */
  9089. disable() {
  9090. this.enabled_ = false;
  9091. this.addClass('vjs-disabled');
  9092. this.el_.setAttribute('aria-disabled', 'true');
  9093. if (typeof this.tabIndex_ !== 'undefined') {
  9094. this.el_.removeAttribute('tabIndex');
  9095. }
  9096. this.off('mouseover', this.handleMouseOver_);
  9097. this.off('mouseout', this.handleMouseOut_);
  9098. this.off(['tap', 'click'], this.handleClick_);
  9099. this.off('keydown', this.handleKeyDown_);
  9100. }
  9101. /**
  9102. * Handles language change in ClickableComponent for the player in components
  9103. *
  9104. *
  9105. */
  9106. handleLanguagechange() {
  9107. this.controlText(this.controlText_);
  9108. }
  9109. /**
  9110. * Event handler that is called when a `ClickableComponent` receives a
  9111. * `click` or `tap` event.
  9112. *
  9113. * @param {Event} event
  9114. * The `tap` or `click` event that caused this function to be called.
  9115. *
  9116. * @listens tap
  9117. * @listens click
  9118. * @abstract
  9119. */
  9120. handleClick(event) {
  9121. if (this.options_.clickHandler) {
  9122. this.options_.clickHandler.call(this, arguments);
  9123. }
  9124. }
  9125. /**
  9126. * Event handler that is called when a `ClickableComponent` receives a
  9127. * `keydown` event.
  9128. *
  9129. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9130. *
  9131. * @param {Event} event
  9132. * The `keydown` event that caused this function to be called.
  9133. *
  9134. * @listens keydown
  9135. */
  9136. handleKeyDown(event) {
  9137. // Support Space or Enter key operation to fire a click event. Also,
  9138. // prevent the event from propagating through the DOM and triggering
  9139. // Player hotkeys.
  9140. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9141. event.preventDefault();
  9142. event.stopPropagation();
  9143. this.trigger('click');
  9144. } else {
  9145. // Pass keypress handling up for unsupported keys
  9146. super.handleKeyDown(event);
  9147. }
  9148. }
  9149. }
  9150. Component.registerComponent('ClickableComponent', ClickableComponent);
  9151. /**
  9152. * @file poster-image.js
  9153. */
  9154. /**
  9155. * A `ClickableComponent` that handles showing the poster image for the player.
  9156. *
  9157. * @extends ClickableComponent
  9158. */
  9159. class PosterImage extends ClickableComponent {
  9160. /**
  9161. * Create an instance of this class.
  9162. *
  9163. * @param { import('./player').default } player
  9164. * The `Player` that this class should attach to.
  9165. *
  9166. * @param {Object} [options]
  9167. * The key/value store of player options.
  9168. */
  9169. constructor(player, options) {
  9170. super(player, options);
  9171. this.update();
  9172. this.update_ = e => this.update(e);
  9173. player.on('posterchange', this.update_);
  9174. }
  9175. /**
  9176. * Clean up and dispose of the `PosterImage`.
  9177. */
  9178. dispose() {
  9179. this.player().off('posterchange', this.update_);
  9180. super.dispose();
  9181. }
  9182. /**
  9183. * Create the `PosterImage`s DOM element.
  9184. *
  9185. * @return {Element}
  9186. * The element that gets created.
  9187. */
  9188. createEl() {
  9189. // The el is an empty div to keep position in the DOM
  9190. // A picture and img el will be inserted when a source is set
  9191. return createEl('div', {
  9192. className: 'vjs-poster'
  9193. });
  9194. }
  9195. /**
  9196. * Get or set the `PosterImage`'s crossOrigin option.
  9197. *
  9198. * @param {string|null} [value]
  9199. * The value to set the crossOrigin to. If an argument is
  9200. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  9201. *
  9202. * @return {string|null}
  9203. * - The current crossOrigin value of the `Player` when getting.
  9204. * - undefined when setting
  9205. */
  9206. crossOrigin(value) {
  9207. // `null` can be set to unset a value
  9208. if (typeof value === 'undefined') {
  9209. if (this.$('img')) {
  9210. // If the poster's element exists, give its value
  9211. return this.$('img').crossOrigin;
  9212. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  9213. // If not but the tech is ready, query the tech
  9214. return this.player_.crossOrigin();
  9215. }
  9216. // Otherwise check options as the poster is usually set before the state of crossorigin
  9217. // can be retrieved by the getter
  9218. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  9219. }
  9220. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  9221. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  9222. return;
  9223. }
  9224. if (this.$('img')) {
  9225. this.$('img').crossOrigin = value;
  9226. }
  9227. return;
  9228. }
  9229. /**
  9230. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9231. *
  9232. * @listens Player#posterchange
  9233. *
  9234. * @param {Event} [event]
  9235. * The `Player#posterchange` event that triggered this function.
  9236. */
  9237. update(event) {
  9238. const url = this.player().poster();
  9239. this.setSrc(url);
  9240. // If there's no poster source we should display:none on this component
  9241. // so it's not still clickable or right-clickable
  9242. if (url) {
  9243. this.show();
  9244. } else {
  9245. this.hide();
  9246. }
  9247. }
  9248. /**
  9249. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  9250. * the inner picture and img elementss when needed.
  9251. *
  9252. * @param {string} [url]
  9253. * The URL to the source for the `PosterImage`. If not specified or falsy,
  9254. * any source and ant inner picture/img are removed.
  9255. */
  9256. setSrc(url) {
  9257. if (!url) {
  9258. this.el_.textContent = '';
  9259. return;
  9260. }
  9261. if (!this.$('img')) {
  9262. this.el_.appendChild(createEl('picture', {
  9263. className: 'vjs-poster',
  9264. // Don't want poster to be tabbable.
  9265. tabIndex: -1
  9266. }, {}, createEl('img', {
  9267. loading: 'lazy',
  9268. crossOrigin: this.crossOrigin()
  9269. }, {
  9270. alt: ''
  9271. })));
  9272. }
  9273. this.$('img').src = url;
  9274. }
  9275. /**
  9276. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9277. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9278. *
  9279. * @listens tap
  9280. * @listens click
  9281. * @listens keydown
  9282. *
  9283. * @param {Event} event
  9284. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9285. */
  9286. handleClick(event) {
  9287. // We don't want a click to trigger playback when controls are disabled
  9288. if (!this.player_.controls()) {
  9289. return;
  9290. }
  9291. if (this.player_.tech(true)) {
  9292. this.player_.tech(true).focus();
  9293. }
  9294. if (this.player_.paused()) {
  9295. silencePromise(this.player_.play());
  9296. } else {
  9297. this.player_.pause();
  9298. }
  9299. }
  9300. }
  9301. /**
  9302. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  9303. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  9304. * behavior.
  9305. *
  9306. * @param {string|null} [value]
  9307. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  9308. * given, must be one of `anonymous` or `use-credentials`.
  9309. *
  9310. * @return {string|null|undefined}
  9311. * - The current crossorigin value of the `Player` when getting.
  9312. * - undefined when setting
  9313. */
  9314. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  9315. Component.registerComponent('PosterImage', PosterImage);
  9316. /**
  9317. * @file text-track-display.js
  9318. */
  9319. const darkGray = '#222';
  9320. const lightGray = '#ccc';
  9321. const fontMap = {
  9322. monospace: 'monospace',
  9323. sansSerif: 'sans-serif',
  9324. serif: 'serif',
  9325. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9326. monospaceSerif: '"Courier New", monospace',
  9327. proportionalSansSerif: 'sans-serif',
  9328. proportionalSerif: 'serif',
  9329. casual: '"Comic Sans MS", Impact, fantasy',
  9330. script: '"Monotype Corsiva", cursive',
  9331. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9332. };
  9333. /**
  9334. * Construct an rgba color from a given hex color code.
  9335. *
  9336. * @param {number} color
  9337. * Hex number for color, like #f0e or #f604e2.
  9338. *
  9339. * @param {number} opacity
  9340. * Value for opacity, 0.0 - 1.0.
  9341. *
  9342. * @return {string}
  9343. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9344. */
  9345. function constructColor(color, opacity) {
  9346. let hex;
  9347. if (color.length === 4) {
  9348. // color looks like "#f0e"
  9349. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9350. } else if (color.length === 7) {
  9351. // color looks like "#f604e2"
  9352. hex = color.slice(1);
  9353. } else {
  9354. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9355. }
  9356. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9357. }
  9358. /**
  9359. * Try to update the style of a DOM element. Some style changes will throw an error,
  9360. * particularly in IE8. Those should be noops.
  9361. *
  9362. * @param {Element} el
  9363. * The DOM element to be styled.
  9364. *
  9365. * @param {string} style
  9366. * The CSS property on the element that should be styled.
  9367. *
  9368. * @param {string} rule
  9369. * The style rule that should be applied to the property.
  9370. *
  9371. * @private
  9372. */
  9373. function tryUpdateStyle(el, style, rule) {
  9374. try {
  9375. el.style[style] = rule;
  9376. } catch (e) {
  9377. // Satisfies linter.
  9378. return;
  9379. }
  9380. }
  9381. /**
  9382. * The component for displaying text track cues.
  9383. *
  9384. * @extends Component
  9385. */
  9386. class TextTrackDisplay extends Component {
  9387. /**
  9388. * Creates an instance of this class.
  9389. *
  9390. * @param { import('../player').default } player
  9391. * The `Player` that this class should be attached to.
  9392. *
  9393. * @param {Object} [options]
  9394. * The key/value store of player options.
  9395. *
  9396. * @param {Function} [ready]
  9397. * The function to call when `TextTrackDisplay` is ready.
  9398. */
  9399. constructor(player, options, ready) {
  9400. super(player, options, ready);
  9401. const updateDisplayHandler = e => this.updateDisplay(e);
  9402. player.on('loadstart', e => this.toggleDisplay(e));
  9403. player.on('texttrackchange', updateDisplayHandler);
  9404. player.on('loadedmetadata', e => this.preselectTrack(e));
  9405. // This used to be called during player init, but was causing an error
  9406. // if a track should show by default and the display hadn't loaded yet.
  9407. // Should probably be moved to an external track loader when we support
  9408. // tracks that don't need a display.
  9409. player.ready(bind_(this, function () {
  9410. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  9411. this.hide();
  9412. return;
  9413. }
  9414. player.on('fullscreenchange', updateDisplayHandler);
  9415. player.on('playerresize', updateDisplayHandler);
  9416. const screenOrientation = window.screen.orientation || window;
  9417. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  9418. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  9419. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  9420. const tracks = this.options_.playerOptions.tracks || [];
  9421. for (let i = 0; i < tracks.length; i++) {
  9422. this.player_.addRemoteTextTrack(tracks[i], true);
  9423. }
  9424. this.preselectTrack();
  9425. }));
  9426. }
  9427. /**
  9428. * Preselect a track following this precedence:
  9429. * - matches the previously selected {@link TextTrack}'s language and kind
  9430. * - matches the previously selected {@link TextTrack}'s language only
  9431. * - is the first default captions track
  9432. * - is the first default descriptions track
  9433. *
  9434. * @listens Player#loadstart
  9435. */
  9436. preselectTrack() {
  9437. const modes = {
  9438. captions: 1,
  9439. subtitles: 1
  9440. };
  9441. const trackList = this.player_.textTracks();
  9442. const userPref = this.player_.cache_.selectedLanguage;
  9443. let firstDesc;
  9444. let firstCaptions;
  9445. let preferredTrack;
  9446. for (let i = 0; i < trackList.length; i++) {
  9447. const track = trackList[i];
  9448. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  9449. // Always choose the track that matches both language and kind
  9450. if (track.kind === userPref.kind) {
  9451. preferredTrack = track;
  9452. // or choose the first track that matches language
  9453. } else if (!preferredTrack) {
  9454. preferredTrack = track;
  9455. }
  9456. // clear everything if offTextTrackMenuItem was clicked
  9457. } else if (userPref && !userPref.enabled) {
  9458. preferredTrack = null;
  9459. firstDesc = null;
  9460. firstCaptions = null;
  9461. } else if (track.default) {
  9462. if (track.kind === 'descriptions' && !firstDesc) {
  9463. firstDesc = track;
  9464. } else if (track.kind in modes && !firstCaptions) {
  9465. firstCaptions = track;
  9466. }
  9467. }
  9468. }
  9469. // The preferredTrack matches the user preference and takes
  9470. // precedence over all the other tracks.
  9471. // So, display the preferredTrack before the first default track
  9472. // and the subtitles/captions track before the descriptions track
  9473. if (preferredTrack) {
  9474. preferredTrack.mode = 'showing';
  9475. } else if (firstCaptions) {
  9476. firstCaptions.mode = 'showing';
  9477. } else if (firstDesc) {
  9478. firstDesc.mode = 'showing';
  9479. }
  9480. }
  9481. /**
  9482. * Turn display of {@link TextTrack}'s from the current state into the other state.
  9483. * There are only two states:
  9484. * - 'shown'
  9485. * - 'hidden'
  9486. *
  9487. * @listens Player#loadstart
  9488. */
  9489. toggleDisplay() {
  9490. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  9491. this.hide();
  9492. } else {
  9493. this.show();
  9494. }
  9495. }
  9496. /**
  9497. * Create the {@link Component}'s DOM element.
  9498. *
  9499. * @return {Element}
  9500. * The element that was created.
  9501. */
  9502. createEl() {
  9503. return super.createEl('div', {
  9504. className: 'vjs-text-track-display'
  9505. }, {
  9506. 'translate': 'yes',
  9507. 'aria-live': 'off',
  9508. 'aria-atomic': 'true'
  9509. });
  9510. }
  9511. /**
  9512. * Clear all displayed {@link TextTrack}s.
  9513. */
  9514. clearDisplay() {
  9515. if (typeof window.WebVTT === 'function') {
  9516. window.WebVTT.processCues(window, [], this.el_);
  9517. }
  9518. }
  9519. /**
  9520. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  9521. * a {@link Player#fullscreenchange} is fired.
  9522. *
  9523. * @listens Player#texttrackchange
  9524. * @listens Player#fullscreenchange
  9525. */
  9526. updateDisplay() {
  9527. const tracks = this.player_.textTracks();
  9528. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  9529. this.clearDisplay();
  9530. if (allowMultipleShowingTracks) {
  9531. const showingTracks = [];
  9532. for (let i = 0; i < tracks.length; ++i) {
  9533. const track = tracks[i];
  9534. if (track.mode !== 'showing') {
  9535. continue;
  9536. }
  9537. showingTracks.push(track);
  9538. }
  9539. this.updateForTrack(showingTracks);
  9540. return;
  9541. }
  9542. // Track display prioritization model: if multiple tracks are 'showing',
  9543. // display the first 'subtitles' or 'captions' track which is 'showing',
  9544. // otherwise display the first 'descriptions' track which is 'showing'
  9545. let descriptionsTrack = null;
  9546. let captionsSubtitlesTrack = null;
  9547. let i = tracks.length;
  9548. while (i--) {
  9549. const track = tracks[i];
  9550. if (track.mode === 'showing') {
  9551. if (track.kind === 'descriptions') {
  9552. descriptionsTrack = track;
  9553. } else {
  9554. captionsSubtitlesTrack = track;
  9555. }
  9556. }
  9557. }
  9558. if (captionsSubtitlesTrack) {
  9559. if (this.getAttribute('aria-live') !== 'off') {
  9560. this.setAttribute('aria-live', 'off');
  9561. }
  9562. this.updateForTrack(captionsSubtitlesTrack);
  9563. } else if (descriptionsTrack) {
  9564. if (this.getAttribute('aria-live') !== 'assertive') {
  9565. this.setAttribute('aria-live', 'assertive');
  9566. }
  9567. this.updateForTrack(descriptionsTrack);
  9568. }
  9569. }
  9570. /**
  9571. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  9572. *
  9573. * @param {TextTrack} track
  9574. * Text track object containing active cues to style.
  9575. */
  9576. updateDisplayState(track) {
  9577. const overrides = this.player_.textTrackSettings.getValues();
  9578. const cues = track.activeCues;
  9579. let i = cues.length;
  9580. while (i--) {
  9581. const cue = cues[i];
  9582. if (!cue) {
  9583. continue;
  9584. }
  9585. const cueDiv = cue.displayState;
  9586. if (overrides.color) {
  9587. cueDiv.firstChild.style.color = overrides.color;
  9588. }
  9589. if (overrides.textOpacity) {
  9590. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  9591. }
  9592. if (overrides.backgroundColor) {
  9593. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  9594. }
  9595. if (overrides.backgroundOpacity) {
  9596. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  9597. }
  9598. if (overrides.windowColor) {
  9599. if (overrides.windowOpacity) {
  9600. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  9601. } else {
  9602. cueDiv.style.backgroundColor = overrides.windowColor;
  9603. }
  9604. }
  9605. if (overrides.edgeStyle) {
  9606. if (overrides.edgeStyle === 'dropshadow') {
  9607. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  9608. } else if (overrides.edgeStyle === 'raised') {
  9609. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  9610. } else if (overrides.edgeStyle === 'depressed') {
  9611. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  9612. } else if (overrides.edgeStyle === 'uniform') {
  9613. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  9614. }
  9615. }
  9616. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  9617. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  9618. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  9619. cueDiv.style.height = 'auto';
  9620. cueDiv.style.top = 'auto';
  9621. }
  9622. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  9623. if (overrides.fontFamily === 'small-caps') {
  9624. cueDiv.firstChild.style.fontVariant = 'small-caps';
  9625. } else {
  9626. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  9627. }
  9628. }
  9629. }
  9630. }
  9631. /**
  9632. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  9633. *
  9634. * @param {TextTrack|TextTrack[]} tracks
  9635. * Text track object or text track array to be added to the list.
  9636. */
  9637. updateForTrack(tracks) {
  9638. if (!Array.isArray(tracks)) {
  9639. tracks = [tracks];
  9640. }
  9641. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  9642. return !track.activeCues;
  9643. })) {
  9644. return;
  9645. }
  9646. const cues = [];
  9647. // push all active track cues
  9648. for (let i = 0; i < tracks.length; ++i) {
  9649. const track = tracks[i];
  9650. for (let j = 0; j < track.activeCues.length; ++j) {
  9651. cues.push(track.activeCues[j]);
  9652. }
  9653. }
  9654. // removes all cues before it processes new ones
  9655. window.WebVTT.processCues(window, cues, this.el_);
  9656. // add unique class to each language text track & add settings styling if necessary
  9657. for (let i = 0; i < tracks.length; ++i) {
  9658. const track = tracks[i];
  9659. for (let j = 0; j < track.activeCues.length; ++j) {
  9660. const cueEl = track.activeCues[j].displayState;
  9661. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  9662. if (track.language) {
  9663. setAttribute(cueEl, 'lang', track.language);
  9664. }
  9665. }
  9666. if (this.player_.textTrackSettings) {
  9667. this.updateDisplayState(track);
  9668. }
  9669. }
  9670. }
  9671. }
  9672. Component.registerComponent('TextTrackDisplay', TextTrackDisplay);
  9673. /**
  9674. * @file loading-spinner.js
  9675. */
  9676. /**
  9677. * A loading spinner for use during waiting/loading events.
  9678. *
  9679. * @extends Component
  9680. */
  9681. class LoadingSpinner extends Component {
  9682. /**
  9683. * Create the `LoadingSpinner`s DOM element.
  9684. *
  9685. * @return {Element}
  9686. * The dom element that gets created.
  9687. */
  9688. createEl() {
  9689. const isAudio = this.player_.isAudio();
  9690. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  9691. const controlText = createEl('span', {
  9692. className: 'vjs-control-text',
  9693. textContent: this.localize('{1} is loading.', [playerType])
  9694. });
  9695. const el = super.createEl('div', {
  9696. className: 'vjs-loading-spinner',
  9697. dir: 'ltr'
  9698. });
  9699. el.appendChild(controlText);
  9700. return el;
  9701. }
  9702. /**
  9703. * Update control text on languagechange
  9704. */
  9705. handleLanguagechange() {
  9706. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  9707. }
  9708. }
  9709. Component.registerComponent('LoadingSpinner', LoadingSpinner);
  9710. /**
  9711. * @file button.js
  9712. */
  9713. /**
  9714. * Base class for all buttons.
  9715. *
  9716. * @extends ClickableComponent
  9717. */
  9718. class Button extends ClickableComponent {
  9719. /**
  9720. * Create the `Button`s DOM element.
  9721. *
  9722. * @param {string} [tag="button"]
  9723. * The element's node type. This argument is IGNORED: no matter what
  9724. * is passed, it will always create a `button` element.
  9725. *
  9726. * @param {Object} [props={}]
  9727. * An object of properties that should be set on the element.
  9728. *
  9729. * @param {Object} [attributes={}]
  9730. * An object of attributes that should be set on the element.
  9731. *
  9732. * @return {Element}
  9733. * The element that gets created.
  9734. */
  9735. createEl(tag, props = {}, attributes = {}) {
  9736. tag = 'button';
  9737. props = Object.assign({
  9738. className: this.buildCSSClass()
  9739. }, props);
  9740. // Add attributes for button element
  9741. attributes = Object.assign({
  9742. // Necessary since the default button type is "submit"
  9743. type: 'button'
  9744. }, attributes);
  9745. const el = createEl(tag, props, attributes);
  9746. el.appendChild(createEl('span', {
  9747. className: 'vjs-icon-placeholder'
  9748. }, {
  9749. 'aria-hidden': true
  9750. }));
  9751. this.createControlTextEl(el);
  9752. return el;
  9753. }
  9754. /**
  9755. * Add a child `Component` inside of this `Button`.
  9756. *
  9757. * @param {string|Component} child
  9758. * The name or instance of a child to add.
  9759. *
  9760. * @param {Object} [options={}]
  9761. * The key/value store of options that will get passed to children of
  9762. * the child.
  9763. *
  9764. * @return {Component}
  9765. * The `Component` that gets added as a child. When using a string the
  9766. * `Component` will get created by this process.
  9767. *
  9768. * @deprecated since version 5
  9769. */
  9770. addChild(child, options = {}) {
  9771. const className = this.constructor.name;
  9772. log.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  9773. // Avoid the error message generated by ClickableComponent's addChild method
  9774. return Component.prototype.addChild.call(this, child, options);
  9775. }
  9776. /**
  9777. * Enable the `Button` element so that it can be activated or clicked. Use this with
  9778. * {@link Button#disable}.
  9779. */
  9780. enable() {
  9781. super.enable();
  9782. this.el_.removeAttribute('disabled');
  9783. }
  9784. /**
  9785. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  9786. * {@link Button#enable}.
  9787. */
  9788. disable() {
  9789. super.disable();
  9790. this.el_.setAttribute('disabled', 'disabled');
  9791. }
  9792. /**
  9793. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  9794. * press.
  9795. *
  9796. * @param {Event} event
  9797. * The event that caused this function to get called.
  9798. *
  9799. * @listens keydown
  9800. */
  9801. handleKeyDown(event) {
  9802. // Ignore Space or Enter key operation, which is handled by the browser for
  9803. // a button - though not for its super class, ClickableComponent. Also,
  9804. // prevent the event from propagating through the DOM and triggering Player
  9805. // hotkeys. We do not preventDefault here because we _want_ the browser to
  9806. // handle it.
  9807. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9808. event.stopPropagation();
  9809. return;
  9810. }
  9811. // Pass keypress handling up for unsupported keys
  9812. super.handleKeyDown(event);
  9813. }
  9814. }
  9815. Component.registerComponent('Button', Button);
  9816. /**
  9817. * @file big-play-button.js
  9818. */
  9819. /**
  9820. * The initial play button that shows before the video has played. The hiding of the
  9821. * `BigPlayButton` get done via CSS and `Player` states.
  9822. *
  9823. * @extends Button
  9824. */
  9825. class BigPlayButton extends Button {
  9826. constructor(player, options) {
  9827. super(player, options);
  9828. this.mouseused_ = false;
  9829. this.on('mousedown', e => this.handleMouseDown(e));
  9830. }
  9831. /**
  9832. * Builds the default DOM `className`.
  9833. *
  9834. * @return {string}
  9835. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  9836. */
  9837. buildCSSClass() {
  9838. return 'vjs-big-play-button';
  9839. }
  9840. /**
  9841. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  9842. * for more detailed information on what a click can be.
  9843. *
  9844. * @param {KeyboardEvent} event
  9845. * The `keydown`, `tap`, or `click` event that caused this function to be
  9846. * called.
  9847. *
  9848. * @listens tap
  9849. * @listens click
  9850. */
  9851. handleClick(event) {
  9852. const playPromise = this.player_.play();
  9853. // exit early if clicked via the mouse
  9854. if (this.mouseused_ && event.clientX && event.clientY) {
  9855. silencePromise(playPromise);
  9856. if (this.player_.tech(true)) {
  9857. this.player_.tech(true).focus();
  9858. }
  9859. return;
  9860. }
  9861. const cb = this.player_.getChild('controlBar');
  9862. const playToggle = cb && cb.getChild('playToggle');
  9863. if (!playToggle) {
  9864. this.player_.tech(true).focus();
  9865. return;
  9866. }
  9867. const playFocus = () => playToggle.focus();
  9868. if (isPromise(playPromise)) {
  9869. playPromise.then(playFocus, () => {});
  9870. } else {
  9871. this.setTimeout(playFocus, 1);
  9872. }
  9873. }
  9874. handleKeyDown(event) {
  9875. this.mouseused_ = false;
  9876. super.handleKeyDown(event);
  9877. }
  9878. handleMouseDown(event) {
  9879. this.mouseused_ = true;
  9880. }
  9881. }
  9882. /**
  9883. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  9884. *
  9885. * @type {string}
  9886. * @protected
  9887. */
  9888. BigPlayButton.prototype.controlText_ = 'Play Video';
  9889. Component.registerComponent('BigPlayButton', BigPlayButton);
  9890. /**
  9891. * @file close-button.js
  9892. */
  9893. /**
  9894. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  9895. * it gets clicked.
  9896. *
  9897. * @extends Button
  9898. */
  9899. class CloseButton extends Button {
  9900. /**
  9901. * Creates an instance of the this class.
  9902. *
  9903. * @param { import('./player').default } player
  9904. * The `Player` that this class should be attached to.
  9905. *
  9906. * @param {Object} [options]
  9907. * The key/value store of player options.
  9908. */
  9909. constructor(player, options) {
  9910. super(player, options);
  9911. this.controlText(options && options.controlText || this.localize('Close'));
  9912. }
  9913. /**
  9914. * Builds the default DOM `className`.
  9915. *
  9916. * @return {string}
  9917. * The DOM `className` for this object.
  9918. */
  9919. buildCSSClass() {
  9920. return `vjs-close-button ${super.buildCSSClass()}`;
  9921. }
  9922. /**
  9923. * This gets called when a `CloseButton` gets clicked. See
  9924. * {@link ClickableComponent#handleClick} for more information on when
  9925. * this will be triggered
  9926. *
  9927. * @param {Event} event
  9928. * The `keydown`, `tap`, or `click` event that caused this function to be
  9929. * called.
  9930. *
  9931. * @listens tap
  9932. * @listens click
  9933. * @fires CloseButton#close
  9934. */
  9935. handleClick(event) {
  9936. /**
  9937. * Triggered when the a `CloseButton` is clicked.
  9938. *
  9939. * @event CloseButton#close
  9940. * @type {Event}
  9941. *
  9942. * @property {boolean} [bubbles=false]
  9943. * set to false so that the close event does not
  9944. * bubble up to parents if there is no listener
  9945. */
  9946. this.trigger({
  9947. type: 'close',
  9948. bubbles: false
  9949. });
  9950. }
  9951. /**
  9952. * Event handler that is called when a `CloseButton` receives a
  9953. * `keydown` event.
  9954. *
  9955. * By default, if the key is Esc, it will trigger a `click` event.
  9956. *
  9957. * @param {Event} event
  9958. * The `keydown` event that caused this function to be called.
  9959. *
  9960. * @listens keydown
  9961. */
  9962. handleKeyDown(event) {
  9963. // Esc button will trigger `click` event
  9964. if (keycode.isEventKey(event, 'Esc')) {
  9965. event.preventDefault();
  9966. event.stopPropagation();
  9967. this.trigger('click');
  9968. } else {
  9969. // Pass keypress handling up for unsupported keys
  9970. super.handleKeyDown(event);
  9971. }
  9972. }
  9973. }
  9974. Component.registerComponent('CloseButton', CloseButton);
  9975. /**
  9976. * @file play-toggle.js
  9977. */
  9978. /**
  9979. * Button to toggle between play and pause.
  9980. *
  9981. * @extends Button
  9982. */
  9983. class PlayToggle extends Button {
  9984. /**
  9985. * Creates an instance of this class.
  9986. *
  9987. * @param { import('./player').default } player
  9988. * The `Player` that this class should be attached to.
  9989. *
  9990. * @param {Object} [options={}]
  9991. * The key/value store of player options.
  9992. */
  9993. constructor(player, options = {}) {
  9994. super(player, options);
  9995. // show or hide replay icon
  9996. options.replay = options.replay === undefined || options.replay;
  9997. this.on(player, 'play', e => this.handlePlay(e));
  9998. this.on(player, 'pause', e => this.handlePause(e));
  9999. if (options.replay) {
  10000. this.on(player, 'ended', e => this.handleEnded(e));
  10001. }
  10002. }
  10003. /**
  10004. * Builds the default DOM `className`.
  10005. *
  10006. * @return {string}
  10007. * The DOM `className` for this object.
  10008. */
  10009. buildCSSClass() {
  10010. return `vjs-play-control ${super.buildCSSClass()}`;
  10011. }
  10012. /**
  10013. * This gets called when an `PlayToggle` is "clicked". See
  10014. * {@link ClickableComponent} for more detailed information on what a click can be.
  10015. *
  10016. * @param {Event} [event]
  10017. * The `keydown`, `tap`, or `click` event that caused this function to be
  10018. * called.
  10019. *
  10020. * @listens tap
  10021. * @listens click
  10022. */
  10023. handleClick(event) {
  10024. if (this.player_.paused()) {
  10025. silencePromise(this.player_.play());
  10026. } else {
  10027. this.player_.pause();
  10028. }
  10029. }
  10030. /**
  10031. * This gets called once after the video has ended and the user seeks so that
  10032. * we can change the replay button back to a play button.
  10033. *
  10034. * @param {Event} [event]
  10035. * The event that caused this function to run.
  10036. *
  10037. * @listens Player#seeked
  10038. */
  10039. handleSeeked(event) {
  10040. this.removeClass('vjs-ended');
  10041. if (this.player_.paused()) {
  10042. this.handlePause(event);
  10043. } else {
  10044. this.handlePlay(event);
  10045. }
  10046. }
  10047. /**
  10048. * Add the vjs-playing class to the element so it can change appearance.
  10049. *
  10050. * @param {Event} [event]
  10051. * The event that caused this function to run.
  10052. *
  10053. * @listens Player#play
  10054. */
  10055. handlePlay(event) {
  10056. this.removeClass('vjs-ended', 'vjs-paused');
  10057. this.addClass('vjs-playing');
  10058. // change the button text to "Pause"
  10059. this.controlText('Pause');
  10060. }
  10061. /**
  10062. * Add the vjs-paused class to the element so it can change appearance.
  10063. *
  10064. * @param {Event} [event]
  10065. * The event that caused this function to run.
  10066. *
  10067. * @listens Player#pause
  10068. */
  10069. handlePause(event) {
  10070. this.removeClass('vjs-playing');
  10071. this.addClass('vjs-paused');
  10072. // change the button text to "Play"
  10073. this.controlText('Play');
  10074. }
  10075. /**
  10076. * Add the vjs-ended class to the element so it can change appearance
  10077. *
  10078. * @param {Event} [event]
  10079. * The event that caused this function to run.
  10080. *
  10081. * @listens Player#ended
  10082. */
  10083. handleEnded(event) {
  10084. this.removeClass('vjs-playing');
  10085. this.addClass('vjs-ended');
  10086. // change the button text to "Replay"
  10087. this.controlText('Replay');
  10088. // on the next seek remove the replay button
  10089. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  10090. }
  10091. }
  10092. /**
  10093. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10094. *
  10095. * @type {string}
  10096. * @protected
  10097. */
  10098. PlayToggle.prototype.controlText_ = 'Play';
  10099. Component.registerComponent('PlayToggle', PlayToggle);
  10100. /**
  10101. * @file time-display.js
  10102. */
  10103. /**
  10104. * Displays time information about the video
  10105. *
  10106. * @extends Component
  10107. */
  10108. class TimeDisplay extends Component {
  10109. /**
  10110. * Creates an instance of this class.
  10111. *
  10112. * @param { import('../../player').default } player
  10113. * The `Player` that this class should be attached to.
  10114. *
  10115. * @param {Object} [options]
  10116. * The key/value store of player options.
  10117. */
  10118. constructor(player, options) {
  10119. super(player, options);
  10120. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  10121. this.updateTextNode_();
  10122. }
  10123. /**
  10124. * Create the `Component`'s DOM element
  10125. *
  10126. * @return {Element}
  10127. * The element that was created.
  10128. */
  10129. createEl() {
  10130. const className = this.buildCSSClass();
  10131. const el = super.createEl('div', {
  10132. className: `${className} vjs-time-control vjs-control`
  10133. });
  10134. const span = createEl('span', {
  10135. className: 'vjs-control-text',
  10136. textContent: `${this.localize(this.labelText_)}\u00a0`
  10137. }, {
  10138. role: 'presentation'
  10139. });
  10140. el.appendChild(span);
  10141. this.contentEl_ = createEl('span', {
  10142. className: `${className}-display`
  10143. }, {
  10144. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10145. // treat them as a break between items in the DOM when using arrow keys
  10146. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10147. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10148. role: 'presentation'
  10149. });
  10150. el.appendChild(this.contentEl_);
  10151. return el;
  10152. }
  10153. dispose() {
  10154. this.contentEl_ = null;
  10155. this.textNode_ = null;
  10156. super.dispose();
  10157. }
  10158. /**
  10159. * Updates the time display text node with a new time
  10160. *
  10161. * @param {number} [time=0] the time to update to
  10162. *
  10163. * @private
  10164. */
  10165. updateTextNode_(time = 0) {
  10166. time = formatTime(time);
  10167. if (this.formattedTime_ === time) {
  10168. return;
  10169. }
  10170. this.formattedTime_ = time;
  10171. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  10172. if (!this.contentEl_) {
  10173. return;
  10174. }
  10175. let oldNode = this.textNode_;
  10176. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  10177. oldNode = null;
  10178. log.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');
  10179. }
  10180. this.textNode_ = document.createTextNode(this.formattedTime_);
  10181. if (!this.textNode_) {
  10182. return;
  10183. }
  10184. if (oldNode) {
  10185. this.contentEl_.replaceChild(this.textNode_, oldNode);
  10186. } else {
  10187. this.contentEl_.appendChild(this.textNode_);
  10188. }
  10189. });
  10190. }
  10191. /**
  10192. * To be filled out in the child class, should update the displayed time
  10193. * in accordance with the fact that the current time has changed.
  10194. *
  10195. * @param {Event} [event]
  10196. * The `timeupdate` event that caused this to run.
  10197. *
  10198. * @listens Player#timeupdate
  10199. */
  10200. updateContent(event) {}
  10201. }
  10202. /**
  10203. * The text that is added to the `TimeDisplay` for screen reader users.
  10204. *
  10205. * @type {string}
  10206. * @private
  10207. */
  10208. TimeDisplay.prototype.labelText_ = 'Time';
  10209. /**
  10210. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10211. *
  10212. * @type {string}
  10213. * @protected
  10214. *
  10215. * @deprecated in v7; controlText_ is not used in non-active display Components
  10216. */
  10217. TimeDisplay.prototype.controlText_ = 'Time';
  10218. Component.registerComponent('TimeDisplay', TimeDisplay);
  10219. /**
  10220. * @file current-time-display.js
  10221. */
  10222. /**
  10223. * Displays the current time
  10224. *
  10225. * @extends Component
  10226. */
  10227. class CurrentTimeDisplay extends TimeDisplay {
  10228. /**
  10229. * Builds the default DOM `className`.
  10230. *
  10231. * @return {string}
  10232. * The DOM `className` for this object.
  10233. */
  10234. buildCSSClass() {
  10235. return 'vjs-current-time';
  10236. }
  10237. /**
  10238. * Update current time display
  10239. *
  10240. * @param {Event} [event]
  10241. * The `timeupdate` event that caused this function to run.
  10242. *
  10243. * @listens Player#timeupdate
  10244. */
  10245. updateContent(event) {
  10246. // Allows for smooth scrubbing, when player can't keep up.
  10247. let time;
  10248. if (this.player_.ended()) {
  10249. time = this.player_.duration();
  10250. } else {
  10251. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  10252. }
  10253. this.updateTextNode_(time);
  10254. }
  10255. }
  10256. /**
  10257. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  10258. *
  10259. * @type {string}
  10260. * @private
  10261. */
  10262. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  10263. /**
  10264. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  10265. *
  10266. * @type {string}
  10267. * @protected
  10268. *
  10269. * @deprecated in v7; controlText_ is not used in non-active display Components
  10270. */
  10271. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  10272. Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  10273. /**
  10274. * @file duration-display.js
  10275. */
  10276. /**
  10277. * Displays the duration
  10278. *
  10279. * @extends Component
  10280. */
  10281. class DurationDisplay extends TimeDisplay {
  10282. /**
  10283. * Creates an instance of this class.
  10284. *
  10285. * @param { import('../../player').default } player
  10286. * The `Player` that this class should be attached to.
  10287. *
  10288. * @param {Object} [options]
  10289. * The key/value store of player options.
  10290. */
  10291. constructor(player, options) {
  10292. super(player, options);
  10293. const updateContent = e => this.updateContent(e);
  10294. // we do not want to/need to throttle duration changes,
  10295. // as they should always display the changed duration as
  10296. // it has changed
  10297. this.on(player, 'durationchange', updateContent);
  10298. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  10299. // but the durationchange on the user agent will not fire.
  10300. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  10301. this.on(player, 'loadstart', updateContent);
  10302. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  10303. // listeners could have broken dependent applications/libraries. These
  10304. // can likely be removed for 7.0.
  10305. this.on(player, 'loadedmetadata', updateContent);
  10306. }
  10307. /**
  10308. * Builds the default DOM `className`.
  10309. *
  10310. * @return {string}
  10311. * The DOM `className` for this object.
  10312. */
  10313. buildCSSClass() {
  10314. return 'vjs-duration';
  10315. }
  10316. /**
  10317. * Update duration time display.
  10318. *
  10319. * @param {Event} [event]
  10320. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  10321. * this function to be called.
  10322. *
  10323. * @listens Player#durationchange
  10324. * @listens Player#timeupdate
  10325. * @listens Player#loadedmetadata
  10326. */
  10327. updateContent(event) {
  10328. const duration = this.player_.duration();
  10329. this.updateTextNode_(duration);
  10330. }
  10331. }
  10332. /**
  10333. * The text that is added to the `DurationDisplay` for screen reader users.
  10334. *
  10335. * @type {string}
  10336. * @private
  10337. */
  10338. DurationDisplay.prototype.labelText_ = 'Duration';
  10339. /**
  10340. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  10341. *
  10342. * @type {string}
  10343. * @protected
  10344. *
  10345. * @deprecated in v7; controlText_ is not used in non-active display Components
  10346. */
  10347. DurationDisplay.prototype.controlText_ = 'Duration';
  10348. Component.registerComponent('DurationDisplay', DurationDisplay);
  10349. /**
  10350. * @file time-divider.js
  10351. */
  10352. /**
  10353. * The separator between the current time and duration.
  10354. * Can be hidden if it's not needed in the design.
  10355. *
  10356. * @extends Component
  10357. */
  10358. class TimeDivider extends Component {
  10359. /**
  10360. * Create the component's DOM element
  10361. *
  10362. * @return {Element}
  10363. * The element that was created.
  10364. */
  10365. createEl() {
  10366. const el = super.createEl('div', {
  10367. className: 'vjs-time-control vjs-time-divider'
  10368. }, {
  10369. // this element and its contents can be hidden from assistive techs since
  10370. // it is made extraneous by the announcement of the control text
  10371. // for the current time and duration displays
  10372. 'aria-hidden': true
  10373. });
  10374. const div = super.createEl('div');
  10375. const span = super.createEl('span', {
  10376. textContent: '/'
  10377. });
  10378. div.appendChild(span);
  10379. el.appendChild(div);
  10380. return el;
  10381. }
  10382. }
  10383. Component.registerComponent('TimeDivider', TimeDivider);
  10384. /**
  10385. * @file remaining-time-display.js
  10386. */
  10387. /**
  10388. * Displays the time left in the video
  10389. *
  10390. * @extends Component
  10391. */
  10392. class RemainingTimeDisplay extends TimeDisplay {
  10393. /**
  10394. * Creates an instance of this class.
  10395. *
  10396. * @param { import('../../player').default } player
  10397. * The `Player` that this class should be attached to.
  10398. *
  10399. * @param {Object} [options]
  10400. * The key/value store of player options.
  10401. */
  10402. constructor(player, options) {
  10403. super(player, options);
  10404. this.on(player, 'durationchange', e => this.updateContent(e));
  10405. }
  10406. /**
  10407. * Builds the default DOM `className`.
  10408. *
  10409. * @return {string}
  10410. * The DOM `className` for this object.
  10411. */
  10412. buildCSSClass() {
  10413. return 'vjs-remaining-time';
  10414. }
  10415. /**
  10416. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  10417. *
  10418. * @return {Element}
  10419. * The element that was created.
  10420. */
  10421. createEl() {
  10422. const el = super.createEl();
  10423. if (this.options_.displayNegative !== false) {
  10424. el.insertBefore(createEl('span', {}, {
  10425. 'aria-hidden': true
  10426. }, '-'), this.contentEl_);
  10427. }
  10428. return el;
  10429. }
  10430. /**
  10431. * Update remaining time display.
  10432. *
  10433. * @param {Event} [event]
  10434. * The `timeupdate` or `durationchange` event that caused this to run.
  10435. *
  10436. * @listens Player#timeupdate
  10437. * @listens Player#durationchange
  10438. */
  10439. updateContent(event) {
  10440. if (typeof this.player_.duration() !== 'number') {
  10441. return;
  10442. }
  10443. let time;
  10444. // @deprecated We should only use remainingTimeDisplay
  10445. // as of video.js 7
  10446. if (this.player_.ended()) {
  10447. time = 0;
  10448. } else if (this.player_.remainingTimeDisplay) {
  10449. time = this.player_.remainingTimeDisplay();
  10450. } else {
  10451. time = this.player_.remainingTime();
  10452. }
  10453. this.updateTextNode_(time);
  10454. }
  10455. }
  10456. /**
  10457. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  10458. *
  10459. * @type {string}
  10460. * @private
  10461. */
  10462. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  10463. /**
  10464. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  10465. *
  10466. * @type {string}
  10467. * @protected
  10468. *
  10469. * @deprecated in v7; controlText_ is not used in non-active display Components
  10470. */
  10471. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  10472. Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  10473. /**
  10474. * @file live-display.js
  10475. */
  10476. // TODO - Future make it click to snap to live
  10477. /**
  10478. * Displays the live indicator when duration is Infinity.
  10479. *
  10480. * @extends Component
  10481. */
  10482. class LiveDisplay extends Component {
  10483. /**
  10484. * Creates an instance of this class.
  10485. *
  10486. * @param { import('./player').default } player
  10487. * The `Player` that this class should be attached to.
  10488. *
  10489. * @param {Object} [options]
  10490. * The key/value store of player options.
  10491. */
  10492. constructor(player, options) {
  10493. super(player, options);
  10494. this.updateShowing();
  10495. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  10496. }
  10497. /**
  10498. * Create the `Component`'s DOM element
  10499. *
  10500. * @return {Element}
  10501. * The element that was created.
  10502. */
  10503. createEl() {
  10504. const el = super.createEl('div', {
  10505. className: 'vjs-live-control vjs-control'
  10506. });
  10507. this.contentEl_ = createEl('div', {
  10508. className: 'vjs-live-display'
  10509. }, {
  10510. 'aria-live': 'off'
  10511. });
  10512. this.contentEl_.appendChild(createEl('span', {
  10513. className: 'vjs-control-text',
  10514. textContent: `${this.localize('Stream Type')}\u00a0`
  10515. }));
  10516. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  10517. el.appendChild(this.contentEl_);
  10518. return el;
  10519. }
  10520. dispose() {
  10521. this.contentEl_ = null;
  10522. super.dispose();
  10523. }
  10524. /**
  10525. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  10526. * it accordingly
  10527. *
  10528. * @param {Event} [event]
  10529. * The {@link Player#durationchange} event that caused this function to run.
  10530. *
  10531. * @listens Player#durationchange
  10532. */
  10533. updateShowing(event) {
  10534. if (this.player().duration() === Infinity) {
  10535. this.show();
  10536. } else {
  10537. this.hide();
  10538. }
  10539. }
  10540. }
  10541. Component.registerComponent('LiveDisplay', LiveDisplay);
  10542. /**
  10543. * @file seek-to-live.js
  10544. */
  10545. /**
  10546. * Displays the live indicator when duration is Infinity.
  10547. *
  10548. * @extends Component
  10549. */
  10550. class SeekToLive extends Button {
  10551. /**
  10552. * Creates an instance of this class.
  10553. *
  10554. * @param { import('./player').default } player
  10555. * The `Player` that this class should be attached to.
  10556. *
  10557. * @param {Object} [options]
  10558. * The key/value store of player options.
  10559. */
  10560. constructor(player, options) {
  10561. super(player, options);
  10562. this.updateLiveEdgeStatus();
  10563. if (this.player_.liveTracker) {
  10564. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  10565. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10566. }
  10567. }
  10568. /**
  10569. * Create the `Component`'s DOM element
  10570. *
  10571. * @return {Element}
  10572. * The element that was created.
  10573. */
  10574. createEl() {
  10575. const el = super.createEl('button', {
  10576. className: 'vjs-seek-to-live-control vjs-control'
  10577. });
  10578. this.textEl_ = createEl('span', {
  10579. className: 'vjs-seek-to-live-text',
  10580. textContent: this.localize('LIVE')
  10581. }, {
  10582. 'aria-hidden': 'true'
  10583. });
  10584. el.appendChild(this.textEl_);
  10585. return el;
  10586. }
  10587. /**
  10588. * Update the state of this button if we are at the live edge
  10589. * or not
  10590. */
  10591. updateLiveEdgeStatus() {
  10592. // default to live edge
  10593. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  10594. this.setAttribute('aria-disabled', true);
  10595. this.addClass('vjs-at-live-edge');
  10596. this.controlText('Seek to live, currently playing live');
  10597. } else {
  10598. this.setAttribute('aria-disabled', false);
  10599. this.removeClass('vjs-at-live-edge');
  10600. this.controlText('Seek to live, currently behind live');
  10601. }
  10602. }
  10603. /**
  10604. * On click bring us as near to the live point as possible.
  10605. * This requires that we wait for the next `live-seekable-change`
  10606. * event which will happen every segment length seconds.
  10607. */
  10608. handleClick() {
  10609. this.player_.liveTracker.seekToLiveEdge();
  10610. }
  10611. /**
  10612. * Dispose of the element and stop tracking
  10613. */
  10614. dispose() {
  10615. if (this.player_.liveTracker) {
  10616. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10617. }
  10618. this.textEl_ = null;
  10619. super.dispose();
  10620. }
  10621. }
  10622. /**
  10623. * The text that should display over the `SeekToLive`s control. Added for localization.
  10624. *
  10625. * @type {string}
  10626. * @protected
  10627. */
  10628. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  10629. Component.registerComponent('SeekToLive', SeekToLive);
  10630. /**
  10631. * @file num.js
  10632. * @module num
  10633. */
  10634. /**
  10635. * Keep a number between a min and a max value
  10636. *
  10637. * @param {number} number
  10638. * The number to clamp
  10639. *
  10640. * @param {number} min
  10641. * The minimum value
  10642. * @param {number} max
  10643. * The maximum value
  10644. *
  10645. * @return {number}
  10646. * the clamped number
  10647. */
  10648. function clamp(number, min, max) {
  10649. number = Number(number);
  10650. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  10651. }
  10652. var Num = /*#__PURE__*/Object.freeze({
  10653. __proto__: null,
  10654. clamp: clamp
  10655. });
  10656. /**
  10657. * @file slider.js
  10658. */
  10659. /**
  10660. * The base functionality for a slider. Can be vertical or horizontal.
  10661. * For instance the volume bar or the seek bar on a video is a slider.
  10662. *
  10663. * @extends Component
  10664. */
  10665. class Slider extends Component {
  10666. /**
  10667. * Create an instance of this class
  10668. *
  10669. * @param { import('../player').default } player
  10670. * The `Player` that this class should be attached to.
  10671. *
  10672. * @param {Object} [options]
  10673. * The key/value store of player options.
  10674. */
  10675. constructor(player, options) {
  10676. super(player, options);
  10677. this.handleMouseDown_ = e => this.handleMouseDown(e);
  10678. this.handleMouseUp_ = e => this.handleMouseUp(e);
  10679. this.handleKeyDown_ = e => this.handleKeyDown(e);
  10680. this.handleClick_ = e => this.handleClick(e);
  10681. this.handleMouseMove_ = e => this.handleMouseMove(e);
  10682. this.update_ = e => this.update(e);
  10683. // Set property names to bar to match with the child Slider class is looking for
  10684. this.bar = this.getChild(this.options_.barName);
  10685. // Set a horizontal or vertical class on the slider depending on the slider type
  10686. this.vertical(!!this.options_.vertical);
  10687. this.enable();
  10688. }
  10689. /**
  10690. * Are controls are currently enabled for this slider or not.
  10691. *
  10692. * @return {boolean}
  10693. * true if controls are enabled, false otherwise
  10694. */
  10695. enabled() {
  10696. return this.enabled_;
  10697. }
  10698. /**
  10699. * Enable controls for this slider if they are disabled
  10700. */
  10701. enable() {
  10702. if (this.enabled()) {
  10703. return;
  10704. }
  10705. this.on('mousedown', this.handleMouseDown_);
  10706. this.on('touchstart', this.handleMouseDown_);
  10707. this.on('keydown', this.handleKeyDown_);
  10708. this.on('click', this.handleClick_);
  10709. // TODO: deprecated, controlsvisible does not seem to be fired
  10710. this.on(this.player_, 'controlsvisible', this.update);
  10711. if (this.playerEvent) {
  10712. this.on(this.player_, this.playerEvent, this.update);
  10713. }
  10714. this.removeClass('disabled');
  10715. this.setAttribute('tabindex', 0);
  10716. this.enabled_ = true;
  10717. }
  10718. /**
  10719. * Disable controls for this slider if they are enabled
  10720. */
  10721. disable() {
  10722. if (!this.enabled()) {
  10723. return;
  10724. }
  10725. const doc = this.bar.el_.ownerDocument;
  10726. this.off('mousedown', this.handleMouseDown_);
  10727. this.off('touchstart', this.handleMouseDown_);
  10728. this.off('keydown', this.handleKeyDown_);
  10729. this.off('click', this.handleClick_);
  10730. this.off(this.player_, 'controlsvisible', this.update_);
  10731. this.off(doc, 'mousemove', this.handleMouseMove_);
  10732. this.off(doc, 'mouseup', this.handleMouseUp_);
  10733. this.off(doc, 'touchmove', this.handleMouseMove_);
  10734. this.off(doc, 'touchend', this.handleMouseUp_);
  10735. this.removeAttribute('tabindex');
  10736. this.addClass('disabled');
  10737. if (this.playerEvent) {
  10738. this.off(this.player_, this.playerEvent, this.update);
  10739. }
  10740. this.enabled_ = false;
  10741. }
  10742. /**
  10743. * Create the `Slider`s DOM element.
  10744. *
  10745. * @param {string} type
  10746. * Type of element to create.
  10747. *
  10748. * @param {Object} [props={}]
  10749. * List of properties in Object form.
  10750. *
  10751. * @param {Object} [attributes={}]
  10752. * list of attributes in Object form.
  10753. *
  10754. * @return {Element}
  10755. * The element that gets created.
  10756. */
  10757. createEl(type, props = {}, attributes = {}) {
  10758. // Add the slider element class to all sub classes
  10759. props.className = props.className + ' vjs-slider';
  10760. props = Object.assign({
  10761. tabIndex: 0
  10762. }, props);
  10763. attributes = Object.assign({
  10764. 'role': 'slider',
  10765. 'aria-valuenow': 0,
  10766. 'aria-valuemin': 0,
  10767. 'aria-valuemax': 100
  10768. }, attributes);
  10769. return super.createEl(type, props, attributes);
  10770. }
  10771. /**
  10772. * Handle `mousedown` or `touchstart` events on the `Slider`.
  10773. *
  10774. * @param {MouseEvent} event
  10775. * `mousedown` or `touchstart` event that triggered this function
  10776. *
  10777. * @listens mousedown
  10778. * @listens touchstart
  10779. * @fires Slider#slideractive
  10780. */
  10781. handleMouseDown(event) {
  10782. const doc = this.bar.el_.ownerDocument;
  10783. if (event.type === 'mousedown') {
  10784. event.preventDefault();
  10785. }
  10786. // Do not call preventDefault() on touchstart in Chrome
  10787. // to avoid console warnings. Use a 'touch-action: none' style
  10788. // instead to prevent unintended scrolling.
  10789. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  10790. if (event.type === 'touchstart' && !IS_CHROME) {
  10791. event.preventDefault();
  10792. }
  10793. blockTextSelection();
  10794. this.addClass('vjs-sliding');
  10795. /**
  10796. * Triggered when the slider is in an active state
  10797. *
  10798. * @event Slider#slideractive
  10799. * @type {MouseEvent}
  10800. */
  10801. this.trigger('slideractive');
  10802. this.on(doc, 'mousemove', this.handleMouseMove_);
  10803. this.on(doc, 'mouseup', this.handleMouseUp_);
  10804. this.on(doc, 'touchmove', this.handleMouseMove_);
  10805. this.on(doc, 'touchend', this.handleMouseUp_);
  10806. this.handleMouseMove(event, true);
  10807. }
  10808. /**
  10809. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  10810. * The `mousemove` and `touchmove` events will only only trigger this function during
  10811. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  10812. * {@link Slider#handleMouseUp}.
  10813. *
  10814. * @param {MouseEvent} event
  10815. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  10816. * this function
  10817. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false.
  10818. *
  10819. * @listens mousemove
  10820. * @listens touchmove
  10821. */
  10822. handleMouseMove(event) {}
  10823. /**
  10824. * Handle `mouseup` or `touchend` events on the `Slider`.
  10825. *
  10826. * @param {MouseEvent} event
  10827. * `mouseup` or `touchend` event that triggered this function.
  10828. *
  10829. * @listens touchend
  10830. * @listens mouseup
  10831. * @fires Slider#sliderinactive
  10832. */
  10833. handleMouseUp(event) {
  10834. const doc = this.bar.el_.ownerDocument;
  10835. unblockTextSelection();
  10836. this.removeClass('vjs-sliding');
  10837. /**
  10838. * Triggered when the slider is no longer in an active state.
  10839. *
  10840. * @event Slider#sliderinactive
  10841. * @type {Event}
  10842. */
  10843. this.trigger('sliderinactive');
  10844. this.off(doc, 'mousemove', this.handleMouseMove_);
  10845. this.off(doc, 'mouseup', this.handleMouseUp_);
  10846. this.off(doc, 'touchmove', this.handleMouseMove_);
  10847. this.off(doc, 'touchend', this.handleMouseUp_);
  10848. this.update();
  10849. }
  10850. /**
  10851. * Update the progress bar of the `Slider`.
  10852. *
  10853. * @return {number}
  10854. * The percentage of progress the progress bar represents as a
  10855. * number from 0 to 1.
  10856. */
  10857. update() {
  10858. // In VolumeBar init we have a setTimeout for update that pops and update
  10859. // to the end of the execution stack. The player is destroyed before then
  10860. // update will cause an error
  10861. // If there's no bar...
  10862. if (!this.el_ || !this.bar) {
  10863. return;
  10864. }
  10865. // clamp progress between 0 and 1
  10866. // and only round to four decimal places, as we round to two below
  10867. const progress = this.getProgress();
  10868. if (progress === this.progress_) {
  10869. return progress;
  10870. }
  10871. this.progress_ = progress;
  10872. this.requestNamedAnimationFrame('Slider#update', () => {
  10873. // Set the new bar width or height
  10874. const sizeKey = this.vertical() ? 'height' : 'width';
  10875. // Convert to a percentage for css value
  10876. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  10877. });
  10878. return progress;
  10879. }
  10880. /**
  10881. * Get the percentage of the bar that should be filled
  10882. * but clamped and rounded.
  10883. *
  10884. * @return {number}
  10885. * percentage filled that the slider is
  10886. */
  10887. getProgress() {
  10888. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  10889. }
  10890. /**
  10891. * Calculate distance for slider
  10892. *
  10893. * @param {Event} event
  10894. * The event that caused this function to run.
  10895. *
  10896. * @return {number}
  10897. * The current position of the Slider.
  10898. * - position.x for vertical `Slider`s
  10899. * - position.y for horizontal `Slider`s
  10900. */
  10901. calculateDistance(event) {
  10902. const position = getPointerPosition(this.el_, event);
  10903. if (this.vertical()) {
  10904. return position.y;
  10905. }
  10906. return position.x;
  10907. }
  10908. /**
  10909. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  10910. * arrow keys. This function will only be called when the slider has focus. See
  10911. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  10912. *
  10913. * @param {KeyboardEvent} event
  10914. * the `keydown` event that caused this function to run.
  10915. *
  10916. * @listens keydown
  10917. */
  10918. handleKeyDown(event) {
  10919. // Left and Down Arrows
  10920. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  10921. event.preventDefault();
  10922. event.stopPropagation();
  10923. this.stepBack();
  10924. // Up and Right Arrows
  10925. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  10926. event.preventDefault();
  10927. event.stopPropagation();
  10928. this.stepForward();
  10929. } else {
  10930. // Pass keydown handling up for unsupported keys
  10931. super.handleKeyDown(event);
  10932. }
  10933. }
  10934. /**
  10935. * Listener for click events on slider, used to prevent clicks
  10936. * from bubbling up to parent elements like button menus.
  10937. *
  10938. * @param {Object} event
  10939. * Event that caused this object to run
  10940. */
  10941. handleClick(event) {
  10942. event.stopPropagation();
  10943. event.preventDefault();
  10944. }
  10945. /**
  10946. * Get/set if slider is horizontal for vertical
  10947. *
  10948. * @param {boolean} [bool]
  10949. * - true if slider is vertical,
  10950. * - false is horizontal
  10951. *
  10952. * @return {boolean}
  10953. * - true if slider is vertical, and getting
  10954. * - false if the slider is horizontal, and getting
  10955. */
  10956. vertical(bool) {
  10957. if (bool === undefined) {
  10958. return this.vertical_ || false;
  10959. }
  10960. this.vertical_ = !!bool;
  10961. if (this.vertical_) {
  10962. this.addClass('vjs-slider-vertical');
  10963. } else {
  10964. this.addClass('vjs-slider-horizontal');
  10965. }
  10966. }
  10967. }
  10968. Component.registerComponent('Slider', Slider);
  10969. /**
  10970. * @file load-progress-bar.js
  10971. */
  10972. // get the percent width of a time compared to the total end
  10973. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  10974. /**
  10975. * Shows loading progress
  10976. *
  10977. * @extends Component
  10978. */
  10979. class LoadProgressBar extends Component {
  10980. /**
  10981. * Creates an instance of this class.
  10982. *
  10983. * @param { import('../../player').default } player
  10984. * The `Player` that this class should be attached to.
  10985. *
  10986. * @param {Object} [options]
  10987. * The key/value store of player options.
  10988. */
  10989. constructor(player, options) {
  10990. super(player, options);
  10991. this.partEls_ = [];
  10992. this.on(player, 'progress', e => this.update(e));
  10993. }
  10994. /**
  10995. * Create the `Component`'s DOM element
  10996. *
  10997. * @return {Element}
  10998. * The element that was created.
  10999. */
  11000. createEl() {
  11001. const el = super.createEl('div', {
  11002. className: 'vjs-load-progress'
  11003. });
  11004. const wrapper = createEl('span', {
  11005. className: 'vjs-control-text'
  11006. });
  11007. const loadedText = createEl('span', {
  11008. textContent: this.localize('Loaded')
  11009. });
  11010. const separator = document.createTextNode(': ');
  11011. this.percentageEl_ = createEl('span', {
  11012. className: 'vjs-control-text-loaded-percentage',
  11013. textContent: '0%'
  11014. });
  11015. el.appendChild(wrapper);
  11016. wrapper.appendChild(loadedText);
  11017. wrapper.appendChild(separator);
  11018. wrapper.appendChild(this.percentageEl_);
  11019. return el;
  11020. }
  11021. dispose() {
  11022. this.partEls_ = null;
  11023. this.percentageEl_ = null;
  11024. super.dispose();
  11025. }
  11026. /**
  11027. * Update progress bar
  11028. *
  11029. * @param {Event} [event]
  11030. * The `progress` event that caused this function to run.
  11031. *
  11032. * @listens Player#progress
  11033. */
  11034. update(event) {
  11035. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  11036. const liveTracker = this.player_.liveTracker;
  11037. const buffered = this.player_.buffered();
  11038. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  11039. const bufferedEnd = this.player_.bufferedEnd();
  11040. const children = this.partEls_;
  11041. const percent = percentify(bufferedEnd, duration);
  11042. if (this.percent_ !== percent) {
  11043. // update the width of the progress bar
  11044. this.el_.style.width = percent;
  11045. // update the control-text
  11046. textContent(this.percentageEl_, percent);
  11047. this.percent_ = percent;
  11048. }
  11049. // add child elements to represent the individual buffered time ranges
  11050. for (let i = 0; i < buffered.length; i++) {
  11051. const start = buffered.start(i);
  11052. const end = buffered.end(i);
  11053. let part = children[i];
  11054. if (!part) {
  11055. part = this.el_.appendChild(createEl());
  11056. children[i] = part;
  11057. }
  11058. // only update if changed
  11059. if (part.dataset.start === start && part.dataset.end === end) {
  11060. continue;
  11061. }
  11062. part.dataset.start = start;
  11063. part.dataset.end = end;
  11064. // set the percent based on the width of the progress bar (bufferedEnd)
  11065. part.style.left = percentify(start, bufferedEnd);
  11066. part.style.width = percentify(end - start, bufferedEnd);
  11067. }
  11068. // remove unused buffered range elements
  11069. for (let i = children.length; i > buffered.length; i--) {
  11070. this.el_.removeChild(children[i - 1]);
  11071. }
  11072. children.length = buffered.length;
  11073. });
  11074. }
  11075. }
  11076. Component.registerComponent('LoadProgressBar', LoadProgressBar);
  11077. /**
  11078. * @file time-tooltip.js
  11079. */
  11080. /**
  11081. * Time tooltips display a time above the progress bar.
  11082. *
  11083. * @extends Component
  11084. */
  11085. class TimeTooltip extends Component {
  11086. /**
  11087. * Creates an instance of this class.
  11088. *
  11089. * @param { import('../../player').default } player
  11090. * The {@link Player} that this class should be attached to.
  11091. *
  11092. * @param {Object} [options]
  11093. * The key/value store of player options.
  11094. */
  11095. constructor(player, options) {
  11096. super(player, options);
  11097. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11098. }
  11099. /**
  11100. * Create the time tooltip DOM element
  11101. *
  11102. * @return {Element}
  11103. * The element that was created.
  11104. */
  11105. createEl() {
  11106. return super.createEl('div', {
  11107. className: 'vjs-time-tooltip'
  11108. }, {
  11109. 'aria-hidden': 'true'
  11110. });
  11111. }
  11112. /**
  11113. * Updates the position of the time tooltip relative to the `SeekBar`.
  11114. *
  11115. * @param {Object} seekBarRect
  11116. * The `ClientRect` for the {@link SeekBar} element.
  11117. *
  11118. * @param {number} seekBarPoint
  11119. * A number from 0 to 1, representing a horizontal reference point
  11120. * from the left edge of the {@link SeekBar}
  11121. */
  11122. update(seekBarRect, seekBarPoint, content) {
  11123. const tooltipRect = findPosition(this.el_);
  11124. const playerRect = getBoundingClientRect(this.player_.el());
  11125. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  11126. // do nothing if either rect isn't available
  11127. // for example, if the player isn't in the DOM for testing
  11128. if (!playerRect || !tooltipRect) {
  11129. return;
  11130. }
  11131. // This is the space left of the `seekBarPoint` available within the bounds
  11132. // of the player. We calculate any gap between the left edge of the player
  11133. // and the left edge of the `SeekBar` and add the number of pixels in the
  11134. // `SeekBar` before hitting the `seekBarPoint`
  11135. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  11136. // This is the space right of the `seekBarPoint` available within the bounds
  11137. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11138. // to the right edge of the `SeekBar` and add to that any gap between the
  11139. // right edge of the `SeekBar` and the player.
  11140. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  11141. // This is the number of pixels by which the tooltip will need to be pulled
  11142. // further to the right to center it over the `seekBarPoint`.
  11143. let pullTooltipBy = tooltipRect.width / 2;
  11144. // Adjust the `pullTooltipBy` distance to the left or right depending on
  11145. // the results of the space calculations above.
  11146. if (spaceLeftOfPoint < pullTooltipBy) {
  11147. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11148. } else if (spaceRightOfPoint < pullTooltipBy) {
  11149. pullTooltipBy = spaceRightOfPoint;
  11150. }
  11151. // Due to the imprecision of decimal/ratio based calculations and varying
  11152. // rounding behaviors, there are cases where the spacing adjustment is off
  11153. // by a pixel or two. This adds insurance to these calculations.
  11154. if (pullTooltipBy < 0) {
  11155. pullTooltipBy = 0;
  11156. } else if (pullTooltipBy > tooltipRect.width) {
  11157. pullTooltipBy = tooltipRect.width;
  11158. }
  11159. // prevent small width fluctuations within 0.4px from
  11160. // changing the value below.
  11161. // This really helps for live to prevent the play
  11162. // progress time tooltip from jittering
  11163. pullTooltipBy = Math.round(pullTooltipBy);
  11164. this.el_.style.right = `-${pullTooltipBy}px`;
  11165. this.write(content);
  11166. }
  11167. /**
  11168. * Write the time to the tooltip DOM element.
  11169. *
  11170. * @param {string} content
  11171. * The formatted time for the tooltip.
  11172. */
  11173. write(content) {
  11174. textContent(this.el_, content);
  11175. }
  11176. /**
  11177. * Updates the position of the time tooltip relative to the `SeekBar`.
  11178. *
  11179. * @param {Object} seekBarRect
  11180. * The `ClientRect` for the {@link SeekBar} element.
  11181. *
  11182. * @param {number} seekBarPoint
  11183. * A number from 0 to 1, representing a horizontal reference point
  11184. * from the left edge of the {@link SeekBar}
  11185. *
  11186. * @param {number} time
  11187. * The time to update the tooltip to, not used during live playback
  11188. *
  11189. * @param {Function} cb
  11190. * A function that will be called during the request animation frame
  11191. * for tooltips that need to do additional animations from the default
  11192. */
  11193. updateTime(seekBarRect, seekBarPoint, time, cb) {
  11194. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  11195. let content;
  11196. const duration = this.player_.duration();
  11197. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11198. const liveWindow = this.player_.liveTracker.liveWindow();
  11199. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11200. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11201. } else {
  11202. content = formatTime(time, duration);
  11203. }
  11204. this.update(seekBarRect, seekBarPoint, content);
  11205. if (cb) {
  11206. cb();
  11207. }
  11208. });
  11209. }
  11210. }
  11211. Component.registerComponent('TimeTooltip', TimeTooltip);
  11212. /**
  11213. * @file play-progress-bar.js
  11214. */
  11215. /**
  11216. * Used by {@link SeekBar} to display media playback progress as part of the
  11217. * {@link ProgressControl}.
  11218. *
  11219. * @extends Component
  11220. */
  11221. class PlayProgressBar extends Component {
  11222. /**
  11223. * Creates an instance of this class.
  11224. *
  11225. * @param { import('../../player').default } player
  11226. * The {@link Player} that this class should be attached to.
  11227. *
  11228. * @param {Object} [options]
  11229. * The key/value store of player options.
  11230. */
  11231. constructor(player, options) {
  11232. super(player, options);
  11233. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11234. }
  11235. /**
  11236. * Create the the DOM element for this class.
  11237. *
  11238. * @return {Element}
  11239. * The element that was created.
  11240. */
  11241. createEl() {
  11242. return super.createEl('div', {
  11243. className: 'vjs-play-progress vjs-slider-bar'
  11244. }, {
  11245. 'aria-hidden': 'true'
  11246. });
  11247. }
  11248. /**
  11249. * Enqueues updates to its own DOM as well as the DOM of its
  11250. * {@link TimeTooltip} child.
  11251. *
  11252. * @param {Object} seekBarRect
  11253. * The `ClientRect` for the {@link SeekBar} element.
  11254. *
  11255. * @param {number} seekBarPoint
  11256. * A number from 0 to 1, representing a horizontal reference point
  11257. * from the left edge of the {@link SeekBar}
  11258. */
  11259. update(seekBarRect, seekBarPoint) {
  11260. const timeTooltip = this.getChild('timeTooltip');
  11261. if (!timeTooltip) {
  11262. return;
  11263. }
  11264. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11265. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  11266. }
  11267. }
  11268. /**
  11269. * Default options for {@link PlayProgressBar}.
  11270. *
  11271. * @type {Object}
  11272. * @private
  11273. */
  11274. PlayProgressBar.prototype.options_ = {
  11275. children: []
  11276. };
  11277. // Time tooltips should not be added to a player on mobile devices
  11278. if (!IS_IOS && !IS_ANDROID) {
  11279. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  11280. }
  11281. Component.registerComponent('PlayProgressBar', PlayProgressBar);
  11282. /**
  11283. * @file mouse-time-display.js
  11284. */
  11285. /**
  11286. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  11287. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  11288. * indicating the time which is represented by a given point in the
  11289. * {@link ProgressControl}.
  11290. *
  11291. * @extends Component
  11292. */
  11293. class MouseTimeDisplay extends Component {
  11294. /**
  11295. * Creates an instance of this class.
  11296. *
  11297. * @param { import('../../player').default } player
  11298. * The {@link Player} that this class should be attached to.
  11299. *
  11300. * @param {Object} [options]
  11301. * The key/value store of player options.
  11302. */
  11303. constructor(player, options) {
  11304. super(player, options);
  11305. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11306. }
  11307. /**
  11308. * Create the DOM element for this class.
  11309. *
  11310. * @return {Element}
  11311. * The element that was created.
  11312. */
  11313. createEl() {
  11314. return super.createEl('div', {
  11315. className: 'vjs-mouse-display'
  11316. });
  11317. }
  11318. /**
  11319. * Enqueues updates to its own DOM as well as the DOM of its
  11320. * {@link TimeTooltip} child.
  11321. *
  11322. * @param {Object} seekBarRect
  11323. * The `ClientRect` for the {@link SeekBar} element.
  11324. *
  11325. * @param {number} seekBarPoint
  11326. * A number from 0 to 1, representing a horizontal reference point
  11327. * from the left edge of the {@link SeekBar}
  11328. */
  11329. update(seekBarRect, seekBarPoint) {
  11330. const time = seekBarPoint * this.player_.duration();
  11331. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  11332. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  11333. });
  11334. }
  11335. }
  11336. /**
  11337. * Default options for `MouseTimeDisplay`
  11338. *
  11339. * @type {Object}
  11340. * @private
  11341. */
  11342. MouseTimeDisplay.prototype.options_ = {
  11343. children: ['timeTooltip']
  11344. };
  11345. Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  11346. /**
  11347. * @file seek-bar.js
  11348. */
  11349. // The number of seconds the `step*` functions move the timeline.
  11350. const STEP_SECONDS = 5;
  11351. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  11352. const PAGE_KEY_MULTIPLIER = 12;
  11353. /**
  11354. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  11355. * as its `bar`.
  11356. *
  11357. * @extends Slider
  11358. */
  11359. class SeekBar extends Slider {
  11360. /**
  11361. * Creates an instance of this class.
  11362. *
  11363. * @param { import('../../player').default } player
  11364. * The `Player` that this class should be attached to.
  11365. *
  11366. * @param {Object} [options]
  11367. * The key/value store of player options.
  11368. */
  11369. constructor(player, options) {
  11370. super(player, options);
  11371. this.setEventHandlers_();
  11372. }
  11373. /**
  11374. * Sets the event handlers
  11375. *
  11376. * @private
  11377. */
  11378. setEventHandlers_() {
  11379. this.update_ = bind_(this, this.update);
  11380. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  11381. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11382. if (this.player_.liveTracker) {
  11383. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  11384. }
  11385. // when playing, let's ensure we smoothly update the play progress bar
  11386. // via an interval
  11387. this.updateInterval = null;
  11388. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  11389. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  11390. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  11391. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11392. // we don't need to update the play progress if the document is hidden,
  11393. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11394. if ('hidden' in document && 'visibilityState' in document) {
  11395. this.on(document, 'visibilitychange', this.toggleVisibility_);
  11396. }
  11397. }
  11398. toggleVisibility_(e) {
  11399. if (document.visibilityState === 'hidden') {
  11400. this.cancelNamedAnimationFrame('SeekBar#update');
  11401. this.cancelNamedAnimationFrame('Slider#update');
  11402. this.disableInterval_(e);
  11403. } else {
  11404. if (!this.player_.ended() && !this.player_.paused()) {
  11405. this.enableInterval_();
  11406. }
  11407. // we just switched back to the page and someone may be looking, so, update ASAP
  11408. this.update();
  11409. }
  11410. }
  11411. enableInterval_() {
  11412. if (this.updateInterval) {
  11413. return;
  11414. }
  11415. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  11416. }
  11417. disableInterval_(e) {
  11418. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  11419. return;
  11420. }
  11421. if (!this.updateInterval) {
  11422. return;
  11423. }
  11424. this.clearInterval(this.updateInterval);
  11425. this.updateInterval = null;
  11426. }
  11427. /**
  11428. * Create the `Component`'s DOM element
  11429. *
  11430. * @return {Element}
  11431. * The element that was created.
  11432. */
  11433. createEl() {
  11434. return super.createEl('div', {
  11435. className: 'vjs-progress-holder'
  11436. }, {
  11437. 'aria-label': this.localize('Progress Bar')
  11438. });
  11439. }
  11440. /**
  11441. * This function updates the play progress bar and accessibility
  11442. * attributes to whatever is passed in.
  11443. *
  11444. * @param {Event} [event]
  11445. * The `timeupdate` or `ended` event that caused this to run.
  11446. *
  11447. * @listens Player#timeupdate
  11448. *
  11449. * @return {number}
  11450. * The current percent at a number from 0-1
  11451. */
  11452. update(event) {
  11453. // ignore updates while the tab is hidden
  11454. if (document.visibilityState === 'hidden') {
  11455. return;
  11456. }
  11457. const percent = super.update();
  11458. this.requestNamedAnimationFrame('SeekBar#update', () => {
  11459. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  11460. const liveTracker = this.player_.liveTracker;
  11461. let duration = this.player_.duration();
  11462. if (liveTracker && liveTracker.isLive()) {
  11463. duration = this.player_.liveTracker.liveCurrentTime();
  11464. }
  11465. if (this.percent_ !== percent) {
  11466. // machine readable value of progress bar (percentage complete)
  11467. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  11468. this.percent_ = percent;
  11469. }
  11470. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  11471. // human readable value of progress bar (time complete)
  11472. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  11473. this.currentTime_ = currentTime;
  11474. this.duration_ = duration;
  11475. }
  11476. // update the progress bar time tooltip with the current time
  11477. if (this.bar) {
  11478. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  11479. }
  11480. });
  11481. return percent;
  11482. }
  11483. /**
  11484. * Prevent liveThreshold from causing seeks to seem like they
  11485. * are not happening from a user perspective.
  11486. *
  11487. * @param {number} ct
  11488. * current time to seek to
  11489. */
  11490. userSeek_(ct) {
  11491. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11492. this.player_.liveTracker.nextSeekedFromUser();
  11493. }
  11494. this.player_.currentTime(ct);
  11495. }
  11496. /**
  11497. * Get the value of current time but allows for smooth scrubbing,
  11498. * when player can't keep up.
  11499. *
  11500. * @return {number}
  11501. * The current time value to display
  11502. *
  11503. * @private
  11504. */
  11505. getCurrentTime_() {
  11506. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11507. }
  11508. /**
  11509. * Get the percentage of media played so far.
  11510. *
  11511. * @return {number}
  11512. * The percentage of media played so far (0 to 1).
  11513. */
  11514. getPercent() {
  11515. const currentTime = this.getCurrentTime_();
  11516. let percent;
  11517. const liveTracker = this.player_.liveTracker;
  11518. if (liveTracker && liveTracker.isLive()) {
  11519. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  11520. // prevent the percent from changing at the live edge
  11521. if (liveTracker.atLiveEdge()) {
  11522. percent = 1;
  11523. }
  11524. } else {
  11525. percent = currentTime / this.player_.duration();
  11526. }
  11527. return percent;
  11528. }
  11529. /**
  11530. * Handle mouse down on seek bar
  11531. *
  11532. * @param {MouseEvent} event
  11533. * The `mousedown` event that caused this to run.
  11534. *
  11535. * @listens mousedown
  11536. */
  11537. handleMouseDown(event) {
  11538. if (!isSingleLeftClick(event)) {
  11539. return;
  11540. }
  11541. // Stop event propagation to prevent double fire in progress-control.js
  11542. event.stopPropagation();
  11543. this.videoWasPlaying = !this.player_.paused();
  11544. this.player_.pause();
  11545. super.handleMouseDown(event);
  11546. }
  11547. /**
  11548. * Handle mouse move on seek bar
  11549. *
  11550. * @param {MouseEvent} event
  11551. * The `mousemove` event that caused this to run.
  11552. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false
  11553. *
  11554. * @listens mousemove
  11555. */
  11556. handleMouseMove(event, mouseDown = false) {
  11557. if (!isSingleLeftClick(event)) {
  11558. return;
  11559. }
  11560. if (!mouseDown && !this.player_.scrubbing()) {
  11561. this.player_.scrubbing(true);
  11562. }
  11563. let newTime;
  11564. const distance = this.calculateDistance(event);
  11565. const liveTracker = this.player_.liveTracker;
  11566. if (!liveTracker || !liveTracker.isLive()) {
  11567. newTime = distance * this.player_.duration();
  11568. // Don't let video end while scrubbing.
  11569. if (newTime === this.player_.duration()) {
  11570. newTime = newTime - 0.1;
  11571. }
  11572. } else {
  11573. if (distance >= 0.99) {
  11574. liveTracker.seekToLiveEdge();
  11575. return;
  11576. }
  11577. const seekableStart = liveTracker.seekableStart();
  11578. const seekableEnd = liveTracker.liveCurrentTime();
  11579. newTime = seekableStart + distance * liveTracker.liveWindow();
  11580. // Don't let video end while scrubbing.
  11581. if (newTime >= seekableEnd) {
  11582. newTime = seekableEnd;
  11583. }
  11584. // Compensate for precision differences so that currentTime is not less
  11585. // than seekable start
  11586. if (newTime <= seekableStart) {
  11587. newTime = seekableStart + 0.1;
  11588. }
  11589. // On android seekableEnd can be Infinity sometimes,
  11590. // this will cause newTime to be Infinity, which is
  11591. // not a valid currentTime.
  11592. if (newTime === Infinity) {
  11593. return;
  11594. }
  11595. }
  11596. // Set new time (tell player to seek to new time)
  11597. this.userSeek_(newTime);
  11598. }
  11599. enable() {
  11600. super.enable();
  11601. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11602. if (!mouseTimeDisplay) {
  11603. return;
  11604. }
  11605. mouseTimeDisplay.show();
  11606. }
  11607. disable() {
  11608. super.disable();
  11609. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11610. if (!mouseTimeDisplay) {
  11611. return;
  11612. }
  11613. mouseTimeDisplay.hide();
  11614. }
  11615. /**
  11616. * Handle mouse up on seek bar
  11617. *
  11618. * @param {MouseEvent} event
  11619. * The `mouseup` event that caused this to run.
  11620. *
  11621. * @listens mouseup
  11622. */
  11623. handleMouseUp(event) {
  11624. super.handleMouseUp(event);
  11625. // Stop event propagation to prevent double fire in progress-control.js
  11626. if (event) {
  11627. event.stopPropagation();
  11628. }
  11629. this.player_.scrubbing(false);
  11630. /**
  11631. * Trigger timeupdate because we're done seeking and the time has changed.
  11632. * This is particularly useful for if the player is paused to time the time displays.
  11633. *
  11634. * @event Tech#timeupdate
  11635. * @type {Event}
  11636. */
  11637. this.player_.trigger({
  11638. type: 'timeupdate',
  11639. target: this,
  11640. manuallyTriggered: true
  11641. });
  11642. if (this.videoWasPlaying) {
  11643. silencePromise(this.player_.play());
  11644. } else {
  11645. // We're done seeking and the time has changed.
  11646. // If the player is paused, make sure we display the correct time on the seek bar.
  11647. this.update_();
  11648. }
  11649. }
  11650. /**
  11651. * Move more quickly fast forward for keyboard-only users
  11652. */
  11653. stepForward() {
  11654. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  11655. }
  11656. /**
  11657. * Move more quickly rewind for keyboard-only users
  11658. */
  11659. stepBack() {
  11660. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  11661. }
  11662. /**
  11663. * Toggles the playback state of the player
  11664. * This gets called when enter or space is used on the seekbar
  11665. *
  11666. * @param {KeyboardEvent} event
  11667. * The `keydown` event that caused this function to be called
  11668. *
  11669. */
  11670. handleAction(event) {
  11671. if (this.player_.paused()) {
  11672. this.player_.play();
  11673. } else {
  11674. this.player_.pause();
  11675. }
  11676. }
  11677. /**
  11678. * Called when this SeekBar has focus and a key gets pressed down.
  11679. * Supports the following keys:
  11680. *
  11681. * Space or Enter key fire a click event
  11682. * Home key moves to start of the timeline
  11683. * End key moves to end of the timeline
  11684. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  11685. * PageDown key moves back a larger step than ArrowDown
  11686. * PageUp key moves forward a large step
  11687. *
  11688. * @param {KeyboardEvent} event
  11689. * The `keydown` event that caused this function to be called.
  11690. *
  11691. * @listens keydown
  11692. */
  11693. handleKeyDown(event) {
  11694. const liveTracker = this.player_.liveTracker;
  11695. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11696. event.preventDefault();
  11697. event.stopPropagation();
  11698. this.handleAction(event);
  11699. } else if (keycode.isEventKey(event, 'Home')) {
  11700. event.preventDefault();
  11701. event.stopPropagation();
  11702. this.userSeek_(0);
  11703. } else if (keycode.isEventKey(event, 'End')) {
  11704. event.preventDefault();
  11705. event.stopPropagation();
  11706. if (liveTracker && liveTracker.isLive()) {
  11707. this.userSeek_(liveTracker.liveCurrentTime());
  11708. } else {
  11709. this.userSeek_(this.player_.duration());
  11710. }
  11711. } else if (/^[0-9]$/.test(keycode(event))) {
  11712. event.preventDefault();
  11713. event.stopPropagation();
  11714. const gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  11715. if (liveTracker && liveTracker.isLive()) {
  11716. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  11717. } else {
  11718. this.userSeek_(this.player_.duration() * gotoFraction);
  11719. }
  11720. } else if (keycode.isEventKey(event, 'PgDn')) {
  11721. event.preventDefault();
  11722. event.stopPropagation();
  11723. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11724. } else if (keycode.isEventKey(event, 'PgUp')) {
  11725. event.preventDefault();
  11726. event.stopPropagation();
  11727. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11728. } else {
  11729. // Pass keydown handling up for unsupported keys
  11730. super.handleKeyDown(event);
  11731. }
  11732. }
  11733. dispose() {
  11734. this.disableInterval_();
  11735. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11736. if (this.player_.liveTracker) {
  11737. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  11738. }
  11739. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  11740. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11741. // we don't need to update the play progress if the document is hidden,
  11742. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11743. if ('hidden' in document && 'visibilityState' in document) {
  11744. this.off(document, 'visibilitychange', this.toggleVisibility_);
  11745. }
  11746. super.dispose();
  11747. }
  11748. }
  11749. /**
  11750. * Default options for the `SeekBar`
  11751. *
  11752. * @type {Object}
  11753. * @private
  11754. */
  11755. SeekBar.prototype.options_ = {
  11756. children: ['loadProgressBar', 'playProgressBar'],
  11757. barName: 'playProgressBar'
  11758. };
  11759. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  11760. if (!IS_IOS && !IS_ANDROID) {
  11761. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  11762. }
  11763. Component.registerComponent('SeekBar', SeekBar);
  11764. /**
  11765. * @file progress-control.js
  11766. */
  11767. /**
  11768. * The Progress Control component contains the seek bar, load progress,
  11769. * and play progress.
  11770. *
  11771. * @extends Component
  11772. */
  11773. class ProgressControl extends Component {
  11774. /**
  11775. * Creates an instance of this class.
  11776. *
  11777. * @param { import('../../player').default } player
  11778. * The `Player` that this class should be attached to.
  11779. *
  11780. * @param {Object} [options]
  11781. * The key/value store of player options.
  11782. */
  11783. constructor(player, options) {
  11784. super(player, options);
  11785. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  11786. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  11787. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  11788. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  11789. this.enable();
  11790. }
  11791. /**
  11792. * Create the `Component`'s DOM element
  11793. *
  11794. * @return {Element}
  11795. * The element that was created.
  11796. */
  11797. createEl() {
  11798. return super.createEl('div', {
  11799. className: 'vjs-progress-control vjs-control'
  11800. });
  11801. }
  11802. /**
  11803. * When the mouse moves over the `ProgressControl`, the pointer position
  11804. * gets passed down to the `MouseTimeDisplay` component.
  11805. *
  11806. * @param {Event} event
  11807. * The `mousemove` event that caused this function to run.
  11808. *
  11809. * @listen mousemove
  11810. */
  11811. handleMouseMove(event) {
  11812. const seekBar = this.getChild('seekBar');
  11813. if (!seekBar) {
  11814. return;
  11815. }
  11816. const playProgressBar = seekBar.getChild('playProgressBar');
  11817. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  11818. if (!playProgressBar && !mouseTimeDisplay) {
  11819. return;
  11820. }
  11821. const seekBarEl = seekBar.el();
  11822. const seekBarRect = findPosition(seekBarEl);
  11823. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  11824. // The default skin has a gap on either side of the `SeekBar`. This means
  11825. // that it's possible to trigger this behavior outside the boundaries of
  11826. // the `SeekBar`. This ensures we stay within it at all times.
  11827. seekBarPoint = clamp(seekBarPoint, 0, 1);
  11828. if (mouseTimeDisplay) {
  11829. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  11830. }
  11831. if (playProgressBar) {
  11832. playProgressBar.update(seekBarRect, seekBar.getProgress());
  11833. }
  11834. }
  11835. /**
  11836. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  11837. *
  11838. * @method ProgressControl#throttledHandleMouseSeek
  11839. * @param {Event} event
  11840. * The `mousemove` event that caused this function to run.
  11841. *
  11842. * @listen mousemove
  11843. * @listen touchmove
  11844. */
  11845. /**
  11846. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  11847. *
  11848. * @param {Event} event
  11849. * `mousedown` or `touchstart` event that triggered this function
  11850. *
  11851. * @listens mousemove
  11852. * @listens touchmove
  11853. */
  11854. handleMouseSeek(event) {
  11855. const seekBar = this.getChild('seekBar');
  11856. if (seekBar) {
  11857. seekBar.handleMouseMove(event);
  11858. }
  11859. }
  11860. /**
  11861. * Are controls are currently enabled for this progress control.
  11862. *
  11863. * @return {boolean}
  11864. * true if controls are enabled, false otherwise
  11865. */
  11866. enabled() {
  11867. return this.enabled_;
  11868. }
  11869. /**
  11870. * Disable all controls on the progress control and its children
  11871. */
  11872. disable() {
  11873. this.children().forEach(child => child.disable && child.disable());
  11874. if (!this.enabled()) {
  11875. return;
  11876. }
  11877. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11878. this.off(this.el_, 'mousemove', this.handleMouseMove);
  11879. this.removeListenersAddedOnMousedownAndTouchstart();
  11880. this.addClass('disabled');
  11881. this.enabled_ = false;
  11882. // Restore normal playback state if controls are disabled while scrubbing
  11883. if (this.player_.scrubbing()) {
  11884. const seekBar = this.getChild('seekBar');
  11885. this.player_.scrubbing(false);
  11886. if (seekBar.videoWasPlaying) {
  11887. silencePromise(this.player_.play());
  11888. }
  11889. }
  11890. }
  11891. /**
  11892. * Enable all controls on the progress control and its children
  11893. */
  11894. enable() {
  11895. this.children().forEach(child => child.enable && child.enable());
  11896. if (this.enabled()) {
  11897. return;
  11898. }
  11899. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11900. this.on(this.el_, 'mousemove', this.handleMouseMove);
  11901. this.removeClass('disabled');
  11902. this.enabled_ = true;
  11903. }
  11904. /**
  11905. * Cleanup listeners after the user finishes interacting with the progress controls
  11906. */
  11907. removeListenersAddedOnMousedownAndTouchstart() {
  11908. const doc = this.el_.ownerDocument;
  11909. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  11910. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  11911. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  11912. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  11913. }
  11914. /**
  11915. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  11916. *
  11917. * @param {Event} event
  11918. * `mousedown` or `touchstart` event that triggered this function
  11919. *
  11920. * @listens mousedown
  11921. * @listens touchstart
  11922. */
  11923. handleMouseDown(event) {
  11924. const doc = this.el_.ownerDocument;
  11925. const seekBar = this.getChild('seekBar');
  11926. if (seekBar) {
  11927. seekBar.handleMouseDown(event);
  11928. }
  11929. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  11930. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  11931. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  11932. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  11933. }
  11934. /**
  11935. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  11936. *
  11937. * @param {Event} event
  11938. * `mouseup` or `touchend` event that triggered this function.
  11939. *
  11940. * @listens touchend
  11941. * @listens mouseup
  11942. */
  11943. handleMouseUp(event) {
  11944. const seekBar = this.getChild('seekBar');
  11945. if (seekBar) {
  11946. seekBar.handleMouseUp(event);
  11947. }
  11948. this.removeListenersAddedOnMousedownAndTouchstart();
  11949. }
  11950. }
  11951. /**
  11952. * Default options for `ProgressControl`
  11953. *
  11954. * @type {Object}
  11955. * @private
  11956. */
  11957. ProgressControl.prototype.options_ = {
  11958. children: ['seekBar']
  11959. };
  11960. Component.registerComponent('ProgressControl', ProgressControl);
  11961. /**
  11962. * @file picture-in-picture-toggle.js
  11963. */
  11964. /**
  11965. * Toggle Picture-in-Picture mode
  11966. *
  11967. * @extends Button
  11968. */
  11969. class PictureInPictureToggle extends Button {
  11970. /**
  11971. * Creates an instance of this class.
  11972. *
  11973. * @param { import('./player').default } player
  11974. * The `Player` that this class should be attached to.
  11975. *
  11976. * @param {Object} [options]
  11977. * The key/value store of player options.
  11978. *
  11979. * @listens Player#enterpictureinpicture
  11980. * @listens Player#leavepictureinpicture
  11981. */
  11982. constructor(player, options) {
  11983. super(player, options);
  11984. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  11985. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  11986. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  11987. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  11988. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  11989. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  11990. if (player.isInPictureInPicture()) {
  11991. player.exitPictureInPicture();
  11992. }
  11993. this.hide();
  11994. } else {
  11995. this.show();
  11996. }
  11997. });
  11998. // TODO: Deactivate button on player emptied event.
  11999. this.disable();
  12000. }
  12001. /**
  12002. * Builds the default DOM `className`.
  12003. *
  12004. * @return {string}
  12005. * The DOM `className` for this object.
  12006. */
  12007. buildCSSClass() {
  12008. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  12009. }
  12010. /**
  12011. * Enables or disables button based on availability of a Picture-In-Picture mode.
  12012. *
  12013. * Enabled if
  12014. * - `player.options().enableDocumentPictureInPicture` is true and
  12015. * window.documentPictureInPicture is available; or
  12016. * - `player.disablePictureInPicture()` is false and
  12017. * element.requestPictureInPicture is available
  12018. */
  12019. handlePictureInPictureEnabledChange() {
  12020. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  12021. this.enable();
  12022. } else {
  12023. this.disable();
  12024. }
  12025. }
  12026. /**
  12027. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12028. *
  12029. * @param {Event} [event]
  12030. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12031. * called.
  12032. *
  12033. * @listens Player#enterpictureinpicture
  12034. * @listens Player#leavepictureinpicture
  12035. */
  12036. handlePictureInPictureChange(event) {
  12037. if (this.player_.isInPictureInPicture()) {
  12038. this.controlText('Exit Picture-in-Picture');
  12039. } else {
  12040. this.controlText('Picture-in-Picture');
  12041. }
  12042. this.handlePictureInPictureEnabledChange();
  12043. }
  12044. /**
  12045. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12046. * {@link ClickableComponent} for more detailed information on what a click can be.
  12047. *
  12048. * @param {Event} [event]
  12049. * The `keydown`, `tap`, or `click` event that caused this function to be
  12050. * called.
  12051. *
  12052. * @listens tap
  12053. * @listens click
  12054. */
  12055. handleClick(event) {
  12056. if (!this.player_.isInPictureInPicture()) {
  12057. this.player_.requestPictureInPicture();
  12058. } else {
  12059. this.player_.exitPictureInPicture();
  12060. }
  12061. }
  12062. }
  12063. /**
  12064. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12065. *
  12066. * @type {string}
  12067. * @protected
  12068. */
  12069. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12070. Component.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12071. /**
  12072. * @file fullscreen-toggle.js
  12073. */
  12074. /**
  12075. * Toggle fullscreen video
  12076. *
  12077. * @extends Button
  12078. */
  12079. class FullscreenToggle extends Button {
  12080. /**
  12081. * Creates an instance of this class.
  12082. *
  12083. * @param { import('./player').default } player
  12084. * The `Player` that this class should be attached to.
  12085. *
  12086. * @param {Object} [options]
  12087. * The key/value store of player options.
  12088. */
  12089. constructor(player, options) {
  12090. super(player, options);
  12091. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  12092. if (document[player.fsApi_.fullscreenEnabled] === false) {
  12093. this.disable();
  12094. }
  12095. }
  12096. /**
  12097. * Builds the default DOM `className`.
  12098. *
  12099. * @return {string}
  12100. * The DOM `className` for this object.
  12101. */
  12102. buildCSSClass() {
  12103. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  12104. }
  12105. /**
  12106. * Handles fullscreenchange on the player and change control text accordingly.
  12107. *
  12108. * @param {Event} [event]
  12109. * The {@link Player#fullscreenchange} event that caused this function to be
  12110. * called.
  12111. *
  12112. * @listens Player#fullscreenchange
  12113. */
  12114. handleFullscreenChange(event) {
  12115. if (this.player_.isFullscreen()) {
  12116. this.controlText('Exit Fullscreen');
  12117. } else {
  12118. this.controlText('Fullscreen');
  12119. }
  12120. }
  12121. /**
  12122. * This gets called when an `FullscreenToggle` is "clicked". See
  12123. * {@link ClickableComponent} for more detailed information on what a click can be.
  12124. *
  12125. * @param {Event} [event]
  12126. * The `keydown`, `tap`, or `click` event that caused this function to be
  12127. * called.
  12128. *
  12129. * @listens tap
  12130. * @listens click
  12131. */
  12132. handleClick(event) {
  12133. if (!this.player_.isFullscreen()) {
  12134. this.player_.requestFullscreen();
  12135. } else {
  12136. this.player_.exitFullscreen();
  12137. }
  12138. }
  12139. }
  12140. /**
  12141. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12142. *
  12143. * @type {string}
  12144. * @protected
  12145. */
  12146. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12147. Component.registerComponent('FullscreenToggle', FullscreenToggle);
  12148. /**
  12149. * Check if volume control is supported and if it isn't hide the
  12150. * `Component` that was passed using the `vjs-hidden` class.
  12151. *
  12152. * @param { import('../../component').default } self
  12153. * The component that should be hidden if volume is unsupported
  12154. *
  12155. * @param { import('../../player').default } player
  12156. * A reference to the player
  12157. *
  12158. * @private
  12159. */
  12160. const checkVolumeSupport = function (self, player) {
  12161. // hide volume controls when they're not supported by the current tech
  12162. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12163. self.addClass('vjs-hidden');
  12164. }
  12165. self.on(player, 'loadstart', function () {
  12166. if (!player.tech_.featuresVolumeControl) {
  12167. self.addClass('vjs-hidden');
  12168. } else {
  12169. self.removeClass('vjs-hidden');
  12170. }
  12171. });
  12172. };
  12173. /**
  12174. * @file volume-level.js
  12175. */
  12176. /**
  12177. * Shows volume level
  12178. *
  12179. * @extends Component
  12180. */
  12181. class VolumeLevel extends Component {
  12182. /**
  12183. * Create the `Component`'s DOM element
  12184. *
  12185. * @return {Element}
  12186. * The element that was created.
  12187. */
  12188. createEl() {
  12189. const el = super.createEl('div', {
  12190. className: 'vjs-volume-level'
  12191. });
  12192. el.appendChild(super.createEl('span', {
  12193. className: 'vjs-control-text'
  12194. }));
  12195. return el;
  12196. }
  12197. }
  12198. Component.registerComponent('VolumeLevel', VolumeLevel);
  12199. /**
  12200. * @file volume-level-tooltip.js
  12201. */
  12202. /**
  12203. * Volume level tooltips display a volume above or side by side the volume bar.
  12204. *
  12205. * @extends Component
  12206. */
  12207. class VolumeLevelTooltip extends Component {
  12208. /**
  12209. * Creates an instance of this class.
  12210. *
  12211. * @param { import('../../player').default } player
  12212. * The {@link Player} that this class should be attached to.
  12213. *
  12214. * @param {Object} [options]
  12215. * The key/value store of player options.
  12216. */
  12217. constructor(player, options) {
  12218. super(player, options);
  12219. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12220. }
  12221. /**
  12222. * Create the volume tooltip DOM element
  12223. *
  12224. * @return {Element}
  12225. * The element that was created.
  12226. */
  12227. createEl() {
  12228. return super.createEl('div', {
  12229. className: 'vjs-volume-tooltip'
  12230. }, {
  12231. 'aria-hidden': 'true'
  12232. });
  12233. }
  12234. /**
  12235. * Updates the position of the tooltip relative to the `VolumeBar` and
  12236. * its content text.
  12237. *
  12238. * @param {Object} rangeBarRect
  12239. * The `ClientRect` for the {@link VolumeBar} element.
  12240. *
  12241. * @param {number} rangeBarPoint
  12242. * A number from 0 to 1, representing a horizontal/vertical reference point
  12243. * from the left edge of the {@link VolumeBar}
  12244. *
  12245. * @param {boolean} vertical
  12246. * Referees to the Volume control position
  12247. * in the control bar{@link VolumeControl}
  12248. *
  12249. */
  12250. update(rangeBarRect, rangeBarPoint, vertical, content) {
  12251. if (!vertical) {
  12252. const tooltipRect = getBoundingClientRect(this.el_);
  12253. const playerRect = getBoundingClientRect(this.player_.el());
  12254. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  12255. if (!playerRect || !tooltipRect) {
  12256. return;
  12257. }
  12258. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  12259. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  12260. let pullTooltipBy = tooltipRect.width / 2;
  12261. if (spaceLeftOfPoint < pullTooltipBy) {
  12262. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12263. } else if (spaceRightOfPoint < pullTooltipBy) {
  12264. pullTooltipBy = spaceRightOfPoint;
  12265. }
  12266. if (pullTooltipBy < 0) {
  12267. pullTooltipBy = 0;
  12268. } else if (pullTooltipBy > tooltipRect.width) {
  12269. pullTooltipBy = tooltipRect.width;
  12270. }
  12271. this.el_.style.right = `-${pullTooltipBy}px`;
  12272. }
  12273. this.write(`${content}%`);
  12274. }
  12275. /**
  12276. * Write the volume to the tooltip DOM element.
  12277. *
  12278. * @param {string} content
  12279. * The formatted volume for the tooltip.
  12280. */
  12281. write(content) {
  12282. textContent(this.el_, content);
  12283. }
  12284. /**
  12285. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  12286. *
  12287. * @param {Object} rangeBarRect
  12288. * The `ClientRect` for the {@link VolumeBar} element.
  12289. *
  12290. * @param {number} rangeBarPoint
  12291. * A number from 0 to 1, representing a horizontal/vertical reference point
  12292. * from the left edge of the {@link VolumeBar}
  12293. *
  12294. * @param {boolean} vertical
  12295. * Referees to the Volume control position
  12296. * in the control bar{@link VolumeControl}
  12297. *
  12298. * @param {number} volume
  12299. * The volume level to update the tooltip to
  12300. *
  12301. * @param {Function} cb
  12302. * A function that will be called during the request animation frame
  12303. * for tooltips that need to do additional animations from the default
  12304. */
  12305. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  12306. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  12307. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  12308. if (cb) {
  12309. cb();
  12310. }
  12311. });
  12312. }
  12313. }
  12314. Component.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  12315. /**
  12316. * @file mouse-volume-level-display.js
  12317. */
  12318. /**
  12319. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  12320. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  12321. * indicating the volume level which is represented by a given point in the
  12322. * {@link VolumeBar}.
  12323. *
  12324. * @extends Component
  12325. */
  12326. class MouseVolumeLevelDisplay extends Component {
  12327. /**
  12328. * Creates an instance of this class.
  12329. *
  12330. * @param { import('../../player').default } player
  12331. * The {@link Player} that this class should be attached to.
  12332. *
  12333. * @param {Object} [options]
  12334. * The key/value store of player options.
  12335. */
  12336. constructor(player, options) {
  12337. super(player, options);
  12338. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12339. }
  12340. /**
  12341. * Create the DOM element for this class.
  12342. *
  12343. * @return {Element}
  12344. * The element that was created.
  12345. */
  12346. createEl() {
  12347. return super.createEl('div', {
  12348. className: 'vjs-mouse-display'
  12349. });
  12350. }
  12351. /**
  12352. * Enquires updates to its own DOM as well as the DOM of its
  12353. * {@link VolumeLevelTooltip} child.
  12354. *
  12355. * @param {Object} rangeBarRect
  12356. * The `ClientRect` for the {@link VolumeBar} element.
  12357. *
  12358. * @param {number} rangeBarPoint
  12359. * A number from 0 to 1, representing a horizontal/vertical reference point
  12360. * from the left edge of the {@link VolumeBar}
  12361. *
  12362. * @param {boolean} vertical
  12363. * Referees to the Volume control position
  12364. * in the control bar{@link VolumeControl}
  12365. *
  12366. */
  12367. update(rangeBarRect, rangeBarPoint, vertical) {
  12368. const volume = 100 * rangeBarPoint;
  12369. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  12370. if (vertical) {
  12371. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  12372. } else {
  12373. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  12374. }
  12375. });
  12376. }
  12377. }
  12378. /**
  12379. * Default options for `MouseVolumeLevelDisplay`
  12380. *
  12381. * @type {Object}
  12382. * @private
  12383. */
  12384. MouseVolumeLevelDisplay.prototype.options_ = {
  12385. children: ['volumeLevelTooltip']
  12386. };
  12387. Component.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  12388. /**
  12389. * @file volume-bar.js
  12390. */
  12391. /**
  12392. * The bar that contains the volume level and can be clicked on to adjust the level
  12393. *
  12394. * @extends Slider
  12395. */
  12396. class VolumeBar extends Slider {
  12397. /**
  12398. * Creates an instance of this class.
  12399. *
  12400. * @param { import('../../player').default } player
  12401. * The `Player` that this class should be attached to.
  12402. *
  12403. * @param {Object} [options]
  12404. * The key/value store of player options.
  12405. */
  12406. constructor(player, options) {
  12407. super(player, options);
  12408. this.on('slideractive', e => this.updateLastVolume_(e));
  12409. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  12410. player.ready(() => this.updateARIAAttributes());
  12411. }
  12412. /**
  12413. * Create the `Component`'s DOM element
  12414. *
  12415. * @return {Element}
  12416. * The element that was created.
  12417. */
  12418. createEl() {
  12419. return super.createEl('div', {
  12420. className: 'vjs-volume-bar vjs-slider-bar'
  12421. }, {
  12422. 'aria-label': this.localize('Volume Level'),
  12423. 'aria-live': 'polite'
  12424. });
  12425. }
  12426. /**
  12427. * Handle mouse down on volume bar
  12428. *
  12429. * @param {Event} event
  12430. * The `mousedown` event that caused this to run.
  12431. *
  12432. * @listens mousedown
  12433. */
  12434. handleMouseDown(event) {
  12435. if (!isSingleLeftClick(event)) {
  12436. return;
  12437. }
  12438. super.handleMouseDown(event);
  12439. }
  12440. /**
  12441. * Handle movement events on the {@link VolumeMenuButton}.
  12442. *
  12443. * @param {Event} event
  12444. * The event that caused this function to run.
  12445. *
  12446. * @listens mousemove
  12447. */
  12448. handleMouseMove(event) {
  12449. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  12450. if (mouseVolumeLevelDisplay) {
  12451. const volumeBarEl = this.el();
  12452. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  12453. const vertical = this.vertical();
  12454. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  12455. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  12456. // The default skin has a gap on either side of the `VolumeBar`. This means
  12457. // that it's possible to trigger this behavior outside the boundaries of
  12458. // the `VolumeBar`. This ensures we stay within it at all times.
  12459. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  12460. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  12461. }
  12462. if (!isSingleLeftClick(event)) {
  12463. return;
  12464. }
  12465. this.checkMuted();
  12466. this.player_.volume(this.calculateDistance(event));
  12467. }
  12468. /**
  12469. * If the player is muted unmute it.
  12470. */
  12471. checkMuted() {
  12472. if (this.player_.muted()) {
  12473. this.player_.muted(false);
  12474. }
  12475. }
  12476. /**
  12477. * Get percent of volume level
  12478. *
  12479. * @return {number}
  12480. * Volume level percent as a decimal number.
  12481. */
  12482. getPercent() {
  12483. if (this.player_.muted()) {
  12484. return 0;
  12485. }
  12486. return this.player_.volume();
  12487. }
  12488. /**
  12489. * Increase volume level for keyboard users
  12490. */
  12491. stepForward() {
  12492. this.checkMuted();
  12493. this.player_.volume(this.player_.volume() + 0.1);
  12494. }
  12495. /**
  12496. * Decrease volume level for keyboard users
  12497. */
  12498. stepBack() {
  12499. this.checkMuted();
  12500. this.player_.volume(this.player_.volume() - 0.1);
  12501. }
  12502. /**
  12503. * Update ARIA accessibility attributes
  12504. *
  12505. * @param {Event} [event]
  12506. * The `volumechange` event that caused this function to run.
  12507. *
  12508. * @listens Player#volumechange
  12509. */
  12510. updateARIAAttributes(event) {
  12511. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  12512. this.el_.setAttribute('aria-valuenow', ariaValue);
  12513. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  12514. }
  12515. /**
  12516. * Returns the current value of the player volume as a percentage
  12517. *
  12518. * @private
  12519. */
  12520. volumeAsPercentage_() {
  12521. return Math.round(this.player_.volume() * 100);
  12522. }
  12523. /**
  12524. * When user starts dragging the VolumeBar, store the volume and listen for
  12525. * the end of the drag. When the drag ends, if the volume was set to zero,
  12526. * set lastVolume to the stored volume.
  12527. *
  12528. * @listens slideractive
  12529. * @private
  12530. */
  12531. updateLastVolume_() {
  12532. const volumeBeforeDrag = this.player_.volume();
  12533. this.one('sliderinactive', () => {
  12534. if (this.player_.volume() === 0) {
  12535. this.player_.lastVolume_(volumeBeforeDrag);
  12536. }
  12537. });
  12538. }
  12539. }
  12540. /**
  12541. * Default options for the `VolumeBar`
  12542. *
  12543. * @type {Object}
  12544. * @private
  12545. */
  12546. VolumeBar.prototype.options_ = {
  12547. children: ['volumeLevel'],
  12548. barName: 'volumeLevel'
  12549. };
  12550. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  12551. if (!IS_IOS && !IS_ANDROID) {
  12552. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  12553. }
  12554. /**
  12555. * Call the update event for this Slider when this event happens on the player.
  12556. *
  12557. * @type {string}
  12558. */
  12559. VolumeBar.prototype.playerEvent = 'volumechange';
  12560. Component.registerComponent('VolumeBar', VolumeBar);
  12561. /**
  12562. * @file volume-control.js
  12563. */
  12564. /**
  12565. * The component for controlling the volume level
  12566. *
  12567. * @extends Component
  12568. */
  12569. class VolumeControl extends Component {
  12570. /**
  12571. * Creates an instance of this class.
  12572. *
  12573. * @param { import('../../player').default } player
  12574. * The `Player` that this class should be attached to.
  12575. *
  12576. * @param {Object} [options={}]
  12577. * The key/value store of player options.
  12578. */
  12579. constructor(player, options = {}) {
  12580. options.vertical = options.vertical || false;
  12581. // Pass the vertical option down to the VolumeBar if
  12582. // the VolumeBar is turned on.
  12583. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  12584. options.volumeBar = options.volumeBar || {};
  12585. options.volumeBar.vertical = options.vertical;
  12586. }
  12587. super(player, options);
  12588. // hide this control if volume support is missing
  12589. checkVolumeSupport(this, player);
  12590. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12591. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  12592. this.on('mousedown', e => this.handleMouseDown(e));
  12593. this.on('touchstart', e => this.handleMouseDown(e));
  12594. this.on('mousemove', e => this.handleMouseMove(e));
  12595. // while the slider is active (the mouse has been pressed down and
  12596. // is dragging) or in focus we do not want to hide the VolumeBar
  12597. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  12598. this.volumeBar.addClass('vjs-slider-active');
  12599. this.addClass('vjs-slider-active');
  12600. this.trigger('slideractive');
  12601. });
  12602. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  12603. this.volumeBar.removeClass('vjs-slider-active');
  12604. this.removeClass('vjs-slider-active');
  12605. this.trigger('sliderinactive');
  12606. });
  12607. }
  12608. /**
  12609. * Create the `Component`'s DOM element
  12610. *
  12611. * @return {Element}
  12612. * The element that was created.
  12613. */
  12614. createEl() {
  12615. let orientationClass = 'vjs-volume-horizontal';
  12616. if (this.options_.vertical) {
  12617. orientationClass = 'vjs-volume-vertical';
  12618. }
  12619. return super.createEl('div', {
  12620. className: `vjs-volume-control vjs-control ${orientationClass}`
  12621. });
  12622. }
  12623. /**
  12624. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12625. *
  12626. * @param {Event} event
  12627. * `mousedown` or `touchstart` event that triggered this function
  12628. *
  12629. * @listens mousedown
  12630. * @listens touchstart
  12631. */
  12632. handleMouseDown(event) {
  12633. const doc = this.el_.ownerDocument;
  12634. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  12635. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  12636. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12637. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12638. }
  12639. /**
  12640. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  12641. *
  12642. * @param {Event} event
  12643. * `mouseup` or `touchend` event that triggered this function.
  12644. *
  12645. * @listens touchend
  12646. * @listens mouseup
  12647. */
  12648. handleMouseUp(event) {
  12649. const doc = this.el_.ownerDocument;
  12650. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  12651. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  12652. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12653. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12654. }
  12655. /**
  12656. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12657. *
  12658. * @param {Event} event
  12659. * `mousedown` or `touchstart` event that triggered this function
  12660. *
  12661. * @listens mousedown
  12662. * @listens touchstart
  12663. */
  12664. handleMouseMove(event) {
  12665. this.volumeBar.handleMouseMove(event);
  12666. }
  12667. }
  12668. /**
  12669. * Default options for the `VolumeControl`
  12670. *
  12671. * @type {Object}
  12672. * @private
  12673. */
  12674. VolumeControl.prototype.options_ = {
  12675. children: ['volumeBar']
  12676. };
  12677. Component.registerComponent('VolumeControl', VolumeControl);
  12678. /**
  12679. * Check if muting volume is supported and if it isn't hide the mute toggle
  12680. * button.
  12681. *
  12682. * @param { import('../../component').default } self
  12683. * A reference to the mute toggle button
  12684. *
  12685. * @param { import('../../player').default } player
  12686. * A reference to the player
  12687. *
  12688. * @private
  12689. */
  12690. const checkMuteSupport = function (self, player) {
  12691. // hide mute toggle button if it's not supported by the current tech
  12692. if (player.tech_ && !player.tech_.featuresMuteControl) {
  12693. self.addClass('vjs-hidden');
  12694. }
  12695. self.on(player, 'loadstart', function () {
  12696. if (!player.tech_.featuresMuteControl) {
  12697. self.addClass('vjs-hidden');
  12698. } else {
  12699. self.removeClass('vjs-hidden');
  12700. }
  12701. });
  12702. };
  12703. /**
  12704. * @file mute-toggle.js
  12705. */
  12706. /**
  12707. * A button component for muting the audio.
  12708. *
  12709. * @extends Button
  12710. */
  12711. class MuteToggle extends Button {
  12712. /**
  12713. * Creates an instance of this class.
  12714. *
  12715. * @param { import('./player').default } player
  12716. * The `Player` that this class should be attached to.
  12717. *
  12718. * @param {Object} [options]
  12719. * The key/value store of player options.
  12720. */
  12721. constructor(player, options) {
  12722. super(player, options);
  12723. // hide this control if volume support is missing
  12724. checkMuteSupport(this, player);
  12725. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  12726. }
  12727. /**
  12728. * Builds the default DOM `className`.
  12729. *
  12730. * @return {string}
  12731. * The DOM `className` for this object.
  12732. */
  12733. buildCSSClass() {
  12734. return `vjs-mute-control ${super.buildCSSClass()}`;
  12735. }
  12736. /**
  12737. * This gets called when an `MuteToggle` is "clicked". See
  12738. * {@link ClickableComponent} for more detailed information on what a click can be.
  12739. *
  12740. * @param {Event} [event]
  12741. * The `keydown`, `tap`, or `click` event that caused this function to be
  12742. * called.
  12743. *
  12744. * @listens tap
  12745. * @listens click
  12746. */
  12747. handleClick(event) {
  12748. const vol = this.player_.volume();
  12749. const lastVolume = this.player_.lastVolume_();
  12750. if (vol === 0) {
  12751. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  12752. this.player_.volume(volumeToSet);
  12753. this.player_.muted(false);
  12754. } else {
  12755. this.player_.muted(this.player_.muted() ? false : true);
  12756. }
  12757. }
  12758. /**
  12759. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  12760. * on the player.
  12761. *
  12762. * @param {Event} [event]
  12763. * The {@link Player#loadstart} event if this function was called
  12764. * through an event.
  12765. *
  12766. * @listens Player#loadstart
  12767. * @listens Player#volumechange
  12768. */
  12769. update(event) {
  12770. this.updateIcon_();
  12771. this.updateControlText_();
  12772. }
  12773. /**
  12774. * Update the appearance of the `MuteToggle` icon.
  12775. *
  12776. * Possible states (given `level` variable below):
  12777. * - 0: crossed out
  12778. * - 1: zero bars of volume
  12779. * - 2: one bar of volume
  12780. * - 3: two bars of volume
  12781. *
  12782. * @private
  12783. */
  12784. updateIcon_() {
  12785. const vol = this.player_.volume();
  12786. let level = 3;
  12787. // in iOS when a player is loaded with muted attribute
  12788. // and volume is changed with a native mute button
  12789. // we want to make sure muted state is updated
  12790. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  12791. this.player_.muted(this.player_.tech_.el_.muted);
  12792. }
  12793. if (vol === 0 || this.player_.muted()) {
  12794. level = 0;
  12795. } else if (vol < 0.33) {
  12796. level = 1;
  12797. } else if (vol < 0.67) {
  12798. level = 2;
  12799. }
  12800. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  12801. addClass(this.el_, `vjs-vol-${level}`);
  12802. }
  12803. /**
  12804. * If `muted` has changed on the player, update the control text
  12805. * (`title` attribute on `vjs-mute-control` element and content of
  12806. * `vjs-control-text` element).
  12807. *
  12808. * @private
  12809. */
  12810. updateControlText_() {
  12811. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  12812. const text = soundOff ? 'Unmute' : 'Mute';
  12813. if (this.controlText() !== text) {
  12814. this.controlText(text);
  12815. }
  12816. }
  12817. }
  12818. /**
  12819. * The text that should display over the `MuteToggle`s controls. Added for localization.
  12820. *
  12821. * @type {string}
  12822. * @protected
  12823. */
  12824. MuteToggle.prototype.controlText_ = 'Mute';
  12825. Component.registerComponent('MuteToggle', MuteToggle);
  12826. /**
  12827. * @file volume-control.js
  12828. */
  12829. /**
  12830. * A Component to contain the MuteToggle and VolumeControl so that
  12831. * they can work together.
  12832. *
  12833. * @extends Component
  12834. */
  12835. class VolumePanel extends Component {
  12836. /**
  12837. * Creates an instance of this class.
  12838. *
  12839. * @param { import('./player').default } player
  12840. * The `Player` that this class should be attached to.
  12841. *
  12842. * @param {Object} [options={}]
  12843. * The key/value store of player options.
  12844. */
  12845. constructor(player, options = {}) {
  12846. if (typeof options.inline !== 'undefined') {
  12847. options.inline = options.inline;
  12848. } else {
  12849. options.inline = true;
  12850. }
  12851. // pass the inline option down to the VolumeControl as vertical if
  12852. // the VolumeControl is on.
  12853. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  12854. options.volumeControl = options.volumeControl || {};
  12855. options.volumeControl.vertical = !options.inline;
  12856. }
  12857. super(player, options);
  12858. // this handler is used by mouse handler methods below
  12859. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  12860. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  12861. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  12862. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  12863. this.on('keydown', e => this.handleKeyPress(e));
  12864. this.on('mouseover', e => this.handleMouseOver(e));
  12865. this.on('mouseout', e => this.handleMouseOut(e));
  12866. // while the slider is active (the mouse has been pressed down and
  12867. // is dragging) we do not want to hide the VolumeBar
  12868. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  12869. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  12870. }
  12871. /**
  12872. * Add vjs-slider-active class to the VolumePanel
  12873. *
  12874. * @listens VolumeControl#slideractive
  12875. * @private
  12876. */
  12877. sliderActive_() {
  12878. this.addClass('vjs-slider-active');
  12879. }
  12880. /**
  12881. * Removes vjs-slider-active class to the VolumePanel
  12882. *
  12883. * @listens VolumeControl#sliderinactive
  12884. * @private
  12885. */
  12886. sliderInactive_() {
  12887. this.removeClass('vjs-slider-active');
  12888. }
  12889. /**
  12890. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  12891. * depending on MuteToggle and VolumeControl state
  12892. *
  12893. * @listens Player#loadstart
  12894. * @private
  12895. */
  12896. volumePanelState_() {
  12897. // hide volume panel if neither volume control or mute toggle
  12898. // are displayed
  12899. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  12900. this.addClass('vjs-hidden');
  12901. }
  12902. // if only mute toggle is visible we don't want
  12903. // volume panel expanding when hovered or active
  12904. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  12905. this.addClass('vjs-mute-toggle-only');
  12906. }
  12907. }
  12908. /**
  12909. * Create the `Component`'s DOM element
  12910. *
  12911. * @return {Element}
  12912. * The element that was created.
  12913. */
  12914. createEl() {
  12915. let orientationClass = 'vjs-volume-panel-horizontal';
  12916. if (!this.options_.inline) {
  12917. orientationClass = 'vjs-volume-panel-vertical';
  12918. }
  12919. return super.createEl('div', {
  12920. className: `vjs-volume-panel vjs-control ${orientationClass}`
  12921. });
  12922. }
  12923. /**
  12924. * Dispose of the `volume-panel` and all child components.
  12925. */
  12926. dispose() {
  12927. this.handleMouseOut();
  12928. super.dispose();
  12929. }
  12930. /**
  12931. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  12932. * the volume panel and sets focus on `MuteToggle`.
  12933. *
  12934. * @param {Event} event
  12935. * The `keyup` event that caused this function to be called.
  12936. *
  12937. * @listens keyup
  12938. */
  12939. handleVolumeControlKeyUp(event) {
  12940. if (keycode.isEventKey(event, 'Esc')) {
  12941. this.muteToggle.focus();
  12942. }
  12943. }
  12944. /**
  12945. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  12946. * Turns on listening for `mouseover` event. When they happen it
  12947. * calls `this.handleMouseOver`.
  12948. *
  12949. * @param {Event} event
  12950. * The `mouseover` event that caused this function to be called.
  12951. *
  12952. * @listens mouseover
  12953. */
  12954. handleMouseOver(event) {
  12955. this.addClass('vjs-hover');
  12956. on(document, 'keyup', this.handleKeyPressHandler_);
  12957. }
  12958. /**
  12959. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  12960. * Turns on listening for `mouseout` event. When they happen it
  12961. * calls `this.handleMouseOut`.
  12962. *
  12963. * @param {Event} event
  12964. * The `mouseout` event that caused this function to be called.
  12965. *
  12966. * @listens mouseout
  12967. */
  12968. handleMouseOut(event) {
  12969. this.removeClass('vjs-hover');
  12970. off(document, 'keyup', this.handleKeyPressHandler_);
  12971. }
  12972. /**
  12973. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  12974. * looking for ESC, which hides the `VolumeControl`.
  12975. *
  12976. * @param {Event} event
  12977. * The keypress that triggered this event.
  12978. *
  12979. * @listens keydown | keyup
  12980. */
  12981. handleKeyPress(event) {
  12982. if (keycode.isEventKey(event, 'Esc')) {
  12983. this.handleMouseOut();
  12984. }
  12985. }
  12986. }
  12987. /**
  12988. * Default options for the `VolumeControl`
  12989. *
  12990. * @type {Object}
  12991. * @private
  12992. */
  12993. VolumePanel.prototype.options_ = {
  12994. children: ['muteToggle', 'volumeControl']
  12995. };
  12996. Component.registerComponent('VolumePanel', VolumePanel);
  12997. /**
  12998. * Button to skip forward a configurable amount of time
  12999. * through a video. Renders in the control bar.
  13000. *
  13001. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  13002. *
  13003. * @extends Button
  13004. */
  13005. class SkipForward extends Button {
  13006. constructor(player, options) {
  13007. super(player, options);
  13008. this.validOptions = [5, 10, 30];
  13009. this.skipTime = this.getSkipForwardTime();
  13010. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13011. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13012. this.show();
  13013. } else {
  13014. this.hide();
  13015. }
  13016. }
  13017. getSkipForwardTime() {
  13018. const playerOptions = this.options_.playerOptions;
  13019. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  13020. }
  13021. buildCSSClass() {
  13022. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  13023. }
  13024. /**
  13025. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  13026. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  13027. * skips to end of duration/seekable range.
  13028. *
  13029. * Handle a click on a `SkipForward` button
  13030. *
  13031. * @param {EventTarget~Event} event
  13032. * The `click` event that caused this function
  13033. * to be called
  13034. */
  13035. handleClick(event) {
  13036. const currentVideoTime = this.player_.currentTime();
  13037. const liveTracker = this.player_.liveTracker;
  13038. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13039. let newTime;
  13040. if (currentVideoTime + this.skipTime <= duration) {
  13041. newTime = currentVideoTime + this.skipTime;
  13042. } else {
  13043. newTime = duration;
  13044. }
  13045. this.player_.currentTime(newTime);
  13046. }
  13047. /**
  13048. * Update control text on languagechange
  13049. */
  13050. handleLanguagechange() {
  13051. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13052. }
  13053. }
  13054. Component.registerComponent('SkipForward', SkipForward);
  13055. /**
  13056. * Button to skip backward a configurable amount of time
  13057. * through a video. Renders in the control bar.
  13058. *
  13059. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  13060. *
  13061. * @extends Button
  13062. */
  13063. class SkipBackward extends Button {
  13064. constructor(player, options) {
  13065. super(player, options);
  13066. this.validOptions = [5, 10, 30];
  13067. this.skipTime = this.getSkipBackwardTime();
  13068. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13069. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13070. this.show();
  13071. } else {
  13072. this.hide();
  13073. }
  13074. }
  13075. getSkipBackwardTime() {
  13076. const playerOptions = this.options_.playerOptions;
  13077. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  13078. }
  13079. buildCSSClass() {
  13080. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  13081. }
  13082. /**
  13083. * On click, skips backward in the video by a configurable amount of seconds.
  13084. * If the current time in the video is less than the configured 'skip backward' time,
  13085. * skips to beginning of video or seekable range.
  13086. *
  13087. * Handle a click on a `SkipBackward` button
  13088. *
  13089. * @param {EventTarget~Event} event
  13090. * The `click` event that caused this function
  13091. * to be called
  13092. */
  13093. handleClick(event) {
  13094. const currentVideoTime = this.player_.currentTime();
  13095. const liveTracker = this.player_.liveTracker;
  13096. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  13097. let newTime;
  13098. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  13099. newTime = seekableStart;
  13100. } else if (currentVideoTime >= this.skipTime) {
  13101. newTime = currentVideoTime - this.skipTime;
  13102. } else {
  13103. newTime = 0;
  13104. }
  13105. this.player_.currentTime(newTime);
  13106. }
  13107. /**
  13108. * Update control text on languagechange
  13109. */
  13110. handleLanguagechange() {
  13111. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13112. }
  13113. }
  13114. SkipBackward.prototype.controlText_ = 'Skip Backward';
  13115. Component.registerComponent('SkipBackward', SkipBackward);
  13116. /**
  13117. * @file menu.js
  13118. */
  13119. /**
  13120. * The Menu component is used to build popup menus, including subtitle and
  13121. * captions selection menus.
  13122. *
  13123. * @extends Component
  13124. */
  13125. class Menu extends Component {
  13126. /**
  13127. * Create an instance of this class.
  13128. *
  13129. * @param { import('../player').default } player
  13130. * the player that this component should attach to
  13131. *
  13132. * @param {Object} [options]
  13133. * Object of option names and values
  13134. *
  13135. */
  13136. constructor(player, options) {
  13137. super(player, options);
  13138. if (options) {
  13139. this.menuButton_ = options.menuButton;
  13140. }
  13141. this.focusedChild_ = -1;
  13142. this.on('keydown', e => this.handleKeyDown(e));
  13143. // All the menu item instances share the same blur handler provided by the menu container.
  13144. this.boundHandleBlur_ = e => this.handleBlur(e);
  13145. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  13146. }
  13147. /**
  13148. * Add event listeners to the {@link MenuItem}.
  13149. *
  13150. * @param {Object} component
  13151. * The instance of the `MenuItem` to add listeners to.
  13152. *
  13153. */
  13154. addEventListenerForItem(component) {
  13155. if (!(component instanceof Component)) {
  13156. return;
  13157. }
  13158. this.on(component, 'blur', this.boundHandleBlur_);
  13159. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13160. }
  13161. /**
  13162. * Remove event listeners from the {@link MenuItem}.
  13163. *
  13164. * @param {Object} component
  13165. * The instance of the `MenuItem` to remove listeners.
  13166. *
  13167. */
  13168. removeEventListenerForItem(component) {
  13169. if (!(component instanceof Component)) {
  13170. return;
  13171. }
  13172. this.off(component, 'blur', this.boundHandleBlur_);
  13173. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13174. }
  13175. /**
  13176. * This method will be called indirectly when the component has been added
  13177. * before the component adds to the new menu instance by `addItem`.
  13178. * In this case, the original menu instance will remove the component
  13179. * by calling `removeChild`.
  13180. *
  13181. * @param {Object} component
  13182. * The instance of the `MenuItem`
  13183. */
  13184. removeChild(component) {
  13185. if (typeof component === 'string') {
  13186. component = this.getChild(component);
  13187. }
  13188. this.removeEventListenerForItem(component);
  13189. super.removeChild(component);
  13190. }
  13191. /**
  13192. * Add a {@link MenuItem} to the menu.
  13193. *
  13194. * @param {Object|string} component
  13195. * The name or instance of the `MenuItem` to add.
  13196. *
  13197. */
  13198. addItem(component) {
  13199. const childComponent = this.addChild(component);
  13200. if (childComponent) {
  13201. this.addEventListenerForItem(childComponent);
  13202. }
  13203. }
  13204. /**
  13205. * Create the `Menu`s DOM element.
  13206. *
  13207. * @return {Element}
  13208. * the element that was created
  13209. */
  13210. createEl() {
  13211. const contentElType = this.options_.contentElType || 'ul';
  13212. this.contentEl_ = createEl(contentElType, {
  13213. className: 'vjs-menu-content'
  13214. });
  13215. this.contentEl_.setAttribute('role', 'menu');
  13216. const el = super.createEl('div', {
  13217. append: this.contentEl_,
  13218. className: 'vjs-menu'
  13219. });
  13220. el.appendChild(this.contentEl_);
  13221. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  13222. // where a click on the parent is significant
  13223. on(el, 'click', function (event) {
  13224. event.preventDefault();
  13225. event.stopImmediatePropagation();
  13226. });
  13227. return el;
  13228. }
  13229. dispose() {
  13230. this.contentEl_ = null;
  13231. this.boundHandleBlur_ = null;
  13232. this.boundHandleTapClick_ = null;
  13233. super.dispose();
  13234. }
  13235. /**
  13236. * Called when a `MenuItem` loses focus.
  13237. *
  13238. * @param {Event} event
  13239. * The `blur` event that caused this function to be called.
  13240. *
  13241. * @listens blur
  13242. */
  13243. handleBlur(event) {
  13244. const relatedTarget = event.relatedTarget || document.activeElement;
  13245. // Close menu popup when a user clicks outside the menu
  13246. if (!this.children().some(element => {
  13247. return element.el() === relatedTarget;
  13248. })) {
  13249. const btn = this.menuButton_;
  13250. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  13251. btn.unpressButton();
  13252. }
  13253. }
  13254. }
  13255. /**
  13256. * Called when a `MenuItem` gets clicked or tapped.
  13257. *
  13258. * @param {Event} event
  13259. * The `click` or `tap` event that caused this function to be called.
  13260. *
  13261. * @listens click,tap
  13262. */
  13263. handleTapClick(event) {
  13264. // Unpress the associated MenuButton, and move focus back to it
  13265. if (this.menuButton_) {
  13266. this.menuButton_.unpressButton();
  13267. const childComponents = this.children();
  13268. if (!Array.isArray(childComponents)) {
  13269. return;
  13270. }
  13271. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  13272. if (!foundComponent) {
  13273. return;
  13274. }
  13275. // don't focus menu button if item is a caption settings item
  13276. // because focus will move elsewhere
  13277. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  13278. this.menuButton_.focus();
  13279. }
  13280. }
  13281. }
  13282. /**
  13283. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  13284. *
  13285. * @param {Event} event
  13286. * A `keydown` event that happened on the menu.
  13287. *
  13288. * @listens keydown
  13289. */
  13290. handleKeyDown(event) {
  13291. // Left and Down Arrows
  13292. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13293. event.preventDefault();
  13294. event.stopPropagation();
  13295. this.stepForward();
  13296. // Up and Right Arrows
  13297. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13298. event.preventDefault();
  13299. event.stopPropagation();
  13300. this.stepBack();
  13301. }
  13302. }
  13303. /**
  13304. * Move to next (lower) menu item for keyboard users.
  13305. */
  13306. stepForward() {
  13307. let stepChild = 0;
  13308. if (this.focusedChild_ !== undefined) {
  13309. stepChild = this.focusedChild_ + 1;
  13310. }
  13311. this.focus(stepChild);
  13312. }
  13313. /**
  13314. * Move to previous (higher) menu item for keyboard users.
  13315. */
  13316. stepBack() {
  13317. let stepChild = 0;
  13318. if (this.focusedChild_ !== undefined) {
  13319. stepChild = this.focusedChild_ - 1;
  13320. }
  13321. this.focus(stepChild);
  13322. }
  13323. /**
  13324. * Set focus on a {@link MenuItem} in the `Menu`.
  13325. *
  13326. * @param {Object|string} [item=0]
  13327. * Index of child item set focus on.
  13328. */
  13329. focus(item = 0) {
  13330. const children = this.children().slice();
  13331. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  13332. if (haveTitle) {
  13333. children.shift();
  13334. }
  13335. if (children.length > 0) {
  13336. if (item < 0) {
  13337. item = 0;
  13338. } else if (item >= children.length) {
  13339. item = children.length - 1;
  13340. }
  13341. this.focusedChild_ = item;
  13342. children[item].el_.focus();
  13343. }
  13344. }
  13345. }
  13346. Component.registerComponent('Menu', Menu);
  13347. /**
  13348. * @file menu-button.js
  13349. */
  13350. /**
  13351. * A `MenuButton` class for any popup {@link Menu}.
  13352. *
  13353. * @extends Component
  13354. */
  13355. class MenuButton extends Component {
  13356. /**
  13357. * Creates an instance of this class.
  13358. *
  13359. * @param { import('../player').default } player
  13360. * The `Player` that this class should be attached to.
  13361. *
  13362. * @param {Object} [options={}]
  13363. * The key/value store of player options.
  13364. */
  13365. constructor(player, options = {}) {
  13366. super(player, options);
  13367. this.menuButton_ = new Button(player, options);
  13368. this.menuButton_.controlText(this.controlText_);
  13369. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  13370. // Add buildCSSClass values to the button, not the wrapper
  13371. const buttonClass = Button.prototype.buildCSSClass();
  13372. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  13373. this.menuButton_.removeClass('vjs-control');
  13374. this.addChild(this.menuButton_);
  13375. this.update();
  13376. this.enabled_ = true;
  13377. const handleClick = e => this.handleClick(e);
  13378. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  13379. this.on(this.menuButton_, 'tap', handleClick);
  13380. this.on(this.menuButton_, 'click', handleClick);
  13381. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  13382. this.on(this.menuButton_, 'mouseenter', () => {
  13383. this.addClass('vjs-hover');
  13384. this.menu.show();
  13385. on(document, 'keyup', this.handleMenuKeyUp_);
  13386. });
  13387. this.on('mouseleave', e => this.handleMouseLeave(e));
  13388. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  13389. }
  13390. /**
  13391. * Update the menu based on the current state of its items.
  13392. */
  13393. update() {
  13394. const menu = this.createMenu();
  13395. if (this.menu) {
  13396. this.menu.dispose();
  13397. this.removeChild(this.menu);
  13398. }
  13399. this.menu = menu;
  13400. this.addChild(menu);
  13401. /**
  13402. * Track the state of the menu button
  13403. *
  13404. * @type {Boolean}
  13405. * @private
  13406. */
  13407. this.buttonPressed_ = false;
  13408. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13409. if (this.items && this.items.length <= this.hideThreshold_) {
  13410. this.hide();
  13411. this.menu.contentEl_.removeAttribute('role');
  13412. } else {
  13413. this.show();
  13414. this.menu.contentEl_.setAttribute('role', 'menu');
  13415. }
  13416. }
  13417. /**
  13418. * Create the menu and add all items to it.
  13419. *
  13420. * @return {Menu}
  13421. * The constructed menu
  13422. */
  13423. createMenu() {
  13424. const menu = new Menu(this.player_, {
  13425. menuButton: this
  13426. });
  13427. /**
  13428. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  13429. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  13430. * it here because every time we run `createMenu` we need to reset the value.
  13431. *
  13432. * @protected
  13433. * @type {Number}
  13434. */
  13435. this.hideThreshold_ = 0;
  13436. // Add a title list item to the top
  13437. if (this.options_.title) {
  13438. const titleEl = createEl('li', {
  13439. className: 'vjs-menu-title',
  13440. textContent: toTitleCase(this.options_.title),
  13441. tabIndex: -1
  13442. });
  13443. const titleComponent = new Component(this.player_, {
  13444. el: titleEl
  13445. });
  13446. menu.addItem(titleComponent);
  13447. }
  13448. this.items = this.createItems();
  13449. if (this.items) {
  13450. // Add menu items to the menu
  13451. for (let i = 0; i < this.items.length; i++) {
  13452. menu.addItem(this.items[i]);
  13453. }
  13454. }
  13455. return menu;
  13456. }
  13457. /**
  13458. * Create the list of menu items. Specific to each subclass.
  13459. *
  13460. * @abstract
  13461. */
  13462. createItems() {}
  13463. /**
  13464. * Create the `MenuButtons`s DOM element.
  13465. *
  13466. * @return {Element}
  13467. * The element that gets created.
  13468. */
  13469. createEl() {
  13470. return super.createEl('div', {
  13471. className: this.buildWrapperCSSClass()
  13472. }, {});
  13473. }
  13474. /**
  13475. * Allow sub components to stack CSS class names for the wrapper element
  13476. *
  13477. * @return {string}
  13478. * The constructed wrapper DOM `className`
  13479. */
  13480. buildWrapperCSSClass() {
  13481. let menuButtonClass = 'vjs-menu-button';
  13482. // If the inline option is passed, we want to use different styles altogether.
  13483. if (this.options_.inline === true) {
  13484. menuButtonClass += '-inline';
  13485. } else {
  13486. menuButtonClass += '-popup';
  13487. }
  13488. // TODO: Fix the CSS so that this isn't necessary
  13489. const buttonClass = Button.prototype.buildCSSClass();
  13490. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  13491. }
  13492. /**
  13493. * Builds the default DOM `className`.
  13494. *
  13495. * @return {string}
  13496. * The DOM `className` for this object.
  13497. */
  13498. buildCSSClass() {
  13499. let menuButtonClass = 'vjs-menu-button';
  13500. // If the inline option is passed, we want to use different styles altogether.
  13501. if (this.options_.inline === true) {
  13502. menuButtonClass += '-inline';
  13503. } else {
  13504. menuButtonClass += '-popup';
  13505. }
  13506. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  13507. }
  13508. /**
  13509. * Get or set the localized control text that will be used for accessibility.
  13510. *
  13511. * > NOTE: This will come from the internal `menuButton_` element.
  13512. *
  13513. * @param {string} [text]
  13514. * Control text for element.
  13515. *
  13516. * @param {Element} [el=this.menuButton_.el()]
  13517. * Element to set the title on.
  13518. *
  13519. * @return {string}
  13520. * - The control text when getting
  13521. */
  13522. controlText(text, el = this.menuButton_.el()) {
  13523. return this.menuButton_.controlText(text, el);
  13524. }
  13525. /**
  13526. * Dispose of the `menu-button` and all child components.
  13527. */
  13528. dispose() {
  13529. this.handleMouseLeave();
  13530. super.dispose();
  13531. }
  13532. /**
  13533. * Handle a click on a `MenuButton`.
  13534. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13535. *
  13536. * @param {Event} event
  13537. * The `keydown`, `tap`, or `click` event that caused this function to be
  13538. * called.
  13539. *
  13540. * @listens tap
  13541. * @listens click
  13542. */
  13543. handleClick(event) {
  13544. if (this.buttonPressed_) {
  13545. this.unpressButton();
  13546. } else {
  13547. this.pressButton();
  13548. }
  13549. }
  13550. /**
  13551. * Handle `mouseleave` for `MenuButton`.
  13552. *
  13553. * @param {Event} event
  13554. * The `mouseleave` event that caused this function to be called.
  13555. *
  13556. * @listens mouseleave
  13557. */
  13558. handleMouseLeave(event) {
  13559. this.removeClass('vjs-hover');
  13560. off(document, 'keyup', this.handleMenuKeyUp_);
  13561. }
  13562. /**
  13563. * Set the focus to the actual button, not to this element
  13564. */
  13565. focus() {
  13566. this.menuButton_.focus();
  13567. }
  13568. /**
  13569. * Remove the focus from the actual button, not this element
  13570. */
  13571. blur() {
  13572. this.menuButton_.blur();
  13573. }
  13574. /**
  13575. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  13576. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13577. *
  13578. * @param {Event} event
  13579. * The `keydown` event that caused this function to be called.
  13580. *
  13581. * @listens keydown
  13582. */
  13583. handleKeyDown(event) {
  13584. // Escape or Tab unpress the 'button'
  13585. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13586. if (this.buttonPressed_) {
  13587. this.unpressButton();
  13588. }
  13589. // Don't preventDefault for Tab key - we still want to lose focus
  13590. if (!keycode.isEventKey(event, 'Tab')) {
  13591. event.preventDefault();
  13592. // Set focus back to the menu button's button
  13593. this.menuButton_.focus();
  13594. }
  13595. // Up Arrow or Down Arrow also 'press' the button to open the menu
  13596. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  13597. if (!this.buttonPressed_) {
  13598. event.preventDefault();
  13599. this.pressButton();
  13600. }
  13601. }
  13602. }
  13603. /**
  13604. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  13605. * the constructor.
  13606. *
  13607. * @param {Event} event
  13608. * Key press event
  13609. *
  13610. * @listens keyup
  13611. */
  13612. handleMenuKeyUp(event) {
  13613. // Escape hides popup menu
  13614. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13615. this.removeClass('vjs-hover');
  13616. }
  13617. }
  13618. /**
  13619. * This method name now delegates to `handleSubmenuKeyDown`. This means
  13620. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  13621. * stop working.
  13622. *
  13623. * @param {Event} event
  13624. * The event that caused this function to be called.
  13625. */
  13626. handleSubmenuKeyPress(event) {
  13627. this.handleSubmenuKeyDown(event);
  13628. }
  13629. /**
  13630. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  13631. * the constructor.
  13632. *
  13633. * @param {Event} event
  13634. * Key press event
  13635. *
  13636. * @listens keydown
  13637. */
  13638. handleSubmenuKeyDown(event) {
  13639. // Escape or Tab unpress the 'button'
  13640. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  13641. if (this.buttonPressed_) {
  13642. this.unpressButton();
  13643. }
  13644. // Don't preventDefault for Tab key - we still want to lose focus
  13645. if (!keycode.isEventKey(event, 'Tab')) {
  13646. event.preventDefault();
  13647. // Set focus back to the menu button's button
  13648. this.menuButton_.focus();
  13649. }
  13650. }
  13651. }
  13652. /**
  13653. * Put the current `MenuButton` into a pressed state.
  13654. */
  13655. pressButton() {
  13656. if (this.enabled_) {
  13657. this.buttonPressed_ = true;
  13658. this.menu.show();
  13659. this.menu.lockShowing();
  13660. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  13661. // set the focus into the submenu, except on iOS where it is resulting in
  13662. // undesired scrolling behavior when the player is in an iframe
  13663. if (IS_IOS && isInFrame()) {
  13664. // Return early so that the menu isn't focused
  13665. return;
  13666. }
  13667. this.menu.focus();
  13668. }
  13669. }
  13670. /**
  13671. * Take the current `MenuButton` out of a pressed state.
  13672. */
  13673. unpressButton() {
  13674. if (this.enabled_) {
  13675. this.buttonPressed_ = false;
  13676. this.menu.unlockShowing();
  13677. this.menu.hide();
  13678. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13679. }
  13680. }
  13681. /**
  13682. * Disable the `MenuButton`. Don't allow it to be clicked.
  13683. */
  13684. disable() {
  13685. this.unpressButton();
  13686. this.enabled_ = false;
  13687. this.addClass('vjs-disabled');
  13688. this.menuButton_.disable();
  13689. }
  13690. /**
  13691. * Enable the `MenuButton`. Allow it to be clicked.
  13692. */
  13693. enable() {
  13694. this.enabled_ = true;
  13695. this.removeClass('vjs-disabled');
  13696. this.menuButton_.enable();
  13697. }
  13698. }
  13699. Component.registerComponent('MenuButton', MenuButton);
  13700. /**
  13701. * @file track-button.js
  13702. */
  13703. /**
  13704. * The base class for buttons that toggle specific track types (e.g. subtitles).
  13705. *
  13706. * @extends MenuButton
  13707. */
  13708. class TrackButton extends MenuButton {
  13709. /**
  13710. * Creates an instance of this class.
  13711. *
  13712. * @param { import('./player').default } player
  13713. * The `Player` that this class should be attached to.
  13714. *
  13715. * @param {Object} [options]
  13716. * The key/value store of player options.
  13717. */
  13718. constructor(player, options) {
  13719. const tracks = options.tracks;
  13720. super(player, options);
  13721. if (this.items.length <= 1) {
  13722. this.hide();
  13723. }
  13724. if (!tracks) {
  13725. return;
  13726. }
  13727. const updateHandler = bind_(this, this.update);
  13728. tracks.addEventListener('removetrack', updateHandler);
  13729. tracks.addEventListener('addtrack', updateHandler);
  13730. tracks.addEventListener('labelchange', updateHandler);
  13731. this.player_.on('ready', updateHandler);
  13732. this.player_.on('dispose', function () {
  13733. tracks.removeEventListener('removetrack', updateHandler);
  13734. tracks.removeEventListener('addtrack', updateHandler);
  13735. tracks.removeEventListener('labelchange', updateHandler);
  13736. });
  13737. }
  13738. }
  13739. Component.registerComponent('TrackButton', TrackButton);
  13740. /**
  13741. * @file menu-keys.js
  13742. */
  13743. /**
  13744. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  13745. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  13746. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  13747. *
  13748. * @typedef MenuKeys
  13749. * @array
  13750. */
  13751. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  13752. /**
  13753. * @file menu-item.js
  13754. */
  13755. /**
  13756. * The component for a menu item. `<li>`
  13757. *
  13758. * @extends ClickableComponent
  13759. */
  13760. class MenuItem extends ClickableComponent {
  13761. /**
  13762. * Creates an instance of the this class.
  13763. *
  13764. * @param { import('../player').default } player
  13765. * The `Player` that this class should be attached to.
  13766. *
  13767. * @param {Object} [options={}]
  13768. * The key/value store of player options.
  13769. *
  13770. */
  13771. constructor(player, options) {
  13772. super(player, options);
  13773. this.selectable = options.selectable;
  13774. this.isSelected_ = options.selected || false;
  13775. this.multiSelectable = options.multiSelectable;
  13776. this.selected(this.isSelected_);
  13777. if (this.selectable) {
  13778. if (this.multiSelectable) {
  13779. this.el_.setAttribute('role', 'menuitemcheckbox');
  13780. } else {
  13781. this.el_.setAttribute('role', 'menuitemradio');
  13782. }
  13783. } else {
  13784. this.el_.setAttribute('role', 'menuitem');
  13785. }
  13786. }
  13787. /**
  13788. * Create the `MenuItem's DOM element
  13789. *
  13790. * @param {string} [type=li]
  13791. * Element's node type, not actually used, always set to `li`.
  13792. *
  13793. * @param {Object} [props={}]
  13794. * An object of properties that should be set on the element
  13795. *
  13796. * @param {Object} [attrs={}]
  13797. * An object of attributes that should be set on the element
  13798. *
  13799. * @return {Element}
  13800. * The element that gets created.
  13801. */
  13802. createEl(type, props, attrs) {
  13803. // The control is textual, not just an icon
  13804. this.nonIconControl = true;
  13805. const el = super.createEl('li', Object.assign({
  13806. className: 'vjs-menu-item',
  13807. tabIndex: -1
  13808. }, props), attrs);
  13809. // swap icon with menu item text.
  13810. el.replaceChild(createEl('span', {
  13811. className: 'vjs-menu-item-text',
  13812. textContent: this.localize(this.options_.label)
  13813. }), el.querySelector('.vjs-icon-placeholder'));
  13814. return el;
  13815. }
  13816. /**
  13817. * Ignore keys which are used by the menu, but pass any other ones up. See
  13818. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13819. *
  13820. * @param {Event} event
  13821. * The `keydown` event that caused this function to be called.
  13822. *
  13823. * @listens keydown
  13824. */
  13825. handleKeyDown(event) {
  13826. if (!MenuKeys.some(key => keycode.isEventKey(event, key))) {
  13827. // Pass keydown handling up for unused keys
  13828. super.handleKeyDown(event);
  13829. }
  13830. }
  13831. /**
  13832. * Any click on a `MenuItem` puts it into the selected state.
  13833. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13834. *
  13835. * @param {Event} event
  13836. * The `keydown`, `tap`, or `click` event that caused this function to be
  13837. * called.
  13838. *
  13839. * @listens tap
  13840. * @listens click
  13841. */
  13842. handleClick(event) {
  13843. this.selected(true);
  13844. }
  13845. /**
  13846. * Set the state for this menu item as selected or not.
  13847. *
  13848. * @param {boolean} selected
  13849. * if the menu item is selected or not
  13850. */
  13851. selected(selected) {
  13852. if (this.selectable) {
  13853. if (selected) {
  13854. this.addClass('vjs-selected');
  13855. this.el_.setAttribute('aria-checked', 'true');
  13856. // aria-checked isn't fully supported by browsers/screen readers,
  13857. // so indicate selected state to screen reader in the control text.
  13858. this.controlText(', selected');
  13859. this.isSelected_ = true;
  13860. } else {
  13861. this.removeClass('vjs-selected');
  13862. this.el_.setAttribute('aria-checked', 'false');
  13863. // Indicate un-selected state to screen reader
  13864. this.controlText('');
  13865. this.isSelected_ = false;
  13866. }
  13867. }
  13868. }
  13869. }
  13870. Component.registerComponent('MenuItem', MenuItem);
  13871. /**
  13872. * @file text-track-menu-item.js
  13873. */
  13874. /**
  13875. * The specific menu item type for selecting a language within a text track kind
  13876. *
  13877. * @extends MenuItem
  13878. */
  13879. class TextTrackMenuItem extends MenuItem {
  13880. /**
  13881. * Creates an instance of this class.
  13882. *
  13883. * @param { import('../../player').default } player
  13884. * The `Player` that this class should be attached to.
  13885. *
  13886. * @param {Object} [options]
  13887. * The key/value store of player options.
  13888. */
  13889. constructor(player, options) {
  13890. const track = options.track;
  13891. const tracks = player.textTracks();
  13892. // Modify options for parent MenuItem class's init.
  13893. options.label = track.label || track.language || 'Unknown';
  13894. options.selected = track.mode === 'showing';
  13895. super(player, options);
  13896. this.track = track;
  13897. // Determine the relevant kind(s) of tracks for this component and filter
  13898. // out empty kinds.
  13899. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  13900. const changeHandler = (...args) => {
  13901. this.handleTracksChange.apply(this, args);
  13902. };
  13903. const selectedLanguageChangeHandler = (...args) => {
  13904. this.handleSelectedLanguageChange.apply(this, args);
  13905. };
  13906. player.on(['loadstart', 'texttrackchange'], changeHandler);
  13907. tracks.addEventListener('change', changeHandler);
  13908. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13909. this.on('dispose', function () {
  13910. player.off(['loadstart', 'texttrackchange'], changeHandler);
  13911. tracks.removeEventListener('change', changeHandler);
  13912. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13913. });
  13914. // iOS7 doesn't dispatch change events to TextTrackLists when an
  13915. // associated track's mode changes. Without something like
  13916. // Object.observe() (also not present on iOS7), it's not
  13917. // possible to detect changes to the mode attribute and polyfill
  13918. // the change event. As a poor substitute, we manually dispatch
  13919. // change events whenever the controls modify the mode.
  13920. if (tracks.onchange === undefined) {
  13921. let event;
  13922. this.on(['tap', 'click'], function () {
  13923. if (typeof window.Event !== 'object') {
  13924. // Android 2.3 throws an Illegal Constructor error for window.Event
  13925. try {
  13926. event = new window.Event('change');
  13927. } catch (err) {
  13928. // continue regardless of error
  13929. }
  13930. }
  13931. if (!event) {
  13932. event = document.createEvent('Event');
  13933. event.initEvent('change', true, true);
  13934. }
  13935. tracks.dispatchEvent(event);
  13936. });
  13937. }
  13938. // set the default state based on current tracks
  13939. this.handleTracksChange();
  13940. }
  13941. /**
  13942. * This gets called when an `TextTrackMenuItem` is "clicked". See
  13943. * {@link ClickableComponent} for more detailed information on what a click can be.
  13944. *
  13945. * @param {Event} event
  13946. * The `keydown`, `tap`, or `click` event that caused this function to be
  13947. * called.
  13948. *
  13949. * @listens tap
  13950. * @listens click
  13951. */
  13952. handleClick(event) {
  13953. const referenceTrack = this.track;
  13954. const tracks = this.player_.textTracks();
  13955. super.handleClick(event);
  13956. if (!tracks) {
  13957. return;
  13958. }
  13959. for (let i = 0; i < tracks.length; i++) {
  13960. const track = tracks[i];
  13961. // If the track from the text tracks list is not of the right kind,
  13962. // skip it. We do not want to affect tracks of incompatible kind(s).
  13963. if (this.kinds.indexOf(track.kind) === -1) {
  13964. continue;
  13965. }
  13966. // If this text track is the component's track and it is not showing,
  13967. // set it to showing.
  13968. if (track === referenceTrack) {
  13969. if (track.mode !== 'showing') {
  13970. track.mode = 'showing';
  13971. }
  13972. // If this text track is not the component's track and it is not
  13973. // disabled, set it to disabled.
  13974. } else if (track.mode !== 'disabled') {
  13975. track.mode = 'disabled';
  13976. }
  13977. }
  13978. }
  13979. /**
  13980. * Handle text track list change
  13981. *
  13982. * @param {Event} event
  13983. * The `change` event that caused this function to be called.
  13984. *
  13985. * @listens TextTrackList#change
  13986. */
  13987. handleTracksChange(event) {
  13988. const shouldBeSelected = this.track.mode === 'showing';
  13989. // Prevent redundant selected() calls because they may cause
  13990. // screen readers to read the appended control text unnecessarily
  13991. if (shouldBeSelected !== this.isSelected_) {
  13992. this.selected(shouldBeSelected);
  13993. }
  13994. }
  13995. handleSelectedLanguageChange(event) {
  13996. if (this.track.mode === 'showing') {
  13997. const selectedLanguage = this.player_.cache_.selectedLanguage;
  13998. // Don't replace the kind of track across the same language
  13999. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14000. return;
  14001. }
  14002. this.player_.cache_.selectedLanguage = {
  14003. enabled: true,
  14004. language: this.track.language,
  14005. kind: this.track.kind
  14006. };
  14007. }
  14008. }
  14009. dispose() {
  14010. // remove reference to track object on dispose
  14011. this.track = null;
  14012. super.dispose();
  14013. }
  14014. }
  14015. Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14016. /**
  14017. * @file off-text-track-menu-item.js
  14018. */
  14019. /**
  14020. * A special menu item for turning of a specific type of text track
  14021. *
  14022. * @extends TextTrackMenuItem
  14023. */
  14024. class OffTextTrackMenuItem extends TextTrackMenuItem {
  14025. /**
  14026. * Creates an instance of this class.
  14027. *
  14028. * @param { import('../../player').default } player
  14029. * The `Player` that this class should be attached to.
  14030. *
  14031. * @param {Object} [options]
  14032. * The key/value store of player options.
  14033. */
  14034. constructor(player, options) {
  14035. // Create pseudo track info
  14036. // Requires options['kind']
  14037. options.track = {
  14038. player,
  14039. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14040. // since they are now stored in the `kinds` property of all instances of
  14041. // TextTrackMenuItem, but this will remain for backwards compatibility
  14042. kind: options.kind,
  14043. kinds: options.kinds,
  14044. default: false,
  14045. mode: 'disabled'
  14046. };
  14047. if (!options.kinds) {
  14048. options.kinds = [options.kind];
  14049. }
  14050. if (options.label) {
  14051. options.track.label = options.label;
  14052. } else {
  14053. options.track.label = options.kinds.join(' and ') + ' off';
  14054. }
  14055. // MenuItem is selectable
  14056. options.selectable = true;
  14057. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14058. options.multiSelectable = false;
  14059. super(player, options);
  14060. }
  14061. /**
  14062. * Handle text track change
  14063. *
  14064. * @param {Event} event
  14065. * The event that caused this function to run
  14066. */
  14067. handleTracksChange(event) {
  14068. const tracks = this.player().textTracks();
  14069. let shouldBeSelected = true;
  14070. for (let i = 0, l = tracks.length; i < l; i++) {
  14071. const track = tracks[i];
  14072. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14073. shouldBeSelected = false;
  14074. break;
  14075. }
  14076. }
  14077. // Prevent redundant selected() calls because they may cause
  14078. // screen readers to read the appended control text unnecessarily
  14079. if (shouldBeSelected !== this.isSelected_) {
  14080. this.selected(shouldBeSelected);
  14081. }
  14082. }
  14083. handleSelectedLanguageChange(event) {
  14084. const tracks = this.player().textTracks();
  14085. let allHidden = true;
  14086. for (let i = 0, l = tracks.length; i < l; i++) {
  14087. const track = tracks[i];
  14088. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14089. allHidden = false;
  14090. break;
  14091. }
  14092. }
  14093. if (allHidden) {
  14094. this.player_.cache_.selectedLanguage = {
  14095. enabled: false
  14096. };
  14097. }
  14098. }
  14099. /**
  14100. * Update control text and label on languagechange
  14101. */
  14102. handleLanguagechange() {
  14103. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  14104. super.handleLanguagechange();
  14105. }
  14106. }
  14107. Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14108. /**
  14109. * @file text-track-button.js
  14110. */
  14111. /**
  14112. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14113. *
  14114. * @extends MenuButton
  14115. */
  14116. class TextTrackButton extends TrackButton {
  14117. /**
  14118. * Creates an instance of this class.
  14119. *
  14120. * @param { import('../../player').default } player
  14121. * The `Player` that this class should be attached to.
  14122. *
  14123. * @param {Object} [options={}]
  14124. * The key/value store of player options.
  14125. */
  14126. constructor(player, options = {}) {
  14127. options.tracks = player.textTracks();
  14128. super(player, options);
  14129. }
  14130. /**
  14131. * Create a menu item for each text track
  14132. *
  14133. * @param {TextTrackMenuItem[]} [items=[]]
  14134. * Existing array of items to use during creation
  14135. *
  14136. * @return {TextTrackMenuItem[]}
  14137. * Array of menu items that were created
  14138. */
  14139. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  14140. // Label is an override for the [track] off label
  14141. // USed to localise captions/subtitles
  14142. let label;
  14143. if (this.label_) {
  14144. label = `${this.label_} off`;
  14145. }
  14146. // Add an OFF menu item to turn all tracks off
  14147. items.push(new OffTextTrackMenuItem(this.player_, {
  14148. kinds: this.kinds_,
  14149. kind: this.kind_,
  14150. label
  14151. }));
  14152. this.hideThreshold_ += 1;
  14153. const tracks = this.player_.textTracks();
  14154. if (!Array.isArray(this.kinds_)) {
  14155. this.kinds_ = [this.kind_];
  14156. }
  14157. for (let i = 0; i < tracks.length; i++) {
  14158. const track = tracks[i];
  14159. // only add tracks that are of an appropriate kind and have a label
  14160. if (this.kinds_.indexOf(track.kind) > -1) {
  14161. const item = new TrackMenuItem(this.player_, {
  14162. track,
  14163. kinds: this.kinds_,
  14164. kind: this.kind_,
  14165. // MenuItem is selectable
  14166. selectable: true,
  14167. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14168. multiSelectable: false
  14169. });
  14170. item.addClass(`vjs-${track.kind}-menu-item`);
  14171. items.push(item);
  14172. }
  14173. }
  14174. return items;
  14175. }
  14176. }
  14177. Component.registerComponent('TextTrackButton', TextTrackButton);
  14178. /**
  14179. * @file chapters-track-menu-item.js
  14180. */
  14181. /**
  14182. * The chapter track menu item
  14183. *
  14184. * @extends MenuItem
  14185. */
  14186. class ChaptersTrackMenuItem extends MenuItem {
  14187. /**
  14188. * Creates an instance of this class.
  14189. *
  14190. * @param { import('../../player').default } player
  14191. * The `Player` that this class should be attached to.
  14192. *
  14193. * @param {Object} [options]
  14194. * The key/value store of player options.
  14195. */
  14196. constructor(player, options) {
  14197. const track = options.track;
  14198. const cue = options.cue;
  14199. const currentTime = player.currentTime();
  14200. // Modify options for parent MenuItem class's init.
  14201. options.selectable = true;
  14202. options.multiSelectable = false;
  14203. options.label = cue.text;
  14204. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  14205. super(player, options);
  14206. this.track = track;
  14207. this.cue = cue;
  14208. }
  14209. /**
  14210. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  14211. * {@link ClickableComponent} for more detailed information on what a click can be.
  14212. *
  14213. * @param {Event} [event]
  14214. * The `keydown`, `tap`, or `click` event that caused this function to be
  14215. * called.
  14216. *
  14217. * @listens tap
  14218. * @listens click
  14219. */
  14220. handleClick(event) {
  14221. super.handleClick();
  14222. this.player_.currentTime(this.cue.startTime);
  14223. }
  14224. }
  14225. Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  14226. /**
  14227. * @file chapters-button.js
  14228. */
  14229. /**
  14230. * The button component for toggling and selecting chapters
  14231. * Chapters act much differently than other text tracks
  14232. * Cues are navigation vs. other tracks of alternative languages
  14233. *
  14234. * @extends TextTrackButton
  14235. */
  14236. class ChaptersButton extends TextTrackButton {
  14237. /**
  14238. * Creates an instance of this class.
  14239. *
  14240. * @param { import('../../player').default } player
  14241. * The `Player` that this class should be attached to.
  14242. *
  14243. * @param {Object} [options]
  14244. * The key/value store of player options.
  14245. *
  14246. * @param {Function} [ready]
  14247. * The function to call when this function is ready.
  14248. */
  14249. constructor(player, options, ready) {
  14250. super(player, options, ready);
  14251. this.selectCurrentItem_ = () => {
  14252. this.items.forEach(item => {
  14253. item.selected(this.track_.activeCues[0] === item.cue);
  14254. });
  14255. };
  14256. }
  14257. /**
  14258. * Builds the default DOM `className`.
  14259. *
  14260. * @return {string}
  14261. * The DOM `className` for this object.
  14262. */
  14263. buildCSSClass() {
  14264. return `vjs-chapters-button ${super.buildCSSClass()}`;
  14265. }
  14266. buildWrapperCSSClass() {
  14267. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  14268. }
  14269. /**
  14270. * Update the menu based on the current state of its items.
  14271. *
  14272. * @param {Event} [event]
  14273. * An event that triggered this function to run.
  14274. *
  14275. * @listens TextTrackList#addtrack
  14276. * @listens TextTrackList#removetrack
  14277. * @listens TextTrackList#change
  14278. */
  14279. update(event) {
  14280. if (event && event.track && event.track.kind !== 'chapters') {
  14281. return;
  14282. }
  14283. const track = this.findChaptersTrack();
  14284. if (track !== this.track_) {
  14285. this.setTrack(track);
  14286. super.update();
  14287. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  14288. // Update the menu initially or if the number of cues has changed since set
  14289. super.update();
  14290. }
  14291. }
  14292. /**
  14293. * Set the currently selected track for the chapters button.
  14294. *
  14295. * @param {TextTrack} track
  14296. * The new track to select. Nothing will change if this is the currently selected
  14297. * track.
  14298. */
  14299. setTrack(track) {
  14300. if (this.track_ === track) {
  14301. return;
  14302. }
  14303. if (!this.updateHandler_) {
  14304. this.updateHandler_ = this.update.bind(this);
  14305. }
  14306. // here this.track_ refers to the old track instance
  14307. if (this.track_) {
  14308. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14309. if (remoteTextTrackEl) {
  14310. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  14311. }
  14312. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  14313. this.track_ = null;
  14314. }
  14315. this.track_ = track;
  14316. // here this.track_ refers to the new track instance
  14317. if (this.track_) {
  14318. this.track_.mode = 'hidden';
  14319. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14320. if (remoteTextTrackEl) {
  14321. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  14322. }
  14323. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  14324. }
  14325. }
  14326. /**
  14327. * Find the track object that is currently in use by this ChaptersButton
  14328. *
  14329. * @return {TextTrack|undefined}
  14330. * The current track or undefined if none was found.
  14331. */
  14332. findChaptersTrack() {
  14333. const tracks = this.player_.textTracks() || [];
  14334. for (let i = tracks.length - 1; i >= 0; i--) {
  14335. // We will always choose the last track as our chaptersTrack
  14336. const track = tracks[i];
  14337. if (track.kind === this.kind_) {
  14338. return track;
  14339. }
  14340. }
  14341. }
  14342. /**
  14343. * Get the caption for the ChaptersButton based on the track label. This will also
  14344. * use the current tracks localized kind as a fallback if a label does not exist.
  14345. *
  14346. * @return {string}
  14347. * The tracks current label or the localized track kind.
  14348. */
  14349. getMenuCaption() {
  14350. if (this.track_ && this.track_.label) {
  14351. return this.track_.label;
  14352. }
  14353. return this.localize(toTitleCase(this.kind_));
  14354. }
  14355. /**
  14356. * Create menu from chapter track
  14357. *
  14358. * @return { import('../../menu/menu').default }
  14359. * New menu for the chapter buttons
  14360. */
  14361. createMenu() {
  14362. this.options_.title = this.getMenuCaption();
  14363. return super.createMenu();
  14364. }
  14365. /**
  14366. * Create a menu item for each text track
  14367. *
  14368. * @return { import('./text-track-menu-item').default[] }
  14369. * Array of menu items
  14370. */
  14371. createItems() {
  14372. const items = [];
  14373. if (!this.track_) {
  14374. return items;
  14375. }
  14376. const cues = this.track_.cues;
  14377. if (!cues) {
  14378. return items;
  14379. }
  14380. for (let i = 0, l = cues.length; i < l; i++) {
  14381. const cue = cues[i];
  14382. const mi = new ChaptersTrackMenuItem(this.player_, {
  14383. track: this.track_,
  14384. cue
  14385. });
  14386. items.push(mi);
  14387. }
  14388. return items;
  14389. }
  14390. }
  14391. /**
  14392. * `kind` of TextTrack to look for to associate it with this menu.
  14393. *
  14394. * @type {string}
  14395. * @private
  14396. */
  14397. ChaptersButton.prototype.kind_ = 'chapters';
  14398. /**
  14399. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  14400. *
  14401. * @type {string}
  14402. * @protected
  14403. */
  14404. ChaptersButton.prototype.controlText_ = 'Chapters';
  14405. Component.registerComponent('ChaptersButton', ChaptersButton);
  14406. /**
  14407. * @file descriptions-button.js
  14408. */
  14409. /**
  14410. * The button component for toggling and selecting descriptions
  14411. *
  14412. * @extends TextTrackButton
  14413. */
  14414. class DescriptionsButton extends TextTrackButton {
  14415. /**
  14416. * Creates an instance of this class.
  14417. *
  14418. * @param { import('../../player').default } player
  14419. * The `Player` that this class should be attached to.
  14420. *
  14421. * @param {Object} [options]
  14422. * The key/value store of player options.
  14423. *
  14424. * @param {Function} [ready]
  14425. * The function to call when this component is ready.
  14426. */
  14427. constructor(player, options, ready) {
  14428. super(player, options, ready);
  14429. const tracks = player.textTracks();
  14430. const changeHandler = bind_(this, this.handleTracksChange);
  14431. tracks.addEventListener('change', changeHandler);
  14432. this.on('dispose', function () {
  14433. tracks.removeEventListener('change', changeHandler);
  14434. });
  14435. }
  14436. /**
  14437. * Handle text track change
  14438. *
  14439. * @param {Event} event
  14440. * The event that caused this function to run
  14441. *
  14442. * @listens TextTrackList#change
  14443. */
  14444. handleTracksChange(event) {
  14445. const tracks = this.player().textTracks();
  14446. let disabled = false;
  14447. // Check whether a track of a different kind is showing
  14448. for (let i = 0, l = tracks.length; i < l; i++) {
  14449. const track = tracks[i];
  14450. if (track.kind !== this.kind_ && track.mode === 'showing') {
  14451. disabled = true;
  14452. break;
  14453. }
  14454. }
  14455. // If another track is showing, disable this menu button
  14456. if (disabled) {
  14457. this.disable();
  14458. } else {
  14459. this.enable();
  14460. }
  14461. }
  14462. /**
  14463. * Builds the default DOM `className`.
  14464. *
  14465. * @return {string}
  14466. * The DOM `className` for this object.
  14467. */
  14468. buildCSSClass() {
  14469. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  14470. }
  14471. buildWrapperCSSClass() {
  14472. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  14473. }
  14474. }
  14475. /**
  14476. * `kind` of TextTrack to look for to associate it with this menu.
  14477. *
  14478. * @type {string}
  14479. * @private
  14480. */
  14481. DescriptionsButton.prototype.kind_ = 'descriptions';
  14482. /**
  14483. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  14484. *
  14485. * @type {string}
  14486. * @protected
  14487. */
  14488. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  14489. Component.registerComponent('DescriptionsButton', DescriptionsButton);
  14490. /**
  14491. * @file subtitles-button.js
  14492. */
  14493. /**
  14494. * The button component for toggling and selecting subtitles
  14495. *
  14496. * @extends TextTrackButton
  14497. */
  14498. class SubtitlesButton extends TextTrackButton {
  14499. /**
  14500. * Creates an instance of this class.
  14501. *
  14502. * @param { import('../../player').default } player
  14503. * The `Player` that this class should be attached to.
  14504. *
  14505. * @param {Object} [options]
  14506. * The key/value store of player options.
  14507. *
  14508. * @param {Function} [ready]
  14509. * The function to call when this component is ready.
  14510. */
  14511. constructor(player, options, ready) {
  14512. super(player, options, ready);
  14513. }
  14514. /**
  14515. * Builds the default DOM `className`.
  14516. *
  14517. * @return {string}
  14518. * The DOM `className` for this object.
  14519. */
  14520. buildCSSClass() {
  14521. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  14522. }
  14523. buildWrapperCSSClass() {
  14524. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  14525. }
  14526. }
  14527. /**
  14528. * `kind` of TextTrack to look for to associate it with this menu.
  14529. *
  14530. * @type {string}
  14531. * @private
  14532. */
  14533. SubtitlesButton.prototype.kind_ = 'subtitles';
  14534. /**
  14535. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  14536. *
  14537. * @type {string}
  14538. * @protected
  14539. */
  14540. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  14541. Component.registerComponent('SubtitlesButton', SubtitlesButton);
  14542. /**
  14543. * @file caption-settings-menu-item.js
  14544. */
  14545. /**
  14546. * The menu item for caption track settings menu
  14547. *
  14548. * @extends TextTrackMenuItem
  14549. */
  14550. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  14551. /**
  14552. * Creates an instance of this class.
  14553. *
  14554. * @param { import('../../player').default } player
  14555. * The `Player` that this class should be attached to.
  14556. *
  14557. * @param {Object} [options]
  14558. * The key/value store of player options.
  14559. */
  14560. constructor(player, options) {
  14561. options.track = {
  14562. player,
  14563. kind: options.kind,
  14564. label: options.kind + ' settings',
  14565. selectable: false,
  14566. default: false,
  14567. mode: 'disabled'
  14568. };
  14569. // CaptionSettingsMenuItem has no concept of 'selected'
  14570. options.selectable = false;
  14571. options.name = 'CaptionSettingsMenuItem';
  14572. super(player, options);
  14573. this.addClass('vjs-texttrack-settings');
  14574. this.controlText(', opens ' + options.kind + ' settings dialog');
  14575. }
  14576. /**
  14577. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  14578. * {@link ClickableComponent} for more detailed information on what a click can be.
  14579. *
  14580. * @param {Event} [event]
  14581. * The `keydown`, `tap`, or `click` event that caused this function to be
  14582. * called.
  14583. *
  14584. * @listens tap
  14585. * @listens click
  14586. */
  14587. handleClick(event) {
  14588. this.player().getChild('textTrackSettings').open();
  14589. }
  14590. /**
  14591. * Update control text and label on languagechange
  14592. */
  14593. handleLanguagechange() {
  14594. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  14595. super.handleLanguagechange();
  14596. }
  14597. }
  14598. Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  14599. /**
  14600. * @file captions-button.js
  14601. */
  14602. /**
  14603. * The button component for toggling and selecting captions
  14604. *
  14605. * @extends TextTrackButton
  14606. */
  14607. class CaptionsButton extends TextTrackButton {
  14608. /**
  14609. * Creates an instance of this class.
  14610. *
  14611. * @param { import('../../player').default } player
  14612. * The `Player` that this class should be attached to.
  14613. *
  14614. * @param {Object} [options]
  14615. * The key/value store of player options.
  14616. *
  14617. * @param {Function} [ready]
  14618. * The function to call when this component is ready.
  14619. */
  14620. constructor(player, options, ready) {
  14621. super(player, options, ready);
  14622. }
  14623. /**
  14624. * Builds the default DOM `className`.
  14625. *
  14626. * @return {string}
  14627. * The DOM `className` for this object.
  14628. */
  14629. buildCSSClass() {
  14630. return `vjs-captions-button ${super.buildCSSClass()}`;
  14631. }
  14632. buildWrapperCSSClass() {
  14633. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  14634. }
  14635. /**
  14636. * Create caption menu items
  14637. *
  14638. * @return {CaptionSettingsMenuItem[]}
  14639. * The array of current menu items.
  14640. */
  14641. createItems() {
  14642. const items = [];
  14643. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14644. items.push(new CaptionSettingsMenuItem(this.player_, {
  14645. kind: this.kind_
  14646. }));
  14647. this.hideThreshold_ += 1;
  14648. }
  14649. return super.createItems(items);
  14650. }
  14651. }
  14652. /**
  14653. * `kind` of TextTrack to look for to associate it with this menu.
  14654. *
  14655. * @type {string}
  14656. * @private
  14657. */
  14658. CaptionsButton.prototype.kind_ = 'captions';
  14659. /**
  14660. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  14661. *
  14662. * @type {string}
  14663. * @protected
  14664. */
  14665. CaptionsButton.prototype.controlText_ = 'Captions';
  14666. Component.registerComponent('CaptionsButton', CaptionsButton);
  14667. /**
  14668. * @file subs-caps-menu-item.js
  14669. */
  14670. /**
  14671. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  14672. * in the SubsCapsMenu.
  14673. *
  14674. * @extends TextTrackMenuItem
  14675. */
  14676. class SubsCapsMenuItem extends TextTrackMenuItem {
  14677. createEl(type, props, attrs) {
  14678. const el = super.createEl(type, props, attrs);
  14679. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14680. if (this.options_.track.kind === 'captions') {
  14681. parentSpan.appendChild(createEl('span', {
  14682. className: 'vjs-icon-placeholder'
  14683. }, {
  14684. 'aria-hidden': true
  14685. }));
  14686. parentSpan.appendChild(createEl('span', {
  14687. className: 'vjs-control-text',
  14688. // space added as the text will visually flow with the
  14689. // label
  14690. textContent: ` ${this.localize('Captions')}`
  14691. }));
  14692. }
  14693. return el;
  14694. }
  14695. }
  14696. Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  14697. /**
  14698. * @file sub-caps-button.js
  14699. */
  14700. /**
  14701. * The button component for toggling and selecting captions and/or subtitles
  14702. *
  14703. * @extends TextTrackButton
  14704. */
  14705. class SubsCapsButton extends TextTrackButton {
  14706. /**
  14707. * Creates an instance of this class.
  14708. *
  14709. * @param { import('../../player').default } player
  14710. * The `Player` that this class should be attached to.
  14711. *
  14712. * @param {Object} [options]
  14713. * The key/value store of player options.
  14714. *
  14715. * @param {Function} [ready]
  14716. * The function to call when this component is ready.
  14717. */
  14718. constructor(player, options = {}) {
  14719. super(player, options);
  14720. // Although North America uses "captions" in most cases for
  14721. // "captions and subtitles" other locales use "subtitles"
  14722. this.label_ = 'subtitles';
  14723. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  14724. this.label_ = 'captions';
  14725. }
  14726. this.menuButton_.controlText(toTitleCase(this.label_));
  14727. }
  14728. /**
  14729. * Builds the default DOM `className`.
  14730. *
  14731. * @return {string}
  14732. * The DOM `className` for this object.
  14733. */
  14734. buildCSSClass() {
  14735. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  14736. }
  14737. buildWrapperCSSClass() {
  14738. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  14739. }
  14740. /**
  14741. * Create caption/subtitles menu items
  14742. *
  14743. * @return {CaptionSettingsMenuItem[]}
  14744. * The array of current menu items.
  14745. */
  14746. createItems() {
  14747. let items = [];
  14748. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14749. items.push(new CaptionSettingsMenuItem(this.player_, {
  14750. kind: this.label_
  14751. }));
  14752. this.hideThreshold_ += 1;
  14753. }
  14754. items = super.createItems(items, SubsCapsMenuItem);
  14755. return items;
  14756. }
  14757. }
  14758. /**
  14759. * `kind`s of TextTrack to look for to associate it with this menu.
  14760. *
  14761. * @type {array}
  14762. * @private
  14763. */
  14764. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  14765. /**
  14766. * The text that should display over the `SubsCapsButton`s controls.
  14767. *
  14768. *
  14769. * @type {string}
  14770. * @protected
  14771. */
  14772. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  14773. Component.registerComponent('SubsCapsButton', SubsCapsButton);
  14774. /**
  14775. * @file audio-track-menu-item.js
  14776. */
  14777. /**
  14778. * An {@link AudioTrack} {@link MenuItem}
  14779. *
  14780. * @extends MenuItem
  14781. */
  14782. class AudioTrackMenuItem extends MenuItem {
  14783. /**
  14784. * Creates an instance of this class.
  14785. *
  14786. * @param { import('../../player').default } player
  14787. * The `Player` that this class should be attached to.
  14788. *
  14789. * @param {Object} [options]
  14790. * The key/value store of player options.
  14791. */
  14792. constructor(player, options) {
  14793. const track = options.track;
  14794. const tracks = player.audioTracks();
  14795. // Modify options for parent MenuItem class's init.
  14796. options.label = track.label || track.language || 'Unknown';
  14797. options.selected = track.enabled;
  14798. super(player, options);
  14799. this.track = track;
  14800. this.addClass(`vjs-${track.kind}-menu-item`);
  14801. const changeHandler = (...args) => {
  14802. this.handleTracksChange.apply(this, args);
  14803. };
  14804. tracks.addEventListener('change', changeHandler);
  14805. this.on('dispose', () => {
  14806. tracks.removeEventListener('change', changeHandler);
  14807. });
  14808. }
  14809. createEl(type, props, attrs) {
  14810. const el = super.createEl(type, props, attrs);
  14811. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14812. if (this.options_.track.kind === 'main-desc') {
  14813. parentSpan.appendChild(createEl('span', {
  14814. className: 'vjs-icon-placeholder'
  14815. }, {
  14816. 'aria-hidden': true
  14817. }));
  14818. parentSpan.appendChild(createEl('span', {
  14819. className: 'vjs-control-text',
  14820. textContent: ' ' + this.localize('Descriptions')
  14821. }));
  14822. }
  14823. return el;
  14824. }
  14825. /**
  14826. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  14827. * for more detailed information on what a click can be.
  14828. *
  14829. * @param {Event} [event]
  14830. * The `keydown`, `tap`, or `click` event that caused this function to be
  14831. * called.
  14832. *
  14833. * @listens tap
  14834. * @listens click
  14835. */
  14836. handleClick(event) {
  14837. super.handleClick(event);
  14838. // the audio track list will automatically toggle other tracks
  14839. // off for us.
  14840. this.track.enabled = true;
  14841. // when native audio tracks are used, we want to make sure that other tracks are turned off
  14842. if (this.player_.tech_.featuresNativeAudioTracks) {
  14843. const tracks = this.player_.audioTracks();
  14844. for (let i = 0; i < tracks.length; i++) {
  14845. const track = tracks[i];
  14846. // skip the current track since we enabled it above
  14847. if (track === this.track) {
  14848. continue;
  14849. }
  14850. track.enabled = track === this.track;
  14851. }
  14852. }
  14853. }
  14854. /**
  14855. * Handle any {@link AudioTrack} change.
  14856. *
  14857. * @param {Event} [event]
  14858. * The {@link AudioTrackList#change} event that caused this to run.
  14859. *
  14860. * @listens AudioTrackList#change
  14861. */
  14862. handleTracksChange(event) {
  14863. this.selected(this.track.enabled);
  14864. }
  14865. }
  14866. Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  14867. /**
  14868. * @file audio-track-button.js
  14869. */
  14870. /**
  14871. * The base class for buttons that toggle specific {@link AudioTrack} types.
  14872. *
  14873. * @extends TrackButton
  14874. */
  14875. class AudioTrackButton extends TrackButton {
  14876. /**
  14877. * Creates an instance of this class.
  14878. *
  14879. * @param {Player} player
  14880. * The `Player` that this class should be attached to.
  14881. *
  14882. * @param {Object} [options={}]
  14883. * The key/value store of player options.
  14884. */
  14885. constructor(player, options = {}) {
  14886. options.tracks = player.audioTracks();
  14887. super(player, options);
  14888. }
  14889. /**
  14890. * Builds the default DOM `className`.
  14891. *
  14892. * @return {string}
  14893. * The DOM `className` for this object.
  14894. */
  14895. buildCSSClass() {
  14896. return `vjs-audio-button ${super.buildCSSClass()}`;
  14897. }
  14898. buildWrapperCSSClass() {
  14899. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  14900. }
  14901. /**
  14902. * Create a menu item for each audio track
  14903. *
  14904. * @param {AudioTrackMenuItem[]} [items=[]]
  14905. * An array of existing menu items to use.
  14906. *
  14907. * @return {AudioTrackMenuItem[]}
  14908. * An array of menu items
  14909. */
  14910. createItems(items = []) {
  14911. // if there's only one audio track, there no point in showing it
  14912. this.hideThreshold_ = 1;
  14913. const tracks = this.player_.audioTracks();
  14914. for (let i = 0; i < tracks.length; i++) {
  14915. const track = tracks[i];
  14916. items.push(new AudioTrackMenuItem(this.player_, {
  14917. track,
  14918. // MenuItem is selectable
  14919. selectable: true,
  14920. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14921. multiSelectable: false
  14922. }));
  14923. }
  14924. return items;
  14925. }
  14926. }
  14927. /**
  14928. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  14929. *
  14930. * @type {string}
  14931. * @protected
  14932. */
  14933. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  14934. Component.registerComponent('AudioTrackButton', AudioTrackButton);
  14935. /**
  14936. * @file playback-rate-menu-item.js
  14937. */
  14938. /**
  14939. * The specific menu item type for selecting a playback rate.
  14940. *
  14941. * @extends MenuItem
  14942. */
  14943. class PlaybackRateMenuItem extends MenuItem {
  14944. /**
  14945. * Creates an instance of this class.
  14946. *
  14947. * @param { import('../../player').default } player
  14948. * The `Player` that this class should be attached to.
  14949. *
  14950. * @param {Object} [options]
  14951. * The key/value store of player options.
  14952. */
  14953. constructor(player, options) {
  14954. const label = options.rate;
  14955. const rate = parseFloat(label, 10);
  14956. // Modify options for parent MenuItem class's init.
  14957. options.label = label;
  14958. options.selected = rate === player.playbackRate();
  14959. options.selectable = true;
  14960. options.multiSelectable = false;
  14961. super(player, options);
  14962. this.label = label;
  14963. this.rate = rate;
  14964. this.on(player, 'ratechange', e => this.update(e));
  14965. }
  14966. /**
  14967. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  14968. * {@link ClickableComponent} for more detailed information on what a click can be.
  14969. *
  14970. * @param {Event} [event]
  14971. * The `keydown`, `tap`, or `click` event that caused this function to be
  14972. * called.
  14973. *
  14974. * @listens tap
  14975. * @listens click
  14976. */
  14977. handleClick(event) {
  14978. super.handleClick();
  14979. this.player().playbackRate(this.rate);
  14980. }
  14981. /**
  14982. * Update the PlaybackRateMenuItem when the playbackrate changes.
  14983. *
  14984. * @param {Event} [event]
  14985. * The `ratechange` event that caused this function to run.
  14986. *
  14987. * @listens Player#ratechange
  14988. */
  14989. update(event) {
  14990. this.selected(this.player().playbackRate() === this.rate);
  14991. }
  14992. }
  14993. /**
  14994. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  14995. *
  14996. * @type {string}
  14997. * @private
  14998. */
  14999. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15000. Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15001. /**
  15002. * @file playback-rate-menu-button.js
  15003. */
  15004. /**
  15005. * The component for controlling the playback rate.
  15006. *
  15007. * @extends MenuButton
  15008. */
  15009. class PlaybackRateMenuButton extends MenuButton {
  15010. /**
  15011. * Creates an instance of this class.
  15012. *
  15013. * @param { import('../../player').default } player
  15014. * The `Player` that this class should be attached to.
  15015. *
  15016. * @param {Object} [options]
  15017. * The key/value store of player options.
  15018. */
  15019. constructor(player, options) {
  15020. super(player, options);
  15021. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  15022. this.updateVisibility();
  15023. this.updateLabel();
  15024. this.on(player, 'loadstart', e => this.updateVisibility(e));
  15025. this.on(player, 'ratechange', e => this.updateLabel(e));
  15026. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  15027. }
  15028. /**
  15029. * Create the `Component`'s DOM element
  15030. *
  15031. * @return {Element}
  15032. * The element that was created.
  15033. */
  15034. createEl() {
  15035. const el = super.createEl();
  15036. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15037. this.labelEl_ = createEl('div', {
  15038. className: 'vjs-playback-rate-value',
  15039. id: this.labelElId_,
  15040. textContent: '1x'
  15041. });
  15042. el.appendChild(this.labelEl_);
  15043. return el;
  15044. }
  15045. dispose() {
  15046. this.labelEl_ = null;
  15047. super.dispose();
  15048. }
  15049. /**
  15050. * Builds the default DOM `className`.
  15051. *
  15052. * @return {string}
  15053. * The DOM `className` for this object.
  15054. */
  15055. buildCSSClass() {
  15056. return `vjs-playback-rate ${super.buildCSSClass()}`;
  15057. }
  15058. buildWrapperCSSClass() {
  15059. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  15060. }
  15061. /**
  15062. * Create the list of menu items. Specific to each subclass.
  15063. *
  15064. */
  15065. createItems() {
  15066. const rates = this.playbackRates();
  15067. const items = [];
  15068. for (let i = rates.length - 1; i >= 0; i--) {
  15069. items.push(new PlaybackRateMenuItem(this.player(), {
  15070. rate: rates[i] + 'x'
  15071. }));
  15072. }
  15073. return items;
  15074. }
  15075. /**
  15076. * On playbackrateschange, update the menu to account for the new items.
  15077. *
  15078. * @listens Player#playbackrateschange
  15079. */
  15080. handlePlaybackRateschange(event) {
  15081. this.update();
  15082. }
  15083. /**
  15084. * Get possible playback rates
  15085. *
  15086. * @return {Array}
  15087. * All possible playback rates
  15088. */
  15089. playbackRates() {
  15090. const player = this.player();
  15091. return player.playbackRates && player.playbackRates() || [];
  15092. }
  15093. /**
  15094. * Get whether playback rates is supported by the tech
  15095. * and an array of playback rates exists
  15096. *
  15097. * @return {boolean}
  15098. * Whether changing playback rate is supported
  15099. */
  15100. playbackRateSupported() {
  15101. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15102. }
  15103. /**
  15104. * Hide playback rate controls when they're no playback rate options to select
  15105. *
  15106. * @param {Event} [event]
  15107. * The event that caused this function to run.
  15108. *
  15109. * @listens Player#loadstart
  15110. */
  15111. updateVisibility(event) {
  15112. if (this.playbackRateSupported()) {
  15113. this.removeClass('vjs-hidden');
  15114. } else {
  15115. this.addClass('vjs-hidden');
  15116. }
  15117. }
  15118. /**
  15119. * Update button label when rate changed
  15120. *
  15121. * @param {Event} [event]
  15122. * The event that caused this function to run.
  15123. *
  15124. * @listens Player#ratechange
  15125. */
  15126. updateLabel(event) {
  15127. if (this.playbackRateSupported()) {
  15128. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  15129. }
  15130. }
  15131. }
  15132. /**
  15133. * The text that should display over the `PlaybackRateMenuButton`s controls.
  15134. *
  15135. * Added for localization.
  15136. *
  15137. * @type {string}
  15138. * @protected
  15139. */
  15140. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  15141. Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  15142. /**
  15143. * @file spacer.js
  15144. */
  15145. /**
  15146. * Just an empty spacer element that can be used as an append point for plugins, etc.
  15147. * Also can be used to create space between elements when necessary.
  15148. *
  15149. * @extends Component
  15150. */
  15151. class Spacer extends Component {
  15152. /**
  15153. * Builds the default DOM `className`.
  15154. *
  15155. * @return {string}
  15156. * The DOM `className` for this object.
  15157. */
  15158. buildCSSClass() {
  15159. return `vjs-spacer ${super.buildCSSClass()}`;
  15160. }
  15161. /**
  15162. * Create the `Component`'s DOM element
  15163. *
  15164. * @return {Element}
  15165. * The element that was created.
  15166. */
  15167. createEl(tag = 'div', props = {}, attributes = {}) {
  15168. if (!props.className) {
  15169. props.className = this.buildCSSClass();
  15170. }
  15171. return super.createEl(tag, props, attributes);
  15172. }
  15173. }
  15174. Component.registerComponent('Spacer', Spacer);
  15175. /**
  15176. * @file custom-control-spacer.js
  15177. */
  15178. /**
  15179. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  15180. *
  15181. * @extends Spacer
  15182. */
  15183. class CustomControlSpacer extends Spacer {
  15184. /**
  15185. * Builds the default DOM `className`.
  15186. *
  15187. * @return {string}
  15188. * The DOM `className` for this object.
  15189. */
  15190. buildCSSClass() {
  15191. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  15192. }
  15193. /**
  15194. * Create the `Component`'s DOM element
  15195. *
  15196. * @return {Element}
  15197. * The element that was created.
  15198. */
  15199. createEl() {
  15200. return super.createEl('div', {
  15201. className: this.buildCSSClass(),
  15202. // No-flex/table-cell mode requires there be some content
  15203. // in the cell to fill the remaining space of the table.
  15204. textContent: '\u00a0'
  15205. });
  15206. }
  15207. }
  15208. Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
  15209. /**
  15210. * @file control-bar.js
  15211. */
  15212. /**
  15213. * Container of main controls.
  15214. *
  15215. * @extends Component
  15216. */
  15217. class ControlBar extends Component {
  15218. /**
  15219. * Create the `Component`'s DOM element
  15220. *
  15221. * @return {Element}
  15222. * The element that was created.
  15223. */
  15224. createEl() {
  15225. return super.createEl('div', {
  15226. className: 'vjs-control-bar',
  15227. dir: 'ltr'
  15228. });
  15229. }
  15230. }
  15231. /**
  15232. * Default options for `ControlBar`
  15233. *
  15234. * @type {Object}
  15235. * @private
  15236. */
  15237. ControlBar.prototype.options_ = {
  15238. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  15239. };
  15240. if ('exitPictureInPicture' in document) {
  15241. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  15242. }
  15243. Component.registerComponent('ControlBar', ControlBar);
  15244. /**
  15245. * @file error-display.js
  15246. */
  15247. /**
  15248. * A display that indicates an error has occurred. This means that the video
  15249. * is unplayable.
  15250. *
  15251. * @extends ModalDialog
  15252. */
  15253. class ErrorDisplay extends ModalDialog {
  15254. /**
  15255. * Creates an instance of this class.
  15256. *
  15257. * @param { import('./player').default } player
  15258. * The `Player` that this class should be attached to.
  15259. *
  15260. * @param {Object} [options]
  15261. * The key/value store of player options.
  15262. */
  15263. constructor(player, options) {
  15264. super(player, options);
  15265. this.on(player, 'error', e => this.open(e));
  15266. }
  15267. /**
  15268. * Builds the default DOM `className`.
  15269. *
  15270. * @return {string}
  15271. * The DOM `className` for this object.
  15272. *
  15273. * @deprecated Since version 5.
  15274. */
  15275. buildCSSClass() {
  15276. return `vjs-error-display ${super.buildCSSClass()}`;
  15277. }
  15278. /**
  15279. * Gets the localized error message based on the `Player`s error.
  15280. *
  15281. * @return {string}
  15282. * The `Player`s error message localized or an empty string.
  15283. */
  15284. content() {
  15285. const error = this.player().error();
  15286. return error ? this.localize(error.message) : '';
  15287. }
  15288. }
  15289. /**
  15290. * The default options for an `ErrorDisplay`.
  15291. *
  15292. * @private
  15293. */
  15294. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  15295. pauseOnOpen: false,
  15296. fillAlways: true,
  15297. temporary: false,
  15298. uncloseable: true
  15299. });
  15300. Component.registerComponent('ErrorDisplay', ErrorDisplay);
  15301. /**
  15302. * @file text-track-settings.js
  15303. */
  15304. const LOCAL_STORAGE_KEY = 'vjs-text-track-settings';
  15305. const COLOR_BLACK = ['#000', 'Black'];
  15306. const COLOR_BLUE = ['#00F', 'Blue'];
  15307. const COLOR_CYAN = ['#0FF', 'Cyan'];
  15308. const COLOR_GREEN = ['#0F0', 'Green'];
  15309. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  15310. const COLOR_RED = ['#F00', 'Red'];
  15311. const COLOR_WHITE = ['#FFF', 'White'];
  15312. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  15313. const OPACITY_OPAQUE = ['1', 'Opaque'];
  15314. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  15315. const OPACITY_TRANS = ['0', 'Transparent'];
  15316. // Configuration for the various <select> elements in the DOM of this component.
  15317. //
  15318. // Possible keys include:
  15319. //
  15320. // `default`:
  15321. // The default option index. Only needs to be provided if not zero.
  15322. // `parser`:
  15323. // A function which is used to parse the value from the selected option in
  15324. // a customized way.
  15325. // `selector`:
  15326. // The selector used to find the associated <select> element.
  15327. const selectConfigs = {
  15328. backgroundColor: {
  15329. selector: '.vjs-bg-color > select',
  15330. id: 'captions-background-color-%s',
  15331. label: 'Color',
  15332. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15333. },
  15334. backgroundOpacity: {
  15335. selector: '.vjs-bg-opacity > select',
  15336. id: 'captions-background-opacity-%s',
  15337. label: 'Opacity',
  15338. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  15339. },
  15340. color: {
  15341. selector: '.vjs-text-color > select',
  15342. id: 'captions-foreground-color-%s',
  15343. label: 'Color',
  15344. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15345. },
  15346. edgeStyle: {
  15347. selector: '.vjs-edge-style > select',
  15348. id: '%s',
  15349. label: 'Text Edge Style',
  15350. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  15351. },
  15352. fontFamily: {
  15353. selector: '.vjs-font-family > select',
  15354. id: 'captions-font-family-%s',
  15355. label: 'Font Family',
  15356. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  15357. },
  15358. fontPercent: {
  15359. selector: '.vjs-font-percent > select',
  15360. id: 'captions-font-size-%s',
  15361. label: 'Font Size',
  15362. options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
  15363. default: 2,
  15364. parser: v => v === '1.00' ? null : Number(v)
  15365. },
  15366. textOpacity: {
  15367. selector: '.vjs-text-opacity > select',
  15368. id: 'captions-foreground-opacity-%s',
  15369. label: 'Opacity',
  15370. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  15371. },
  15372. // Options for this object are defined below.
  15373. windowColor: {
  15374. selector: '.vjs-window-color > select',
  15375. id: 'captions-window-color-%s',
  15376. label: 'Color'
  15377. },
  15378. // Options for this object are defined below.
  15379. windowOpacity: {
  15380. selector: '.vjs-window-opacity > select',
  15381. id: 'captions-window-opacity-%s',
  15382. label: 'Opacity',
  15383. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  15384. }
  15385. };
  15386. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  15387. /**
  15388. * Get the actual value of an option.
  15389. *
  15390. * @param {string} value
  15391. * The value to get
  15392. *
  15393. * @param {Function} [parser]
  15394. * Optional function to adjust the value.
  15395. *
  15396. * @return {*}
  15397. * - Will be `undefined` if no value exists
  15398. * - Will be `undefined` if the given value is "none".
  15399. * - Will be the actual value otherwise.
  15400. *
  15401. * @private
  15402. */
  15403. function parseOptionValue(value, parser) {
  15404. if (parser) {
  15405. value = parser(value);
  15406. }
  15407. if (value && value !== 'none') {
  15408. return value;
  15409. }
  15410. }
  15411. /**
  15412. * Gets the value of the selected <option> element within a <select> element.
  15413. *
  15414. * @param {Element} el
  15415. * the element to look in
  15416. *
  15417. * @param {Function} [parser]
  15418. * Optional function to adjust the value.
  15419. *
  15420. * @return {*}
  15421. * - Will be `undefined` if no value exists
  15422. * - Will be `undefined` if the given value is "none".
  15423. * - Will be the actual value otherwise.
  15424. *
  15425. * @private
  15426. */
  15427. function getSelectedOptionValue(el, parser) {
  15428. const value = el.options[el.options.selectedIndex].value;
  15429. return parseOptionValue(value, parser);
  15430. }
  15431. /**
  15432. * Sets the selected <option> element within a <select> element based on a
  15433. * given value.
  15434. *
  15435. * @param {Element} el
  15436. * The element to look in.
  15437. *
  15438. * @param {string} value
  15439. * the property to look on.
  15440. *
  15441. * @param {Function} [parser]
  15442. * Optional function to adjust the value before comparing.
  15443. *
  15444. * @private
  15445. */
  15446. function setSelectedOption(el, value, parser) {
  15447. if (!value) {
  15448. return;
  15449. }
  15450. for (let i = 0; i < el.options.length; i++) {
  15451. if (parseOptionValue(el.options[i].value, parser) === value) {
  15452. el.selectedIndex = i;
  15453. break;
  15454. }
  15455. }
  15456. }
  15457. /**
  15458. * Manipulate Text Tracks settings.
  15459. *
  15460. * @extends ModalDialog
  15461. */
  15462. class TextTrackSettings extends ModalDialog {
  15463. /**
  15464. * Creates an instance of this class.
  15465. *
  15466. * @param { import('../player').default } player
  15467. * The `Player` that this class should be attached to.
  15468. *
  15469. * @param {Object} [options]
  15470. * The key/value store of player options.
  15471. */
  15472. constructor(player, options) {
  15473. options.temporary = false;
  15474. super(player, options);
  15475. this.updateDisplay = this.updateDisplay.bind(this);
  15476. // fill the modal and pretend we have opened it
  15477. this.fill();
  15478. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  15479. this.endDialog = createEl('p', {
  15480. className: 'vjs-control-text',
  15481. textContent: this.localize('End of dialog window.')
  15482. });
  15483. this.el().appendChild(this.endDialog);
  15484. this.setDefaults();
  15485. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  15486. if (options.persistTextTrackSettings === undefined) {
  15487. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  15488. }
  15489. this.on(this.$('.vjs-done-button'), 'click', () => {
  15490. this.saveSettings();
  15491. this.close();
  15492. });
  15493. this.on(this.$('.vjs-default-button'), 'click', () => {
  15494. this.setDefaults();
  15495. this.updateDisplay();
  15496. });
  15497. each(selectConfigs, config => {
  15498. this.on(this.$(config.selector), 'change', this.updateDisplay);
  15499. });
  15500. if (this.options_.persistTextTrackSettings) {
  15501. this.restoreSettings();
  15502. }
  15503. }
  15504. dispose() {
  15505. this.endDialog = null;
  15506. super.dispose();
  15507. }
  15508. /**
  15509. * Create a <select> element with configured options.
  15510. *
  15511. * @param {string} key
  15512. * Configuration key to use during creation.
  15513. *
  15514. * @return {string}
  15515. * An HTML string.
  15516. *
  15517. * @private
  15518. */
  15519. createElSelect_(key, legendId = '', type = 'label') {
  15520. const config = selectConfigs[key];
  15521. const id = config.id.replace('%s', this.id_);
  15522. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  15523. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  15524. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  15525. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  15526. })).concat('</select>').join('');
  15527. }
  15528. /**
  15529. * Create foreground color element for the component
  15530. *
  15531. * @return {string}
  15532. * An HTML string.
  15533. *
  15534. * @private
  15535. */
  15536. createElFgColor_() {
  15537. const legendId = `captions-text-legend-${this.id_}`;
  15538. return ['<fieldset class="vjs-fg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text'), '</legend>', '<span class="vjs-text-color">', this.createElSelect_('color', legendId), '</span>', '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
  15539. }
  15540. /**
  15541. * Create background color element for the component
  15542. *
  15543. * @return {string}
  15544. * An HTML string.
  15545. *
  15546. * @private
  15547. */
  15548. createElBgColor_() {
  15549. const legendId = `captions-background-${this.id_}`;
  15550. return ['<fieldset class="vjs-bg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text Background'), '</legend>', '<span class="vjs-bg-color">', this.createElSelect_('backgroundColor', legendId), '</span>', '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
  15551. }
  15552. /**
  15553. * Create window color element for the component
  15554. *
  15555. * @return {string}
  15556. * An HTML string.
  15557. *
  15558. * @private
  15559. */
  15560. createElWinColor_() {
  15561. const legendId = `captions-window-${this.id_}`;
  15562. return ['<fieldset class="vjs-window vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Caption Area Background'), '</legend>', '<span class="vjs-window-color">', this.createElSelect_('windowColor', legendId), '</span>', '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
  15563. }
  15564. /**
  15565. * Create color elements for the component
  15566. *
  15567. * @return {Element}
  15568. * The element that was created
  15569. *
  15570. * @private
  15571. */
  15572. createElColors_() {
  15573. return createEl('div', {
  15574. className: 'vjs-track-settings-colors',
  15575. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  15576. });
  15577. }
  15578. /**
  15579. * Create font elements for the component
  15580. *
  15581. * @return {Element}
  15582. * The element that was created.
  15583. *
  15584. * @private
  15585. */
  15586. createElFont_() {
  15587. return createEl('div', {
  15588. className: 'vjs-track-settings-font',
  15589. innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_('fontPercent', '', 'legend'), '</fieldset>', '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_('edgeStyle', '', 'legend'), '</fieldset>', '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_('fontFamily', '', 'legend'), '</fieldset>'].join('')
  15590. });
  15591. }
  15592. /**
  15593. * Create controls for the component
  15594. *
  15595. * @return {Element}
  15596. * The element that was created.
  15597. *
  15598. * @private
  15599. */
  15600. createElControls_() {
  15601. const defaultsDescription = this.localize('restore all settings to the default values');
  15602. return createEl('div', {
  15603. className: 'vjs-track-settings-controls',
  15604. innerHTML: [`<button type="button" class="vjs-default-button" title="${defaultsDescription}">`, this.localize('Reset'), `<span class="vjs-control-text"> ${defaultsDescription}</span>`, '</button>', `<button type="button" class="vjs-done-button">${this.localize('Done')}</button>`].join('')
  15605. });
  15606. }
  15607. content() {
  15608. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  15609. }
  15610. label() {
  15611. return this.localize('Caption Settings Dialog');
  15612. }
  15613. description() {
  15614. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  15615. }
  15616. buildCSSClass() {
  15617. return super.buildCSSClass() + ' vjs-text-track-settings';
  15618. }
  15619. /**
  15620. * Gets an object of text track settings (or null).
  15621. *
  15622. * @return {Object}
  15623. * An object with config values parsed from the DOM or localStorage.
  15624. */
  15625. getValues() {
  15626. return reduce(selectConfigs, (accum, config, key) => {
  15627. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  15628. if (value !== undefined) {
  15629. accum[key] = value;
  15630. }
  15631. return accum;
  15632. }, {});
  15633. }
  15634. /**
  15635. * Sets text track settings from an object of values.
  15636. *
  15637. * @param {Object} values
  15638. * An object with config values parsed from the DOM or localStorage.
  15639. */
  15640. setValues(values) {
  15641. each(selectConfigs, (config, key) => {
  15642. setSelectedOption(this.$(config.selector), values[key], config.parser);
  15643. });
  15644. }
  15645. /**
  15646. * Sets all `<select>` elements to their default values.
  15647. */
  15648. setDefaults() {
  15649. each(selectConfigs, config => {
  15650. const index = config.hasOwnProperty('default') ? config.default : 0;
  15651. this.$(config.selector).selectedIndex = index;
  15652. });
  15653. }
  15654. /**
  15655. * Restore texttrack settings from localStorage
  15656. */
  15657. restoreSettings() {
  15658. let values;
  15659. try {
  15660. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY));
  15661. } catch (err) {
  15662. log.warn(err);
  15663. }
  15664. if (values) {
  15665. this.setValues(values);
  15666. }
  15667. }
  15668. /**
  15669. * Save text track settings to localStorage
  15670. */
  15671. saveSettings() {
  15672. if (!this.options_.persistTextTrackSettings) {
  15673. return;
  15674. }
  15675. const values = this.getValues();
  15676. try {
  15677. if (Object.keys(values).length) {
  15678. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values));
  15679. } else {
  15680. window.localStorage.removeItem(LOCAL_STORAGE_KEY);
  15681. }
  15682. } catch (err) {
  15683. log.warn(err);
  15684. }
  15685. }
  15686. /**
  15687. * Update display of text track settings
  15688. */
  15689. updateDisplay() {
  15690. const ttDisplay = this.player_.getChild('textTrackDisplay');
  15691. if (ttDisplay) {
  15692. ttDisplay.updateDisplay();
  15693. }
  15694. }
  15695. /**
  15696. * conditionally blur the element and refocus the captions button
  15697. *
  15698. * @private
  15699. */
  15700. conditionalBlur_() {
  15701. this.previouslyActiveEl_ = null;
  15702. const cb = this.player_.controlBar;
  15703. const subsCapsBtn = cb && cb.subsCapsButton;
  15704. const ccBtn = cb && cb.captionsButton;
  15705. if (subsCapsBtn) {
  15706. subsCapsBtn.focus();
  15707. } else if (ccBtn) {
  15708. ccBtn.focus();
  15709. }
  15710. }
  15711. /**
  15712. * Repopulate dialog with new localizations on languagechange
  15713. */
  15714. handleLanguagechange() {
  15715. this.fill();
  15716. }
  15717. }
  15718. Component.registerComponent('TextTrackSettings', TextTrackSettings);
  15719. /**
  15720. * @file resize-manager.js
  15721. */
  15722. /**
  15723. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  15724. *
  15725. * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
  15726. *
  15727. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  15728. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  15729. *
  15730. * @example <caption>How to disable the resize manager</caption>
  15731. * const player = videojs('#vid', {
  15732. * resizeManager: false
  15733. * });
  15734. *
  15735. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  15736. *
  15737. * @extends Component
  15738. */
  15739. class ResizeManager extends Component {
  15740. /**
  15741. * Create the ResizeManager.
  15742. *
  15743. * @param {Object} player
  15744. * The `Player` that this class should be attached to.
  15745. *
  15746. * @param {Object} [options]
  15747. * The key/value store of ResizeManager options.
  15748. *
  15749. * @param {Object} [options.ResizeObserver]
  15750. * A polyfill for ResizeObserver can be passed in here.
  15751. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  15752. */
  15753. constructor(player, options) {
  15754. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  15755. // if `null` was passed, we want to disable the ResizeObserver
  15756. if (options.ResizeObserver === null) {
  15757. RESIZE_OBSERVER_AVAILABLE = false;
  15758. }
  15759. // Only create an element when ResizeObserver isn't available
  15760. const options_ = merge({
  15761. createEl: !RESIZE_OBSERVER_AVAILABLE,
  15762. reportTouchActivity: false
  15763. }, options);
  15764. super(player, options_);
  15765. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  15766. this.loadListener_ = null;
  15767. this.resizeObserver_ = null;
  15768. this.debouncedHandler_ = debounce(() => {
  15769. this.resizeHandler();
  15770. }, 100, false, this);
  15771. if (RESIZE_OBSERVER_AVAILABLE) {
  15772. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  15773. this.resizeObserver_.observe(player.el());
  15774. } else {
  15775. this.loadListener_ = () => {
  15776. if (!this.el_ || !this.el_.contentWindow) {
  15777. return;
  15778. }
  15779. const debouncedHandler_ = this.debouncedHandler_;
  15780. let unloadListener_ = this.unloadListener_ = function () {
  15781. off(this, 'resize', debouncedHandler_);
  15782. off(this, 'unload', unloadListener_);
  15783. unloadListener_ = null;
  15784. };
  15785. // safari and edge can unload the iframe before resizemanager dispose
  15786. // we have to dispose of event handlers correctly before that happens
  15787. on(this.el_.contentWindow, 'unload', unloadListener_);
  15788. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  15789. };
  15790. this.one('load', this.loadListener_);
  15791. }
  15792. }
  15793. createEl() {
  15794. return super.createEl('iframe', {
  15795. className: 'vjs-resize-manager',
  15796. tabIndex: -1,
  15797. title: this.localize('No content')
  15798. }, {
  15799. 'aria-hidden': 'true'
  15800. });
  15801. }
  15802. /**
  15803. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  15804. *
  15805. * @fires Player#playerresize
  15806. */
  15807. resizeHandler() {
  15808. /**
  15809. * Called when the player size has changed
  15810. *
  15811. * @event Player#playerresize
  15812. * @type {Event}
  15813. */
  15814. // make sure player is still around to trigger
  15815. // prevents this from causing an error after dispose
  15816. if (!this.player_ || !this.player_.trigger) {
  15817. return;
  15818. }
  15819. this.player_.trigger('playerresize');
  15820. }
  15821. dispose() {
  15822. if (this.debouncedHandler_) {
  15823. this.debouncedHandler_.cancel();
  15824. }
  15825. if (this.resizeObserver_) {
  15826. if (this.player_.el()) {
  15827. this.resizeObserver_.unobserve(this.player_.el());
  15828. }
  15829. this.resizeObserver_.disconnect();
  15830. }
  15831. if (this.loadListener_) {
  15832. this.off('load', this.loadListener_);
  15833. }
  15834. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  15835. this.unloadListener_.call(this.el_.contentWindow);
  15836. }
  15837. this.ResizeObserver = null;
  15838. this.resizeObserver = null;
  15839. this.debouncedHandler_ = null;
  15840. this.loadListener_ = null;
  15841. super.dispose();
  15842. }
  15843. }
  15844. Component.registerComponent('ResizeManager', ResizeManager);
  15845. const defaults = {
  15846. trackingThreshold: 20,
  15847. liveTolerance: 15
  15848. };
  15849. /*
  15850. track when we are at the live edge, and other helpers for live playback */
  15851. /**
  15852. * A class for checking live current time and determining when the player
  15853. * is at or behind the live edge.
  15854. */
  15855. class LiveTracker extends Component {
  15856. /**
  15857. * Creates an instance of this class.
  15858. *
  15859. * @param { import('./player').default } player
  15860. * The `Player` that this class should be attached to.
  15861. *
  15862. * @param {Object} [options]
  15863. * The key/value store of player options.
  15864. *
  15865. * @param {number} [options.trackingThreshold=20]
  15866. * Number of seconds of live window (seekableEnd - seekableStart) that
  15867. * media needs to have before the liveui will be shown.
  15868. *
  15869. * @param {number} [options.liveTolerance=15]
  15870. * Number of seconds behind live that we have to be
  15871. * before we will be considered non-live. Note that this will only
  15872. * be used when playing at the live edge. This allows large seekable end
  15873. * changes to not effect whether we are live or not.
  15874. */
  15875. constructor(player, options) {
  15876. // LiveTracker does not need an element
  15877. const options_ = merge(defaults, options, {
  15878. createEl: false
  15879. });
  15880. super(player, options_);
  15881. this.trackLiveHandler_ = () => this.trackLive_();
  15882. this.handlePlay_ = e => this.handlePlay(e);
  15883. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  15884. this.handleSeeked_ = e => this.handleSeeked(e);
  15885. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  15886. this.reset_();
  15887. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  15888. // we should try to toggle tracking on canplay as native playback engines, like Safari
  15889. // may not have the proper values for things like seekableEnd until then
  15890. this.on(this.player_, 'canplay', () => this.toggleTracking());
  15891. }
  15892. /**
  15893. * all the functionality for tracking when seek end changes
  15894. * and for tracking how far past seek end we should be
  15895. */
  15896. trackLive_() {
  15897. const seekable = this.player_.seekable();
  15898. // skip undefined seekable
  15899. if (!seekable || !seekable.length) {
  15900. return;
  15901. }
  15902. const newTime = Number(window.performance.now().toFixed(4));
  15903. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  15904. this.lastTime_ = newTime;
  15905. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  15906. const liveCurrentTime = this.liveCurrentTime();
  15907. const currentTime = this.player_.currentTime();
  15908. // we are behind live if any are true
  15909. // 1. the player is paused
  15910. // 2. the user seeked to a location 2 seconds away from live
  15911. // 3. the difference between live and current time is greater
  15912. // liveTolerance which defaults to 15s
  15913. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  15914. // we cannot be behind if
  15915. // 1. until we have not seen a timeupdate yet
  15916. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  15917. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  15918. isBehind = false;
  15919. }
  15920. if (isBehind !== this.behindLiveEdge_) {
  15921. this.behindLiveEdge_ = isBehind;
  15922. this.trigger('liveedgechange');
  15923. }
  15924. }
  15925. /**
  15926. * handle a durationchange event on the player
  15927. * and start/stop tracking accordingly.
  15928. */
  15929. handleDurationchange() {
  15930. this.toggleTracking();
  15931. }
  15932. /**
  15933. * start/stop tracking
  15934. */
  15935. toggleTracking() {
  15936. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  15937. if (this.player_.options_.liveui) {
  15938. this.player_.addClass('vjs-liveui');
  15939. }
  15940. this.startTracking();
  15941. } else {
  15942. this.player_.removeClass('vjs-liveui');
  15943. this.stopTracking();
  15944. }
  15945. }
  15946. /**
  15947. * start tracking live playback
  15948. */
  15949. startTracking() {
  15950. if (this.isTracking()) {
  15951. return;
  15952. }
  15953. // If we haven't seen a timeupdate, we need to check whether playback
  15954. // began before this component started tracking. This can happen commonly
  15955. // when using autoplay.
  15956. if (!this.timeupdateSeen_) {
  15957. this.timeupdateSeen_ = this.player_.hasStarted();
  15958. }
  15959. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  15960. this.trackLive_();
  15961. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  15962. if (!this.timeupdateSeen_) {
  15963. this.one(this.player_, 'play', this.handlePlay_);
  15964. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  15965. } else {
  15966. this.on(this.player_, 'seeked', this.handleSeeked_);
  15967. }
  15968. }
  15969. /**
  15970. * handle the first timeupdate on the player if it wasn't already playing
  15971. * when live tracker started tracking.
  15972. */
  15973. handleFirstTimeupdate() {
  15974. this.timeupdateSeen_ = true;
  15975. this.on(this.player_, 'seeked', this.handleSeeked_);
  15976. }
  15977. /**
  15978. * Keep track of what time a seek starts, and listen for seeked
  15979. * to find where a seek ends.
  15980. */
  15981. handleSeeked() {
  15982. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  15983. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  15984. this.nextSeekedFromUser_ = false;
  15985. this.trackLive_();
  15986. }
  15987. /**
  15988. * handle the first play on the player, and make sure that we seek
  15989. * right to the live edge.
  15990. */
  15991. handlePlay() {
  15992. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  15993. }
  15994. /**
  15995. * Stop tracking, and set all internal variables to
  15996. * their initial value.
  15997. */
  15998. reset_() {
  15999. this.lastTime_ = -1;
  16000. this.pastSeekEnd_ = 0;
  16001. this.lastSeekEnd_ = -1;
  16002. this.behindLiveEdge_ = true;
  16003. this.timeupdateSeen_ = false;
  16004. this.seekedBehindLive_ = false;
  16005. this.nextSeekedFromUser_ = false;
  16006. this.clearInterval(this.trackingInterval_);
  16007. this.trackingInterval_ = null;
  16008. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16009. this.off(this.player_, 'seeked', this.handleSeeked_);
  16010. this.off(this.player_, 'play', this.handlePlay_);
  16011. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16012. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16013. }
  16014. /**
  16015. * The next seeked event is from the user. Meaning that any seek
  16016. * > 2s behind live will be considered behind live for real and
  16017. * liveTolerance will be ignored.
  16018. */
  16019. nextSeekedFromUser() {
  16020. this.nextSeekedFromUser_ = true;
  16021. }
  16022. /**
  16023. * stop tracking live playback
  16024. */
  16025. stopTracking() {
  16026. if (!this.isTracking()) {
  16027. return;
  16028. }
  16029. this.reset_();
  16030. this.trigger('liveedgechange');
  16031. }
  16032. /**
  16033. * A helper to get the player seekable end
  16034. * so that we don't have to null check everywhere
  16035. *
  16036. * @return {number}
  16037. * The furthest seekable end or Infinity.
  16038. */
  16039. seekableEnd() {
  16040. const seekable = this.player_.seekable();
  16041. const seekableEnds = [];
  16042. let i = seekable ? seekable.length : 0;
  16043. while (i--) {
  16044. seekableEnds.push(seekable.end(i));
  16045. }
  16046. // grab the furthest seekable end after sorting, or if there are none
  16047. // default to Infinity
  16048. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  16049. }
  16050. /**
  16051. * A helper to get the player seekable start
  16052. * so that we don't have to null check everywhere
  16053. *
  16054. * @return {number}
  16055. * The earliest seekable start or 0.
  16056. */
  16057. seekableStart() {
  16058. const seekable = this.player_.seekable();
  16059. const seekableStarts = [];
  16060. let i = seekable ? seekable.length : 0;
  16061. while (i--) {
  16062. seekableStarts.push(seekable.start(i));
  16063. }
  16064. // grab the first seekable start after sorting, or if there are none
  16065. // default to 0
  16066. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  16067. }
  16068. /**
  16069. * Get the live time window aka
  16070. * the amount of time between seekable start and
  16071. * live current time.
  16072. *
  16073. * @return {number}
  16074. * The amount of seconds that are seekable in
  16075. * the live video.
  16076. */
  16077. liveWindow() {
  16078. const liveCurrentTime = this.liveCurrentTime();
  16079. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  16080. if (liveCurrentTime === Infinity) {
  16081. return 0;
  16082. }
  16083. return liveCurrentTime - this.seekableStart();
  16084. }
  16085. /**
  16086. * Determines if the player is live, only checks if this component
  16087. * is tracking live playback or not
  16088. *
  16089. * @return {boolean}
  16090. * Whether liveTracker is tracking
  16091. */
  16092. isLive() {
  16093. return this.isTracking();
  16094. }
  16095. /**
  16096. * Determines if currentTime is at the live edge and won't fall behind
  16097. * on each seekableendchange
  16098. *
  16099. * @return {boolean}
  16100. * Whether playback is at the live edge
  16101. */
  16102. atLiveEdge() {
  16103. return !this.behindLiveEdge();
  16104. }
  16105. /**
  16106. * get what we expect the live current time to be
  16107. *
  16108. * @return {number}
  16109. * The expected live current time
  16110. */
  16111. liveCurrentTime() {
  16112. return this.pastSeekEnd() + this.seekableEnd();
  16113. }
  16114. /**
  16115. * The number of seconds that have occurred after seekable end
  16116. * changed. This will be reset to 0 once seekable end changes.
  16117. *
  16118. * @return {number}
  16119. * Seconds past the current seekable end
  16120. */
  16121. pastSeekEnd() {
  16122. const seekableEnd = this.seekableEnd();
  16123. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  16124. this.pastSeekEnd_ = 0;
  16125. }
  16126. this.lastSeekEnd_ = seekableEnd;
  16127. return this.pastSeekEnd_;
  16128. }
  16129. /**
  16130. * If we are currently behind the live edge, aka currentTime will be
  16131. * behind on a seekableendchange
  16132. *
  16133. * @return {boolean}
  16134. * If we are behind the live edge
  16135. */
  16136. behindLiveEdge() {
  16137. return this.behindLiveEdge_;
  16138. }
  16139. /**
  16140. * Whether live tracker is currently tracking or not.
  16141. */
  16142. isTracking() {
  16143. return typeof this.trackingInterval_ === 'number';
  16144. }
  16145. /**
  16146. * Seek to the live edge if we are behind the live edge
  16147. */
  16148. seekToLiveEdge() {
  16149. this.seekedBehindLive_ = false;
  16150. if (this.atLiveEdge()) {
  16151. return;
  16152. }
  16153. this.nextSeekedFromUser_ = false;
  16154. this.player_.currentTime(this.liveCurrentTime());
  16155. }
  16156. /**
  16157. * Dispose of liveTracker
  16158. */
  16159. dispose() {
  16160. this.stopTracking();
  16161. super.dispose();
  16162. }
  16163. }
  16164. Component.registerComponent('LiveTracker', LiveTracker);
  16165. /**
  16166. * Displays an element over the player which contains an optional title and
  16167. * description for the current content.
  16168. *
  16169. * Much of the code for this component originated in the now obsolete
  16170. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  16171. *
  16172. * @extends Component
  16173. */
  16174. class TitleBar extends Component {
  16175. constructor(player, options) {
  16176. super(player, options);
  16177. this.on('statechanged', e => this.updateDom_());
  16178. this.updateDom_();
  16179. }
  16180. /**
  16181. * Create the `TitleBar`'s DOM element
  16182. *
  16183. * @return {Element}
  16184. * The element that was created.
  16185. */
  16186. createEl() {
  16187. this.els = {
  16188. title: createEl('div', {
  16189. className: 'vjs-title-bar-title',
  16190. id: `vjs-title-bar-title-${newGUID()}`
  16191. }),
  16192. description: createEl('div', {
  16193. className: 'vjs-title-bar-description',
  16194. id: `vjs-title-bar-description-${newGUID()}`
  16195. })
  16196. };
  16197. return createEl('div', {
  16198. className: 'vjs-title-bar'
  16199. }, {}, Object.values(this.els));
  16200. }
  16201. /**
  16202. * Updates the DOM based on the component's state object.
  16203. */
  16204. updateDom_() {
  16205. const tech = this.player_.tech_;
  16206. const techEl = tech && tech.el_;
  16207. const techAriaAttrs = {
  16208. title: 'aria-labelledby',
  16209. description: 'aria-describedby'
  16210. };
  16211. ['title', 'description'].forEach(k => {
  16212. const value = this.state[k];
  16213. const el = this.els[k];
  16214. const techAriaAttr = techAriaAttrs[k];
  16215. emptyEl(el);
  16216. if (value) {
  16217. textContent(el, value);
  16218. }
  16219. // If there is a tech element available, update its ARIA attributes
  16220. // according to whether a title and/or description have been provided.
  16221. if (techEl) {
  16222. techEl.removeAttribute(techAriaAttr);
  16223. if (value) {
  16224. techEl.setAttribute(techAriaAttr, el.id);
  16225. }
  16226. }
  16227. });
  16228. if (this.state.title || this.state.description) {
  16229. this.show();
  16230. } else {
  16231. this.hide();
  16232. }
  16233. }
  16234. /**
  16235. * Update the contents of the title bar component with new title and
  16236. * description text.
  16237. *
  16238. * If both title and description are missing, the title bar will be hidden.
  16239. *
  16240. * If either title or description are present, the title bar will be visible.
  16241. *
  16242. * NOTE: Any previously set value will be preserved. To unset a previously
  16243. * set value, you must pass an empty string or null.
  16244. *
  16245. * For example:
  16246. *
  16247. * ```
  16248. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  16249. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  16250. * update({title: ''}) // title: '', description: 'bar2'
  16251. * update({title: 'foo', description: null}) // title: 'foo', description: null
  16252. * ```
  16253. *
  16254. * @param {Object} [options={}]
  16255. * An options object. When empty, the title bar will be hidden.
  16256. *
  16257. * @param {string} [options.title]
  16258. * A title to display in the title bar.
  16259. *
  16260. * @param {string} [options.description]
  16261. * A description to display in the title bar.
  16262. */
  16263. update(options) {
  16264. this.setState(options);
  16265. }
  16266. /**
  16267. * Dispose the component.
  16268. */
  16269. dispose() {
  16270. const tech = this.player_.tech_;
  16271. const techEl = tech && tech.el_;
  16272. if (techEl) {
  16273. techEl.removeAttribute('aria-labelledby');
  16274. techEl.removeAttribute('aria-describedby');
  16275. }
  16276. super.dispose();
  16277. this.els = null;
  16278. }
  16279. }
  16280. Component.registerComponent('TitleBar', TitleBar);
  16281. /**
  16282. * This function is used to fire a sourceset when there is something
  16283. * similar to `mediaEl.load()` being called. It will try to find the source via
  16284. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  16285. * with the source that was found or empty string if we cannot know. If it cannot
  16286. * find a source then `sourceset` will not be fired.
  16287. *
  16288. * @param { import('./html5').default } tech
  16289. * The tech object that sourceset was setup on
  16290. *
  16291. * @return {boolean}
  16292. * returns false if the sourceset was not fired and true otherwise.
  16293. */
  16294. const sourcesetLoad = tech => {
  16295. const el = tech.el();
  16296. // if `el.src` is set, that source will be loaded.
  16297. if (el.hasAttribute('src')) {
  16298. tech.triggerSourceset(el.src);
  16299. return true;
  16300. }
  16301. /**
  16302. * Since there isn't a src property on the media element, source elements will be used for
  16303. * implementing the source selection algorithm. This happens asynchronously and
  16304. * for most cases were there is more than one source we cannot tell what source will
  16305. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  16306. * going to do that. There are three special cases that we do handle here though:
  16307. *
  16308. * 1. If there are no sources, do not fire `sourceset`.
  16309. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  16310. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  16311. * That will be our src.
  16312. */
  16313. const sources = tech.$$('source');
  16314. const srcUrls = [];
  16315. let src = '';
  16316. // if there are no sources, do not fire sourceset
  16317. if (!sources.length) {
  16318. return false;
  16319. }
  16320. // only count valid/non-duplicate source elements
  16321. for (let i = 0; i < sources.length; i++) {
  16322. const url = sources[i].src;
  16323. if (url && srcUrls.indexOf(url) === -1) {
  16324. srcUrls.push(url);
  16325. }
  16326. }
  16327. // there were no valid sources
  16328. if (!srcUrls.length) {
  16329. return false;
  16330. }
  16331. // there is only one valid source element url
  16332. // use that
  16333. if (srcUrls.length === 1) {
  16334. src = srcUrls[0];
  16335. }
  16336. tech.triggerSourceset(src);
  16337. return true;
  16338. };
  16339. /**
  16340. * our implementation of an `innerHTML` descriptor for browsers
  16341. * that do not have one.
  16342. */
  16343. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  16344. get() {
  16345. return this.cloneNode(true).innerHTML;
  16346. },
  16347. set(v) {
  16348. // make a dummy node to use innerHTML on
  16349. const dummy = document.createElement(this.nodeName.toLowerCase());
  16350. // set innerHTML to the value provided
  16351. dummy.innerHTML = v;
  16352. // make a document fragment to hold the nodes from dummy
  16353. const docFrag = document.createDocumentFragment();
  16354. // copy all of the nodes created by the innerHTML on dummy
  16355. // to the document fragment
  16356. while (dummy.childNodes.length) {
  16357. docFrag.appendChild(dummy.childNodes[0]);
  16358. }
  16359. // remove content
  16360. this.innerText = '';
  16361. // now we add all of that html in one by appending the
  16362. // document fragment. This is how innerHTML does it.
  16363. window.Element.prototype.appendChild.call(this, docFrag);
  16364. // then return the result that innerHTML's setter would
  16365. return this.innerHTML;
  16366. }
  16367. });
  16368. /**
  16369. * Get a property descriptor given a list of priorities and the
  16370. * property to get.
  16371. */
  16372. const getDescriptor = (priority, prop) => {
  16373. let descriptor = {};
  16374. for (let i = 0; i < priority.length; i++) {
  16375. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  16376. if (descriptor && descriptor.set && descriptor.get) {
  16377. break;
  16378. }
  16379. }
  16380. descriptor.enumerable = true;
  16381. descriptor.configurable = true;
  16382. return descriptor;
  16383. };
  16384. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  16385. /**
  16386. * Patches browser internal functions so that we can tell synchronously
  16387. * if a `<source>` was appended to the media element. For some reason this
  16388. * causes a `sourceset` if the the media element is ready and has no source.
  16389. * This happens when:
  16390. * - The page has just loaded and the media element does not have a source.
  16391. * - The media element was emptied of all sources, then `load()` was called.
  16392. *
  16393. * It does this by patching the following functions/properties when they are supported:
  16394. *
  16395. * - `append()` - can be used to add a `<source>` element to the media element
  16396. * - `appendChild()` - can be used to add a `<source>` element to the media element
  16397. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  16398. * - `innerHTML` - can be used to add a `<source>` element to the media element
  16399. *
  16400. * @param {Html5} tech
  16401. * The tech object that sourceset is being setup on.
  16402. */
  16403. const firstSourceWatch = function (tech) {
  16404. const el = tech.el();
  16405. // make sure firstSourceWatch isn't setup twice.
  16406. if (el.resetSourceWatch_) {
  16407. return;
  16408. }
  16409. const old = {};
  16410. const innerDescriptor = getInnerHTMLDescriptor(tech);
  16411. const appendWrapper = appendFn => (...args) => {
  16412. const retval = appendFn.apply(el, args);
  16413. sourcesetLoad(tech);
  16414. return retval;
  16415. };
  16416. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  16417. if (!el[k]) {
  16418. return;
  16419. }
  16420. // store the old function
  16421. old[k] = el[k];
  16422. // call the old function with a sourceset if a source
  16423. // was loaded
  16424. el[k] = appendWrapper(old[k]);
  16425. });
  16426. Object.defineProperty(el, 'innerHTML', merge(innerDescriptor, {
  16427. set: appendWrapper(innerDescriptor.set)
  16428. }));
  16429. el.resetSourceWatch_ = () => {
  16430. el.resetSourceWatch_ = null;
  16431. Object.keys(old).forEach(k => {
  16432. el[k] = old[k];
  16433. });
  16434. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  16435. };
  16436. // on the first sourceset, we need to revert our changes
  16437. tech.one('sourceset', el.resetSourceWatch_);
  16438. };
  16439. /**
  16440. * our implementation of a `src` descriptor for browsers
  16441. * that do not have one
  16442. */
  16443. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  16444. get() {
  16445. if (this.hasAttribute('src')) {
  16446. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  16447. }
  16448. return '';
  16449. },
  16450. set(v) {
  16451. window.Element.prototype.setAttribute.call(this, 'src', v);
  16452. return v;
  16453. }
  16454. });
  16455. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  16456. /**
  16457. * setup `sourceset` handling on the `Html5` tech. This function
  16458. * patches the following element properties/functions:
  16459. *
  16460. * - `src` - to determine when `src` is set
  16461. * - `setAttribute()` - to determine when `src` is set
  16462. * - `load()` - this re-triggers the source selection algorithm, and can
  16463. * cause a sourceset.
  16464. *
  16465. * If there is no source when we are adding `sourceset` support or during a `load()`
  16466. * we also patch the functions listed in `firstSourceWatch`.
  16467. *
  16468. * @param {Html5} tech
  16469. * The tech to patch
  16470. */
  16471. const setupSourceset = function (tech) {
  16472. if (!tech.featuresSourceset) {
  16473. return;
  16474. }
  16475. const el = tech.el();
  16476. // make sure sourceset isn't setup twice.
  16477. if (el.resetSourceset_) {
  16478. return;
  16479. }
  16480. const srcDescriptor = getSrcDescriptor(tech);
  16481. const oldSetAttribute = el.setAttribute;
  16482. const oldLoad = el.load;
  16483. Object.defineProperty(el, 'src', merge(srcDescriptor, {
  16484. set: v => {
  16485. const retval = srcDescriptor.set.call(el, v);
  16486. // we use the getter here to get the actual value set on src
  16487. tech.triggerSourceset(el.src);
  16488. return retval;
  16489. }
  16490. }));
  16491. el.setAttribute = (n, v) => {
  16492. const retval = oldSetAttribute.call(el, n, v);
  16493. if (/src/i.test(n)) {
  16494. tech.triggerSourceset(el.src);
  16495. }
  16496. return retval;
  16497. };
  16498. el.load = () => {
  16499. const retval = oldLoad.call(el);
  16500. // if load was called, but there was no source to fire
  16501. // sourceset on. We have to watch for a source append
  16502. // as that can trigger a `sourceset` when the media element
  16503. // has no source
  16504. if (!sourcesetLoad(tech)) {
  16505. tech.triggerSourceset('');
  16506. firstSourceWatch(tech);
  16507. }
  16508. return retval;
  16509. };
  16510. if (el.currentSrc) {
  16511. tech.triggerSourceset(el.currentSrc);
  16512. } else if (!sourcesetLoad(tech)) {
  16513. firstSourceWatch(tech);
  16514. }
  16515. el.resetSourceset_ = () => {
  16516. el.resetSourceset_ = null;
  16517. el.load = oldLoad;
  16518. el.setAttribute = oldSetAttribute;
  16519. Object.defineProperty(el, 'src', srcDescriptor);
  16520. if (el.resetSourceWatch_) {
  16521. el.resetSourceWatch_();
  16522. }
  16523. };
  16524. };
  16525. /**
  16526. * @file html5.js
  16527. */
  16528. /**
  16529. * HTML5 Media Controller - Wrapper for HTML5 Media API
  16530. *
  16531. * @mixes Tech~SourceHandlerAdditions
  16532. * @extends Tech
  16533. */
  16534. class Html5 extends Tech {
  16535. /**
  16536. * Create an instance of this Tech.
  16537. *
  16538. * @param {Object} [options]
  16539. * The key/value store of player options.
  16540. *
  16541. * @param {Function} [ready]
  16542. * Callback function to call when the `HTML5` Tech is ready.
  16543. */
  16544. constructor(options, ready) {
  16545. super(options, ready);
  16546. const source = options.source;
  16547. let crossoriginTracks = false;
  16548. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  16549. // Set the source if one is provided
  16550. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  16551. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  16552. // anyway so the error gets fired.
  16553. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  16554. this.setSource(source);
  16555. } else {
  16556. this.handleLateInit_(this.el_);
  16557. }
  16558. // setup sourceset after late sourceset/init
  16559. if (options.enableSourceset) {
  16560. this.setupSourcesetHandling_();
  16561. }
  16562. this.isScrubbing_ = false;
  16563. if (this.el_.hasChildNodes()) {
  16564. const nodes = this.el_.childNodes;
  16565. let nodesLength = nodes.length;
  16566. const removeNodes = [];
  16567. while (nodesLength--) {
  16568. const node = nodes[nodesLength];
  16569. const nodeName = node.nodeName.toLowerCase();
  16570. if (nodeName === 'track') {
  16571. if (!this.featuresNativeTextTracks) {
  16572. // Empty video tag tracks so the built-in player doesn't use them also.
  16573. // This may not be fast enough to stop HTML5 browsers from reading the tags
  16574. // so we'll need to turn off any default tracks if we're manually doing
  16575. // captions and subtitles. videoElement.textTracks
  16576. removeNodes.push(node);
  16577. } else {
  16578. // store HTMLTrackElement and TextTrack to remote list
  16579. this.remoteTextTrackEls().addTrackElement_(node);
  16580. this.remoteTextTracks().addTrack(node.track);
  16581. this.textTracks().addTrack(node.track);
  16582. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  16583. crossoriginTracks = true;
  16584. }
  16585. }
  16586. }
  16587. }
  16588. for (let i = 0; i < removeNodes.length; i++) {
  16589. this.el_.removeChild(removeNodes[i]);
  16590. }
  16591. }
  16592. this.proxyNativeTracks_();
  16593. if (this.featuresNativeTextTracks && crossoriginTracks) {
  16594. log.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'This may prevent text tracks from loading.');
  16595. }
  16596. // prevent iOS Safari from disabling metadata text tracks during native playback
  16597. this.restoreMetadataTracksInIOSNativePlayer_();
  16598. // Determine if native controls should be used
  16599. // Our goal should be to get the custom controls on mobile solid everywhere
  16600. // so we can remove this all together. Right now this will block custom
  16601. // controls on touch enabled laptops like the Chrome Pixel
  16602. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  16603. this.setControls(true);
  16604. }
  16605. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  16606. // into a `fullscreenchange` event
  16607. this.proxyWebkitFullscreen_();
  16608. this.triggerReady();
  16609. }
  16610. /**
  16611. * Dispose of `HTML5` media element and remove all tracks.
  16612. */
  16613. dispose() {
  16614. if (this.el_ && this.el_.resetSourceset_) {
  16615. this.el_.resetSourceset_();
  16616. }
  16617. Html5.disposeMediaElement(this.el_);
  16618. this.options_ = null;
  16619. // tech will handle clearing of the emulated track list
  16620. super.dispose();
  16621. }
  16622. /**
  16623. * Modify the media element so that we can detect when
  16624. * the source is changed. Fires `sourceset` just after the source has changed
  16625. */
  16626. setupSourcesetHandling_() {
  16627. setupSourceset(this);
  16628. }
  16629. /**
  16630. * When a captions track is enabled in the iOS Safari native player, all other
  16631. * tracks are disabled (including metadata tracks), which nulls all of their
  16632. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  16633. * state in those cases so that cue points are not needlessly lost.
  16634. *
  16635. * @private
  16636. */
  16637. restoreMetadataTracksInIOSNativePlayer_() {
  16638. const textTracks = this.textTracks();
  16639. let metadataTracksPreFullscreenState;
  16640. // captures a snapshot of every metadata track's current state
  16641. const takeMetadataTrackSnapshot = () => {
  16642. metadataTracksPreFullscreenState = [];
  16643. for (let i = 0; i < textTracks.length; i++) {
  16644. const track = textTracks[i];
  16645. if (track.kind === 'metadata') {
  16646. metadataTracksPreFullscreenState.push({
  16647. track,
  16648. storedMode: track.mode
  16649. });
  16650. }
  16651. }
  16652. };
  16653. // snapshot each metadata track's initial state, and update the snapshot
  16654. // each time there is a track 'change' event
  16655. takeMetadataTrackSnapshot();
  16656. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16657. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  16658. const restoreTrackMode = () => {
  16659. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  16660. const storedTrack = metadataTracksPreFullscreenState[i];
  16661. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  16662. storedTrack.track.mode = storedTrack.storedMode;
  16663. }
  16664. }
  16665. // we only want this handler to be executed on the first 'change' event
  16666. textTracks.removeEventListener('change', restoreTrackMode);
  16667. };
  16668. // when we enter fullscreen playback, stop updating the snapshot and
  16669. // restore all track modes to their pre-fullscreen state
  16670. this.on('webkitbeginfullscreen', () => {
  16671. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16672. // remove the listener before adding it just in case it wasn't previously removed
  16673. textTracks.removeEventListener('change', restoreTrackMode);
  16674. textTracks.addEventListener('change', restoreTrackMode);
  16675. });
  16676. // start updating the snapshot again after leaving fullscreen
  16677. this.on('webkitendfullscreen', () => {
  16678. // remove the listener before adding it just in case it wasn't previously removed
  16679. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16680. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16681. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  16682. textTracks.removeEventListener('change', restoreTrackMode);
  16683. });
  16684. }
  16685. /**
  16686. * Attempt to force override of tracks for the given type
  16687. *
  16688. * @param {string} type - Track type to override, possible values include 'Audio',
  16689. * 'Video', and 'Text'.
  16690. * @param {boolean} override - If set to true native audio/video will be overridden,
  16691. * otherwise native audio/video will potentially be used.
  16692. * @private
  16693. */
  16694. overrideNative_(type, override) {
  16695. // If there is no behavioral change don't add/remove listeners
  16696. if (override !== this[`featuresNative${type}Tracks`]) {
  16697. return;
  16698. }
  16699. const lowerCaseType = type.toLowerCase();
  16700. if (this[`${lowerCaseType}TracksListeners_`]) {
  16701. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  16702. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  16703. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  16704. });
  16705. }
  16706. this[`featuresNative${type}Tracks`] = !override;
  16707. this[`${lowerCaseType}TracksListeners_`] = null;
  16708. this.proxyNativeTracksForType_(lowerCaseType);
  16709. }
  16710. /**
  16711. * Attempt to force override of native audio tracks.
  16712. *
  16713. * @param {boolean} override - If set to true native audio will be overridden,
  16714. * otherwise native audio will potentially be used.
  16715. */
  16716. overrideNativeAudioTracks(override) {
  16717. this.overrideNative_('Audio', override);
  16718. }
  16719. /**
  16720. * Attempt to force override of native video tracks.
  16721. *
  16722. * @param {boolean} override - If set to true native video will be overridden,
  16723. * otherwise native video will potentially be used.
  16724. */
  16725. overrideNativeVideoTracks(override) {
  16726. this.overrideNative_('Video', override);
  16727. }
  16728. /**
  16729. * Proxy native track list events for the given type to our track
  16730. * lists if the browser we are playing in supports that type of track list.
  16731. *
  16732. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  16733. * @private
  16734. */
  16735. proxyNativeTracksForType_(name) {
  16736. const props = NORMAL[name];
  16737. const elTracks = this.el()[props.getterName];
  16738. const techTracks = this[props.getterName]();
  16739. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  16740. return;
  16741. }
  16742. const listeners = {
  16743. change: e => {
  16744. const event = {
  16745. type: 'change',
  16746. target: techTracks,
  16747. currentTarget: techTracks,
  16748. srcElement: techTracks
  16749. };
  16750. techTracks.trigger(event);
  16751. // if we are a text track change event, we should also notify the
  16752. // remote text track list. This can potentially cause a false positive
  16753. // if we were to get a change event on a non-remote track and
  16754. // we triggered the event on the remote text track list which doesn't
  16755. // contain that track. However, best practices mean looping through the
  16756. // list of tracks and searching for the appropriate mode value, so,
  16757. // this shouldn't pose an issue
  16758. if (name === 'text') {
  16759. this[REMOTE.remoteText.getterName]().trigger(event);
  16760. }
  16761. },
  16762. addtrack(e) {
  16763. techTracks.addTrack(e.track);
  16764. },
  16765. removetrack(e) {
  16766. techTracks.removeTrack(e.track);
  16767. }
  16768. };
  16769. const removeOldTracks = function () {
  16770. const removeTracks = [];
  16771. for (let i = 0; i < techTracks.length; i++) {
  16772. let found = false;
  16773. for (let j = 0; j < elTracks.length; j++) {
  16774. if (elTracks[j] === techTracks[i]) {
  16775. found = true;
  16776. break;
  16777. }
  16778. }
  16779. if (!found) {
  16780. removeTracks.push(techTracks[i]);
  16781. }
  16782. }
  16783. while (removeTracks.length) {
  16784. techTracks.removeTrack(removeTracks.shift());
  16785. }
  16786. };
  16787. this[props.getterName + 'Listeners_'] = listeners;
  16788. Object.keys(listeners).forEach(eventName => {
  16789. const listener = listeners[eventName];
  16790. elTracks.addEventListener(eventName, listener);
  16791. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  16792. });
  16793. // Remove (native) tracks that are not used anymore
  16794. this.on('loadstart', removeOldTracks);
  16795. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  16796. }
  16797. /**
  16798. * Proxy all native track list events to our track lists if the browser we are playing
  16799. * in supports that type of track list.
  16800. *
  16801. * @private
  16802. */
  16803. proxyNativeTracks_() {
  16804. NORMAL.names.forEach(name => {
  16805. this.proxyNativeTracksForType_(name);
  16806. });
  16807. }
  16808. /**
  16809. * Create the `Html5` Tech's DOM element.
  16810. *
  16811. * @return {Element}
  16812. * The element that gets created.
  16813. */
  16814. createEl() {
  16815. let el = this.options_.tag;
  16816. // Check if this browser supports moving the element into the box.
  16817. // On the iPhone video will break if you move the element,
  16818. // So we have to create a brand new element.
  16819. // If we ingested the player div, we do not need to move the media element.
  16820. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  16821. // If the original tag is still there, clone and remove it.
  16822. if (el) {
  16823. const clone = el.cloneNode(true);
  16824. if (el.parentNode) {
  16825. el.parentNode.insertBefore(clone, el);
  16826. }
  16827. Html5.disposeMediaElement(el);
  16828. el = clone;
  16829. } else {
  16830. el = document.createElement('video');
  16831. // determine if native controls should be used
  16832. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  16833. const attributes = merge({}, tagAttributes);
  16834. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  16835. delete attributes.controls;
  16836. }
  16837. setAttributes(el, Object.assign(attributes, {
  16838. id: this.options_.techId,
  16839. class: 'vjs-tech'
  16840. }));
  16841. }
  16842. el.playerId = this.options_.playerId;
  16843. }
  16844. if (typeof this.options_.preload !== 'undefined') {
  16845. setAttribute(el, 'preload', this.options_.preload);
  16846. }
  16847. if (this.options_.disablePictureInPicture !== undefined) {
  16848. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  16849. }
  16850. // Update specific tag settings, in case they were overridden
  16851. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  16852. // when iOS/Safari or other browsers attempt to autoplay.
  16853. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  16854. for (let i = 0; i < settingsAttrs.length; i++) {
  16855. const attr = settingsAttrs[i];
  16856. const value = this.options_[attr];
  16857. if (typeof value !== 'undefined') {
  16858. if (value) {
  16859. setAttribute(el, attr, attr);
  16860. } else {
  16861. removeAttribute(el, attr);
  16862. }
  16863. el[attr] = value;
  16864. }
  16865. }
  16866. return el;
  16867. }
  16868. /**
  16869. * This will be triggered if the loadstart event has already fired, before videojs was
  16870. * ready. Two known examples of when this can happen are:
  16871. * 1. If we're loading the playback object after it has started loading
  16872. * 2. The media is already playing the (often with autoplay on) then
  16873. *
  16874. * This function will fire another loadstart so that videojs can catchup.
  16875. *
  16876. * @fires Tech#loadstart
  16877. *
  16878. * @return {undefined}
  16879. * returns nothing.
  16880. */
  16881. handleLateInit_(el) {
  16882. if (el.networkState === 0 || el.networkState === 3) {
  16883. // The video element hasn't started loading the source yet
  16884. // or didn't find a source
  16885. return;
  16886. }
  16887. if (el.readyState === 0) {
  16888. // NetworkState is set synchronously BUT loadstart is fired at the
  16889. // end of the current stack, usually before setInterval(fn, 0).
  16890. // So at this point we know loadstart may have already fired or is
  16891. // about to fire, and either way the player hasn't seen it yet.
  16892. // We don't want to fire loadstart prematurely here and cause a
  16893. // double loadstart so we'll wait and see if it happens between now
  16894. // and the next loop, and fire it if not.
  16895. // HOWEVER, we also want to make sure it fires before loadedmetadata
  16896. // which could also happen between now and the next loop, so we'll
  16897. // watch for that also.
  16898. let loadstartFired = false;
  16899. const setLoadstartFired = function () {
  16900. loadstartFired = true;
  16901. };
  16902. this.on('loadstart', setLoadstartFired);
  16903. const triggerLoadstart = function () {
  16904. // We did miss the original loadstart. Make sure the player
  16905. // sees loadstart before loadedmetadata
  16906. if (!loadstartFired) {
  16907. this.trigger('loadstart');
  16908. }
  16909. };
  16910. this.on('loadedmetadata', triggerLoadstart);
  16911. this.ready(function () {
  16912. this.off('loadstart', setLoadstartFired);
  16913. this.off('loadedmetadata', triggerLoadstart);
  16914. if (!loadstartFired) {
  16915. // We did miss the original native loadstart. Fire it now.
  16916. this.trigger('loadstart');
  16917. }
  16918. });
  16919. return;
  16920. }
  16921. // From here on we know that loadstart already fired and we missed it.
  16922. // The other readyState events aren't as much of a problem if we double
  16923. // them, so not going to go to as much trouble as loadstart to prevent
  16924. // that unless we find reason to.
  16925. const eventsToTrigger = ['loadstart'];
  16926. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  16927. eventsToTrigger.push('loadedmetadata');
  16928. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  16929. if (el.readyState >= 2) {
  16930. eventsToTrigger.push('loadeddata');
  16931. }
  16932. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  16933. if (el.readyState >= 3) {
  16934. eventsToTrigger.push('canplay');
  16935. }
  16936. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  16937. if (el.readyState >= 4) {
  16938. eventsToTrigger.push('canplaythrough');
  16939. }
  16940. // We still need to give the player time to add event listeners
  16941. this.ready(function () {
  16942. eventsToTrigger.forEach(function (type) {
  16943. this.trigger(type);
  16944. }, this);
  16945. });
  16946. }
  16947. /**
  16948. * Set whether we are scrubbing or not.
  16949. * This is used to decide whether we should use `fastSeek` or not.
  16950. * `fastSeek` is used to provide trick play on Safari browsers.
  16951. *
  16952. * @param {boolean} isScrubbing
  16953. * - true for we are currently scrubbing
  16954. * - false for we are no longer scrubbing
  16955. */
  16956. setScrubbing(isScrubbing) {
  16957. this.isScrubbing_ = isScrubbing;
  16958. }
  16959. /**
  16960. * Get whether we are scrubbing or not.
  16961. *
  16962. * @return {boolean} isScrubbing
  16963. * - true for we are currently scrubbing
  16964. * - false for we are no longer scrubbing
  16965. */
  16966. scrubbing() {
  16967. return this.isScrubbing_;
  16968. }
  16969. /**
  16970. * Set current time for the `HTML5` tech.
  16971. *
  16972. * @param {number} seconds
  16973. * Set the current time of the media to this.
  16974. */
  16975. setCurrentTime(seconds) {
  16976. try {
  16977. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  16978. this.el_.fastSeek(seconds);
  16979. } else {
  16980. this.el_.currentTime = seconds;
  16981. }
  16982. } catch (e) {
  16983. log(e, 'Video is not ready. (Video.js)');
  16984. // this.warning(VideoJS.warnings.videoNotReady);
  16985. }
  16986. }
  16987. /**
  16988. * Get the current duration of the HTML5 media element.
  16989. *
  16990. * @return {number}
  16991. * The duration of the media or 0 if there is no duration.
  16992. */
  16993. duration() {
  16994. // Android Chrome will report duration as Infinity for VOD HLS until after
  16995. // playback has started, which triggers the live display erroneously.
  16996. // Return NaN if playback has not started and trigger a durationupdate once
  16997. // the duration can be reliably known.
  16998. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  16999. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17000. // several with 0
  17001. const checkProgress = () => {
  17002. if (this.el_.currentTime > 0) {
  17003. // Trigger durationchange for genuinely live video
  17004. if (this.el_.duration === Infinity) {
  17005. this.trigger('durationchange');
  17006. }
  17007. this.off('timeupdate', checkProgress);
  17008. }
  17009. };
  17010. this.on('timeupdate', checkProgress);
  17011. return NaN;
  17012. }
  17013. return this.el_.duration || NaN;
  17014. }
  17015. /**
  17016. * Get the current width of the HTML5 media element.
  17017. *
  17018. * @return {number}
  17019. * The width of the HTML5 media element.
  17020. */
  17021. width() {
  17022. return this.el_.offsetWidth;
  17023. }
  17024. /**
  17025. * Get the current height of the HTML5 media element.
  17026. *
  17027. * @return {number}
  17028. * The height of the HTML5 media element.
  17029. */
  17030. height() {
  17031. return this.el_.offsetHeight;
  17032. }
  17033. /**
  17034. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17035. * `fullscreenchange` event.
  17036. *
  17037. * @private
  17038. * @fires fullscreenchange
  17039. * @listens webkitendfullscreen
  17040. * @listens webkitbeginfullscreen
  17041. * @listens webkitbeginfullscreen
  17042. */
  17043. proxyWebkitFullscreen_() {
  17044. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17045. return;
  17046. }
  17047. const endFn = function () {
  17048. this.trigger('fullscreenchange', {
  17049. isFullscreen: false
  17050. });
  17051. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  17052. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17053. this.el_.controls = false;
  17054. }
  17055. };
  17056. const beginFn = function () {
  17057. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17058. this.one('webkitendfullscreen', endFn);
  17059. this.trigger('fullscreenchange', {
  17060. isFullscreen: true,
  17061. // set a flag in case another tech triggers fullscreenchange
  17062. nativeIOSFullscreen: true
  17063. });
  17064. }
  17065. };
  17066. this.on('webkitbeginfullscreen', beginFn);
  17067. this.on('dispose', () => {
  17068. this.off('webkitbeginfullscreen', beginFn);
  17069. this.off('webkitendfullscreen', endFn);
  17070. });
  17071. }
  17072. /**
  17073. * Check if fullscreen is supported on the video el.
  17074. *
  17075. * @return {boolean}
  17076. * - True if fullscreen is supported.
  17077. * - False if fullscreen is not supported.
  17078. */
  17079. supportsFullScreen() {
  17080. return typeof this.el_.webkitEnterFullScreen === 'function';
  17081. }
  17082. /**
  17083. * Request that the `HTML5` Tech enter fullscreen.
  17084. */
  17085. enterFullScreen() {
  17086. const video = this.el_;
  17087. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17088. // attempt to prime the video element for programmatic access
  17089. // this isn't necessary on the desktop but shouldn't hurt
  17090. silencePromise(this.el_.play());
  17091. // playing and pausing synchronously during the transition to fullscreen
  17092. // can get iOS ~6.1 devices into a play/pause loop
  17093. this.setTimeout(function () {
  17094. video.pause();
  17095. try {
  17096. video.webkitEnterFullScreen();
  17097. } catch (e) {
  17098. this.trigger('fullscreenerror', e);
  17099. }
  17100. }, 0);
  17101. } else {
  17102. try {
  17103. video.webkitEnterFullScreen();
  17104. } catch (e) {
  17105. this.trigger('fullscreenerror', e);
  17106. }
  17107. }
  17108. }
  17109. /**
  17110. * Request that the `HTML5` Tech exit fullscreen.
  17111. */
  17112. exitFullScreen() {
  17113. if (!this.el_.webkitDisplayingFullscreen) {
  17114. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  17115. return;
  17116. }
  17117. this.el_.webkitExitFullScreen();
  17118. }
  17119. /**
  17120. * Create a floating video window always on top of other windows so that users may
  17121. * continue consuming media while they interact with other content sites, or
  17122. * applications on their device.
  17123. *
  17124. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  17125. *
  17126. * @return {Promise}
  17127. * A promise with a Picture-in-Picture window.
  17128. */
  17129. requestPictureInPicture() {
  17130. return this.el_.requestPictureInPicture();
  17131. }
  17132. /**
  17133. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  17134. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  17135. * Needs to be checked later than the constructor
  17136. * This will be a false positive for clear sources loaded after a Fairplay source
  17137. *
  17138. * @param {function} cb function to call
  17139. * @return {number} id of request
  17140. */
  17141. requestVideoFrameCallback(cb) {
  17142. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17143. return this.el_.requestVideoFrameCallback(cb);
  17144. }
  17145. return super.requestVideoFrameCallback(cb);
  17146. }
  17147. /**
  17148. * Native or fallback requestVideoFrameCallback
  17149. *
  17150. * @param {number} id request id to cancel
  17151. */
  17152. cancelVideoFrameCallback(id) {
  17153. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17154. this.el_.cancelVideoFrameCallback(id);
  17155. } else {
  17156. super.cancelVideoFrameCallback(id);
  17157. }
  17158. }
  17159. /**
  17160. * A getter/setter for the `Html5` Tech's source object.
  17161. * > Note: Please use {@link Html5#setSource}
  17162. *
  17163. * @param {Tech~SourceObject} [src]
  17164. * The source object you want to set on the `HTML5` techs element.
  17165. *
  17166. * @return {Tech~SourceObject|undefined}
  17167. * - The current source object when a source is not passed in.
  17168. * - undefined when setting
  17169. *
  17170. * @deprecated Since version 5.
  17171. */
  17172. src(src) {
  17173. if (src === undefined) {
  17174. return this.el_.src;
  17175. }
  17176. // Setting src through `src` instead of `setSrc` will be deprecated
  17177. this.setSrc(src);
  17178. }
  17179. /**
  17180. * Reset the tech by removing all sources and then calling
  17181. * {@link Html5.resetMediaElement}.
  17182. */
  17183. reset() {
  17184. Html5.resetMediaElement(this.el_);
  17185. }
  17186. /**
  17187. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  17188. * the HTML5 media element.
  17189. *
  17190. * @return {Tech~SourceObject}
  17191. * The current source object from the HTML5 tech. With a fallback to the
  17192. * elements source.
  17193. */
  17194. currentSrc() {
  17195. if (this.currentSource_) {
  17196. return this.currentSource_.src;
  17197. }
  17198. return this.el_.currentSrc;
  17199. }
  17200. /**
  17201. * Set controls attribute for the HTML5 media Element.
  17202. *
  17203. * @param {string} val
  17204. * Value to set the controls attribute to
  17205. */
  17206. setControls(val) {
  17207. this.el_.controls = !!val;
  17208. }
  17209. /**
  17210. * Create and returns a remote {@link TextTrack} object.
  17211. *
  17212. * @param {string} kind
  17213. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  17214. *
  17215. * @param {string} [label]
  17216. * Label to identify the text track
  17217. *
  17218. * @param {string} [language]
  17219. * Two letter language abbreviation
  17220. *
  17221. * @return {TextTrack}
  17222. * The TextTrack that gets created.
  17223. */
  17224. addTextTrack(kind, label, language) {
  17225. if (!this.featuresNativeTextTracks) {
  17226. return super.addTextTrack(kind, label, language);
  17227. }
  17228. return this.el_.addTextTrack(kind, label, language);
  17229. }
  17230. /**
  17231. * Creates either native TextTrack or an emulated TextTrack depending
  17232. * on the value of `featuresNativeTextTracks`
  17233. *
  17234. * @param {Object} options
  17235. * The object should contain the options to initialize the TextTrack with.
  17236. *
  17237. * @param {string} [options.kind]
  17238. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  17239. *
  17240. * @param {string} [options.label]
  17241. * Label to identify the text track
  17242. *
  17243. * @param {string} [options.language]
  17244. * Two letter language abbreviation.
  17245. *
  17246. * @param {boolean} [options.default]
  17247. * Default this track to on.
  17248. *
  17249. * @param {string} [options.id]
  17250. * The internal id to assign this track.
  17251. *
  17252. * @param {string} [options.src]
  17253. * A source url for the track.
  17254. *
  17255. * @return {HTMLTrackElement}
  17256. * The track element that gets created.
  17257. */
  17258. createRemoteTextTrack(options) {
  17259. if (!this.featuresNativeTextTracks) {
  17260. return super.createRemoteTextTrack(options);
  17261. }
  17262. const htmlTrackElement = document.createElement('track');
  17263. if (options.kind) {
  17264. htmlTrackElement.kind = options.kind;
  17265. }
  17266. if (options.label) {
  17267. htmlTrackElement.label = options.label;
  17268. }
  17269. if (options.language || options.srclang) {
  17270. htmlTrackElement.srclang = options.language || options.srclang;
  17271. }
  17272. if (options.default) {
  17273. htmlTrackElement.default = options.default;
  17274. }
  17275. if (options.id) {
  17276. htmlTrackElement.id = options.id;
  17277. }
  17278. if (options.src) {
  17279. htmlTrackElement.src = options.src;
  17280. }
  17281. return htmlTrackElement;
  17282. }
  17283. /**
  17284. * Creates a remote text track object and returns an html track element.
  17285. *
  17286. * @param {Object} options The object should contain values for
  17287. * kind, language, label, and src (location of the WebVTT file)
  17288. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  17289. * will not be removed from the TextTrackList and HtmlTrackElementList
  17290. * after a source change
  17291. * @return {HTMLTrackElement} An Html Track Element.
  17292. * This can be an emulated {@link HTMLTrackElement} or a native one.
  17293. *
  17294. */
  17295. addRemoteTextTrack(options, manualCleanup) {
  17296. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  17297. if (this.featuresNativeTextTracks) {
  17298. this.el().appendChild(htmlTrackElement);
  17299. }
  17300. return htmlTrackElement;
  17301. }
  17302. /**
  17303. * Remove remote `TextTrack` from `TextTrackList` object
  17304. *
  17305. * @param {TextTrack} track
  17306. * `TextTrack` object to remove
  17307. */
  17308. removeRemoteTextTrack(track) {
  17309. super.removeRemoteTextTrack(track);
  17310. if (this.featuresNativeTextTracks) {
  17311. const tracks = this.$$('track');
  17312. let i = tracks.length;
  17313. while (i--) {
  17314. if (track === tracks[i] || track === tracks[i].track) {
  17315. this.el().removeChild(tracks[i]);
  17316. }
  17317. }
  17318. }
  17319. }
  17320. /**
  17321. * Gets available media playback quality metrics as specified by the W3C's Media
  17322. * Playback Quality API.
  17323. *
  17324. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  17325. *
  17326. * @return {Object}
  17327. * An object with supported media playback quality metrics
  17328. */
  17329. getVideoPlaybackQuality() {
  17330. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  17331. return this.el().getVideoPlaybackQuality();
  17332. }
  17333. const videoPlaybackQuality = {};
  17334. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  17335. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  17336. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  17337. }
  17338. if (window.performance) {
  17339. videoPlaybackQuality.creationTime = window.performance.now();
  17340. }
  17341. return videoPlaybackQuality;
  17342. }
  17343. }
  17344. /* HTML5 Support Testing ---------------------------------------------------- */
  17345. /**
  17346. * Element for testing browser HTML5 media capabilities
  17347. *
  17348. * @type {Element}
  17349. * @constant
  17350. * @private
  17351. */
  17352. defineLazyProperty(Html5, 'TEST_VID', function () {
  17353. if (!isReal()) {
  17354. return;
  17355. }
  17356. const video = document.createElement('video');
  17357. const track = document.createElement('track');
  17358. track.kind = 'captions';
  17359. track.srclang = 'en';
  17360. track.label = 'English';
  17361. video.appendChild(track);
  17362. return video;
  17363. });
  17364. /**
  17365. * Check if HTML5 media is supported by this browser/device.
  17366. *
  17367. * @return {boolean}
  17368. * - True if HTML5 media is supported.
  17369. * - False if HTML5 media is not supported.
  17370. */
  17371. Html5.isSupported = function () {
  17372. // IE with no Media Player is a LIAR! (#984)
  17373. try {
  17374. Html5.TEST_VID.volume = 0.5;
  17375. } catch (e) {
  17376. return false;
  17377. }
  17378. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  17379. };
  17380. /**
  17381. * Check if the tech can support the given type
  17382. *
  17383. * @param {string} type
  17384. * The mimetype to check
  17385. * @return {string} 'probably', 'maybe', or '' (empty string)
  17386. */
  17387. Html5.canPlayType = function (type) {
  17388. return Html5.TEST_VID.canPlayType(type);
  17389. };
  17390. /**
  17391. * Check if the tech can support the given source
  17392. *
  17393. * @param {Object} srcObj
  17394. * The source object
  17395. * @param {Object} options
  17396. * The options passed to the tech
  17397. * @return {string} 'probably', 'maybe', or '' (empty string)
  17398. */
  17399. Html5.canPlaySource = function (srcObj, options) {
  17400. return Html5.canPlayType(srcObj.type);
  17401. };
  17402. /**
  17403. * Check if the volume can be changed in this browser/device.
  17404. * Volume cannot be changed in a lot of mobile devices.
  17405. * Specifically, it can't be changed from 1 on iOS.
  17406. *
  17407. * @return {boolean}
  17408. * - True if volume can be controlled
  17409. * - False otherwise
  17410. */
  17411. Html5.canControlVolume = function () {
  17412. // IE will error if Windows Media Player not installed #3315
  17413. try {
  17414. const volume = Html5.TEST_VID.volume;
  17415. Html5.TEST_VID.volume = volume / 2 + 0.1;
  17416. const canControl = volume !== Html5.TEST_VID.volume;
  17417. // With the introduction of iOS 15, there are cases where the volume is read as
  17418. // changed but reverts back to its original state at the start of the next tick.
  17419. // To determine whether volume can be controlled on iOS,
  17420. // a timeout is set and the volume is checked asynchronously.
  17421. // Since `features` doesn't currently work asynchronously, the value is manually set.
  17422. if (canControl && IS_IOS) {
  17423. window.setTimeout(() => {
  17424. if (Html5 && Html5.prototype) {
  17425. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  17426. }
  17427. });
  17428. // default iOS to false, which will be updated in the timeout above.
  17429. return false;
  17430. }
  17431. return canControl;
  17432. } catch (e) {
  17433. return false;
  17434. }
  17435. };
  17436. /**
  17437. * Check if the volume can be muted in this browser/device.
  17438. * Some devices, e.g. iOS, don't allow changing volume
  17439. * but permits muting/unmuting.
  17440. *
  17441. * @return {boolean}
  17442. * - True if volume can be muted
  17443. * - False otherwise
  17444. */
  17445. Html5.canMuteVolume = function () {
  17446. try {
  17447. const muted = Html5.TEST_VID.muted;
  17448. // in some versions of iOS muted property doesn't always
  17449. // work, so we want to set both property and attribute
  17450. Html5.TEST_VID.muted = !muted;
  17451. if (Html5.TEST_VID.muted) {
  17452. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  17453. } else {
  17454. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  17455. }
  17456. return muted !== Html5.TEST_VID.muted;
  17457. } catch (e) {
  17458. return false;
  17459. }
  17460. };
  17461. /**
  17462. * Check if the playback rate can be changed in this browser/device.
  17463. *
  17464. * @return {boolean}
  17465. * - True if playback rate can be controlled
  17466. * - False otherwise
  17467. */
  17468. Html5.canControlPlaybackRate = function () {
  17469. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  17470. // https://github.com/videojs/video.js/issues/3180
  17471. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  17472. return false;
  17473. }
  17474. // IE will error if Windows Media Player not installed #3315
  17475. try {
  17476. const playbackRate = Html5.TEST_VID.playbackRate;
  17477. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  17478. return playbackRate !== Html5.TEST_VID.playbackRate;
  17479. } catch (e) {
  17480. return false;
  17481. }
  17482. };
  17483. /**
  17484. * Check if we can override a video/audio elements attributes, with
  17485. * Object.defineProperty.
  17486. *
  17487. * @return {boolean}
  17488. * - True if builtin attributes can be overridden
  17489. * - False otherwise
  17490. */
  17491. Html5.canOverrideAttributes = function () {
  17492. // if we cannot overwrite the src/innerHTML property, there is no support
  17493. // iOS 7 safari for instance cannot do this.
  17494. try {
  17495. const noop = () => {};
  17496. Object.defineProperty(document.createElement('video'), 'src', {
  17497. get: noop,
  17498. set: noop
  17499. });
  17500. Object.defineProperty(document.createElement('audio'), 'src', {
  17501. get: noop,
  17502. set: noop
  17503. });
  17504. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  17505. get: noop,
  17506. set: noop
  17507. });
  17508. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  17509. get: noop,
  17510. set: noop
  17511. });
  17512. } catch (e) {
  17513. return false;
  17514. }
  17515. return true;
  17516. };
  17517. /**
  17518. * Check to see if native `TextTrack`s are supported by this browser/device.
  17519. *
  17520. * @return {boolean}
  17521. * - True if native `TextTrack`s are supported.
  17522. * - False otherwise
  17523. */
  17524. Html5.supportsNativeTextTracks = function () {
  17525. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  17526. };
  17527. /**
  17528. * Check to see if native `VideoTrack`s are supported by this browser/device
  17529. *
  17530. * @return {boolean}
  17531. * - True if native `VideoTrack`s are supported.
  17532. * - False otherwise
  17533. */
  17534. Html5.supportsNativeVideoTracks = function () {
  17535. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  17536. };
  17537. /**
  17538. * Check to see if native `AudioTrack`s are supported by this browser/device
  17539. *
  17540. * @return {boolean}
  17541. * - True if native `AudioTrack`s are supported.
  17542. * - False otherwise
  17543. */
  17544. Html5.supportsNativeAudioTracks = function () {
  17545. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  17546. };
  17547. /**
  17548. * An array of events available on the Html5 tech.
  17549. *
  17550. * @private
  17551. * @type {Array}
  17552. */
  17553. Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
  17554. /**
  17555. * Boolean indicating whether the `Tech` supports volume control.
  17556. *
  17557. * @type {boolean}
  17558. * @default {@link Html5.canControlVolume}
  17559. */
  17560. /**
  17561. * Boolean indicating whether the `Tech` supports muting volume.
  17562. *
  17563. * @type {boolean}
  17564. * @default {@link Html5.canMuteVolume}
  17565. */
  17566. /**
  17567. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  17568. * plays. Examples:
  17569. * - Set player to play 2x (twice) as fast
  17570. * - Set player to play 0.5x (half) as fast
  17571. *
  17572. * @type {boolean}
  17573. * @default {@link Html5.canControlPlaybackRate}
  17574. */
  17575. /**
  17576. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  17577. *
  17578. * @type {boolean}
  17579. * @default
  17580. */
  17581. /**
  17582. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  17583. *
  17584. * @type {boolean}
  17585. * @default {@link Html5.supportsNativeTextTracks}
  17586. */
  17587. /**
  17588. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  17589. *
  17590. * @type {boolean}
  17591. * @default {@link Html5.supportsNativeVideoTracks}
  17592. */
  17593. /**
  17594. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  17595. *
  17596. * @type {boolean}
  17597. * @default {@link Html5.supportsNativeAudioTracks}
  17598. */
  17599. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  17600. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  17601. });
  17602. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  17603. /**
  17604. * Boolean indicating whether the `HTML5` tech currently supports the media element
  17605. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  17606. * false there. Everywhere else this should be true.
  17607. *
  17608. * @type {boolean}
  17609. * @default
  17610. */
  17611. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  17612. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  17613. // Is this true?
  17614. /**
  17615. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  17616. * when going into fullscreen.
  17617. *
  17618. * @type {boolean}
  17619. * @default
  17620. */
  17621. Html5.prototype.featuresFullscreenResize = true;
  17622. /**
  17623. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  17624. * If this is false, manual `progress` events will be triggered instead.
  17625. *
  17626. * @type {boolean}
  17627. * @default
  17628. */
  17629. Html5.prototype.featuresProgressEvents = true;
  17630. /**
  17631. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  17632. * If this is false, manual `timeupdate` events will be triggered instead.
  17633. *
  17634. * @default
  17635. */
  17636. Html5.prototype.featuresTimeupdateEvents = true;
  17637. /**
  17638. * Whether the HTML5 el supports `requestVideoFrameCallback`
  17639. *
  17640. * @type {boolean}
  17641. */
  17642. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  17643. Html5.disposeMediaElement = function (el) {
  17644. if (!el) {
  17645. return;
  17646. }
  17647. if (el.parentNode) {
  17648. el.parentNode.removeChild(el);
  17649. }
  17650. // remove any child track or source nodes to prevent their loading
  17651. while (el.hasChildNodes()) {
  17652. el.removeChild(el.firstChild);
  17653. }
  17654. // remove any src reference. not setting `src=''` because that causes a warning
  17655. // in firefox
  17656. el.removeAttribute('src');
  17657. // force the media element to update its loading state by calling load()
  17658. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  17659. if (typeof el.load === 'function') {
  17660. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17661. (function () {
  17662. try {
  17663. el.load();
  17664. } catch (e) {
  17665. // not supported
  17666. }
  17667. })();
  17668. }
  17669. };
  17670. Html5.resetMediaElement = function (el) {
  17671. if (!el) {
  17672. return;
  17673. }
  17674. const sources = el.querySelectorAll('source');
  17675. let i = sources.length;
  17676. while (i--) {
  17677. el.removeChild(sources[i]);
  17678. }
  17679. // remove any src reference.
  17680. // not setting `src=''` because that throws an error
  17681. el.removeAttribute('src');
  17682. if (typeof el.load === 'function') {
  17683. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17684. (function () {
  17685. try {
  17686. el.load();
  17687. } catch (e) {
  17688. // satisfy linter
  17689. }
  17690. })();
  17691. }
  17692. };
  17693. /* Native HTML5 element property wrapping ----------------------------------- */
  17694. // Wrap native boolean attributes with getters that check both property and attribute
  17695. // The list is as followed:
  17696. // muted, defaultMuted, autoplay, controls, loop, playsinline
  17697. [
  17698. /**
  17699. * Get the value of `muted` from the media element. `muted` indicates
  17700. * that the volume for the media should be set to silent. This does not actually change
  17701. * the `volume` attribute.
  17702. *
  17703. * @method Html5#muted
  17704. * @return {boolean}
  17705. * - True if the value of `volume` should be ignored and the audio set to silent.
  17706. * - False if the value of `volume` should be used.
  17707. *
  17708. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17709. */
  17710. 'muted',
  17711. /**
  17712. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  17713. * whether the media should start muted or not. Only changes the default state of the
  17714. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  17715. * current state.
  17716. *
  17717. * @method Html5#defaultMuted
  17718. * @return {boolean}
  17719. * - The value of `defaultMuted` from the media element.
  17720. * - True indicates that the media should start muted.
  17721. * - False indicates that the media should not start muted
  17722. *
  17723. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17724. */
  17725. 'defaultMuted',
  17726. /**
  17727. * Get the value of `autoplay` from the media element. `autoplay` indicates
  17728. * that the media should start to play as soon as the page is ready.
  17729. *
  17730. * @method Html5#autoplay
  17731. * @return {boolean}
  17732. * - The value of `autoplay` from the media element.
  17733. * - True indicates that the media should start as soon as the page loads.
  17734. * - False indicates that the media should not start as soon as the page loads.
  17735. *
  17736. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17737. */
  17738. 'autoplay',
  17739. /**
  17740. * Get the value of `controls` from the media element. `controls` indicates
  17741. * whether the native media controls should be shown or hidden.
  17742. *
  17743. * @method Html5#controls
  17744. * @return {boolean}
  17745. * - The value of `controls` from the media element.
  17746. * - True indicates that native controls should be showing.
  17747. * - False indicates that native controls should be hidden.
  17748. *
  17749. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  17750. */
  17751. 'controls',
  17752. /**
  17753. * Get the value of `loop` from the media element. `loop` indicates
  17754. * that the media should return to the start of the media and continue playing once
  17755. * it reaches the end.
  17756. *
  17757. * @method Html5#loop
  17758. * @return {boolean}
  17759. * - The value of `loop` from the media element.
  17760. * - True indicates that playback should seek back to start once
  17761. * the end of a media is reached.
  17762. * - False indicates that playback should not loop back to the start when the
  17763. * end of the media is reached.
  17764. *
  17765. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17766. */
  17767. 'loop',
  17768. /**
  17769. * Get the value of `playsinline` from the media element. `playsinline` indicates
  17770. * to the browser that non-fullscreen playback is preferred when fullscreen
  17771. * playback is the native default, such as in iOS Safari.
  17772. *
  17773. * @method Html5#playsinline
  17774. * @return {boolean}
  17775. * - The value of `playsinline` from the media element.
  17776. * - True indicates that the media should play inline.
  17777. * - False indicates that the media should not play inline.
  17778. *
  17779. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17780. */
  17781. 'playsinline'].forEach(function (prop) {
  17782. Html5.prototype[prop] = function () {
  17783. return this.el_[prop] || this.el_.hasAttribute(prop);
  17784. };
  17785. });
  17786. // Wrap native boolean attributes with setters that set both property and attribute
  17787. // The list is as followed:
  17788. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  17789. // setControls is special-cased above
  17790. [
  17791. /**
  17792. * Set the value of `muted` on the media element. `muted` indicates that the current
  17793. * audio level should be silent.
  17794. *
  17795. * @method Html5#setMuted
  17796. * @param {boolean} muted
  17797. * - True if the audio should be set to silent
  17798. * - False otherwise
  17799. *
  17800. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17801. */
  17802. 'muted',
  17803. /**
  17804. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  17805. * audio level should be silent, but will only effect the muted level on initial playback..
  17806. *
  17807. * @method Html5.prototype.setDefaultMuted
  17808. * @param {boolean} defaultMuted
  17809. * - True if the audio should be set to silent
  17810. * - False otherwise
  17811. *
  17812. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17813. */
  17814. 'defaultMuted',
  17815. /**
  17816. * Set the value of `autoplay` on the media element. `autoplay` indicates
  17817. * that the media should start to play as soon as the page is ready.
  17818. *
  17819. * @method Html5#setAutoplay
  17820. * @param {boolean} autoplay
  17821. * - True indicates that the media should start as soon as the page loads.
  17822. * - False indicates that the media should not start as soon as the page loads.
  17823. *
  17824. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17825. */
  17826. 'autoplay',
  17827. /**
  17828. * Set the value of `loop` on the media element. `loop` indicates
  17829. * that the media should return to the start of the media and continue playing once
  17830. * it reaches the end.
  17831. *
  17832. * @method Html5#setLoop
  17833. * @param {boolean} loop
  17834. * - True indicates that playback should seek back to start once
  17835. * the end of a media is reached.
  17836. * - False indicates that playback should not loop back to the start when the
  17837. * end of the media is reached.
  17838. *
  17839. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17840. */
  17841. 'loop',
  17842. /**
  17843. * Set the value of `playsinline` from the media element. `playsinline` indicates
  17844. * to the browser that non-fullscreen playback is preferred when fullscreen
  17845. * playback is the native default, such as in iOS Safari.
  17846. *
  17847. * @method Html5#setPlaysinline
  17848. * @param {boolean} playsinline
  17849. * - True indicates that the media should play inline.
  17850. * - False indicates that the media should not play inline.
  17851. *
  17852. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17853. */
  17854. 'playsinline'].forEach(function (prop) {
  17855. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  17856. this.el_[prop] = v;
  17857. if (v) {
  17858. this.el_.setAttribute(prop, prop);
  17859. } else {
  17860. this.el_.removeAttribute(prop);
  17861. }
  17862. };
  17863. });
  17864. // Wrap native properties with a getter
  17865. // The list is as followed
  17866. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  17867. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  17868. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  17869. [
  17870. /**
  17871. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  17872. * is currently paused or not.
  17873. *
  17874. * @method Html5#paused
  17875. * @return {boolean}
  17876. * The value of `paused` from the media element.
  17877. *
  17878. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  17879. */
  17880. 'paused',
  17881. /**
  17882. * Get the value of `currentTime` from the media element. `currentTime` indicates
  17883. * the current second that the media is at in playback.
  17884. *
  17885. * @method Html5#currentTime
  17886. * @return {number}
  17887. * The value of `currentTime` from the media element.
  17888. *
  17889. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  17890. */
  17891. 'currentTime',
  17892. /**
  17893. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  17894. * object that represents the parts of the media that are already downloaded and
  17895. * available for playback.
  17896. *
  17897. * @method Html5#buffered
  17898. * @return {TimeRange}
  17899. * The value of `buffered` from the media element.
  17900. *
  17901. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  17902. */
  17903. 'buffered',
  17904. /**
  17905. * Get the value of `volume` from the media element. `volume` indicates
  17906. * the current playback volume of audio for a media. `volume` will be a value from 0
  17907. * (silent) to 1 (loudest and default).
  17908. *
  17909. * @method Html5#volume
  17910. * @return {number}
  17911. * The value of `volume` from the media element. Value will be between 0-1.
  17912. *
  17913. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  17914. */
  17915. 'volume',
  17916. /**
  17917. * Get the value of `poster` from the media element. `poster` indicates
  17918. * that the url of an image file that can/will be shown when no media data is available.
  17919. *
  17920. * @method Html5#poster
  17921. * @return {string}
  17922. * The value of `poster` from the media element. Value will be a url to an
  17923. * image.
  17924. *
  17925. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  17926. */
  17927. 'poster',
  17928. /**
  17929. * Get the value of `preload` from the media element. `preload` indicates
  17930. * what should download before the media is interacted with. It can have the following
  17931. * values:
  17932. * - none: nothing should be downloaded
  17933. * - metadata: poster and the first few frames of the media may be downloaded to get
  17934. * media dimensions and other metadata
  17935. * - auto: allow the media and metadata for the media to be downloaded before
  17936. * interaction
  17937. *
  17938. * @method Html5#preload
  17939. * @return {string}
  17940. * The value of `preload` from the media element. Will be 'none', 'metadata',
  17941. * or 'auto'.
  17942. *
  17943. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  17944. */
  17945. 'preload',
  17946. /**
  17947. * Get the value of the `error` from the media element. `error` indicates any
  17948. * MediaError that may have occurred during playback. If error returns null there is no
  17949. * current error.
  17950. *
  17951. * @method Html5#error
  17952. * @return {MediaError|null}
  17953. * The value of `error` from the media element. Will be `MediaError` if there
  17954. * is a current error and null otherwise.
  17955. *
  17956. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  17957. */
  17958. 'error',
  17959. /**
  17960. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  17961. * media is currently seeking to a new position or not.
  17962. *
  17963. * @method Html5#seeking
  17964. * @return {boolean}
  17965. * - The value of `seeking` from the media element.
  17966. * - True indicates that the media is currently seeking to a new position.
  17967. * - False indicates that the media is not seeking to a new position at this time.
  17968. *
  17969. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  17970. */
  17971. 'seeking',
  17972. /**
  17973. * Get the value of `seekable` from the media element. `seekable` returns a
  17974. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  17975. *
  17976. * @method Html5#seekable
  17977. * @return {TimeRange}
  17978. * The value of `seekable` from the media element. A `TimeRange` object
  17979. * indicating the current ranges of time that can be seeked to.
  17980. *
  17981. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  17982. */
  17983. 'seekable',
  17984. /**
  17985. * Get the value of `ended` from the media element. `ended` indicates whether
  17986. * the media has reached the end or not.
  17987. *
  17988. * @method Html5#ended
  17989. * @return {boolean}
  17990. * - The value of `ended` from the media element.
  17991. * - True indicates that the media has ended.
  17992. * - False indicates that the media has not ended.
  17993. *
  17994. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  17995. */
  17996. 'ended',
  17997. /**
  17998. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  17999. * the rate at which the media is currently playing back. Examples:
  18000. * - if playbackRate is set to 2, media will play twice as fast.
  18001. * - if playbackRate is set to 0.5, media will play half as fast.
  18002. *
  18003. * @method Html5#playbackRate
  18004. * @return {number}
  18005. * The value of `playbackRate` from the media element. A number indicating
  18006. * the current playback speed of the media, where 1 is normal speed.
  18007. *
  18008. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18009. */
  18010. 'playbackRate',
  18011. /**
  18012. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18013. * the rate at which the media is currently playing back. This value will not indicate the current
  18014. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18015. *
  18016. * Examples:
  18017. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18018. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18019. *
  18020. * @method Html5.prototype.defaultPlaybackRate
  18021. * @return {number}
  18022. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18023. * the current playback speed of the media, where 1 is normal speed.
  18024. *
  18025. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18026. */
  18027. 'defaultPlaybackRate',
  18028. /**
  18029. * Get the value of 'disablePictureInPicture' from the video element.
  18030. *
  18031. * @method Html5#disablePictureInPicture
  18032. * @return {boolean} value
  18033. * - The value of `disablePictureInPicture` from the video element.
  18034. * - True indicates that the video can't be played in Picture-In-Picture mode
  18035. * - False indicates that the video can be played in Picture-In-Picture mode
  18036. *
  18037. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18038. */
  18039. 'disablePictureInPicture',
  18040. /**
  18041. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18042. * object representing points in the media timeline that have been played.
  18043. *
  18044. * @method Html5#played
  18045. * @return {TimeRange}
  18046. * The value of `played` from the media element. A `TimeRange` object indicating
  18047. * the ranges of time that have been played.
  18048. *
  18049. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18050. */
  18051. 'played',
  18052. /**
  18053. * Get the value of `networkState` from the media element. `networkState` indicates
  18054. * the current network state. It returns an enumeration from the following list:
  18055. * - 0: NETWORK_EMPTY
  18056. * - 1: NETWORK_IDLE
  18057. * - 2: NETWORK_LOADING
  18058. * - 3: NETWORK_NO_SOURCE
  18059. *
  18060. * @method Html5#networkState
  18061. * @return {number}
  18062. * The value of `networkState` from the media element. This will be a number
  18063. * from the list in the description.
  18064. *
  18065. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18066. */
  18067. 'networkState',
  18068. /**
  18069. * Get the value of `readyState` from the media element. `readyState` indicates
  18070. * the current state of the media element. It returns an enumeration from the
  18071. * following list:
  18072. * - 0: HAVE_NOTHING
  18073. * - 1: HAVE_METADATA
  18074. * - 2: HAVE_CURRENT_DATA
  18075. * - 3: HAVE_FUTURE_DATA
  18076. * - 4: HAVE_ENOUGH_DATA
  18077. *
  18078. * @method Html5#readyState
  18079. * @return {number}
  18080. * The value of `readyState` from the media element. This will be a number
  18081. * from the list in the description.
  18082. *
  18083. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  18084. */
  18085. 'readyState',
  18086. /**
  18087. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  18088. * the current width of the video in css pixels.
  18089. *
  18090. * @method Html5#videoWidth
  18091. * @return {number}
  18092. * The value of `videoWidth` from the video element. This will be a number
  18093. * in css pixels.
  18094. *
  18095. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18096. */
  18097. 'videoWidth',
  18098. /**
  18099. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  18100. * the current height of the video in css pixels.
  18101. *
  18102. * @method Html5#videoHeight
  18103. * @return {number}
  18104. * The value of `videoHeight` from the video element. This will be a number
  18105. * in css pixels.
  18106. *
  18107. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18108. */
  18109. 'videoHeight',
  18110. /**
  18111. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18112. * to the browser that should sent the cookies along with the requests for the
  18113. * different assets/playlists
  18114. *
  18115. * @method Html5#crossOrigin
  18116. * @return {string}
  18117. * - anonymous indicates that the media should not sent cookies.
  18118. * - use-credentials indicates that the media should sent cookies along the requests.
  18119. *
  18120. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18121. */
  18122. 'crossOrigin'].forEach(function (prop) {
  18123. Html5.prototype[prop] = function () {
  18124. return this.el_[prop];
  18125. };
  18126. });
  18127. // Wrap native properties with a setter in this format:
  18128. // set + toTitleCase(name)
  18129. // The list is as follows:
  18130. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  18131. // setDisablePictureInPicture, setCrossOrigin
  18132. [
  18133. /**
  18134. * Set the value of `volume` on the media element. `volume` indicates the current
  18135. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  18136. * so on.
  18137. *
  18138. * @method Html5#setVolume
  18139. * @param {number} percentAsDecimal
  18140. * The volume percent as a decimal. Valid range is from 0-1.
  18141. *
  18142. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18143. */
  18144. 'volume',
  18145. /**
  18146. * Set the value of `src` on the media element. `src` indicates the current
  18147. * {@link Tech~SourceObject} for the media.
  18148. *
  18149. * @method Html5#setSrc
  18150. * @param {Tech~SourceObject} src
  18151. * The source object to set as the current source.
  18152. *
  18153. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  18154. */
  18155. 'src',
  18156. /**
  18157. * Set the value of `poster` on the media element. `poster` is the url to
  18158. * an image file that can/will be shown when no media data is available.
  18159. *
  18160. * @method Html5#setPoster
  18161. * @param {string} poster
  18162. * The url to an image that should be used as the `poster` for the media
  18163. * element.
  18164. *
  18165. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  18166. */
  18167. 'poster',
  18168. /**
  18169. * Set the value of `preload` on the media element. `preload` indicates
  18170. * what should download before the media is interacted with. It can have the following
  18171. * values:
  18172. * - none: nothing should be downloaded
  18173. * - metadata: poster and the first few frames of the media may be downloaded to get
  18174. * media dimensions and other metadata
  18175. * - auto: allow the media and metadata for the media to be downloaded before
  18176. * interaction
  18177. *
  18178. * @method Html5#setPreload
  18179. * @param {string} preload
  18180. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  18181. * or 'auto'.
  18182. *
  18183. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18184. */
  18185. 'preload',
  18186. /**
  18187. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  18188. * the rate at which the media should play back. Examples:
  18189. * - if playbackRate is set to 2, media will play twice as fast.
  18190. * - if playbackRate is set to 0.5, media will play half as fast.
  18191. *
  18192. * @method Html5#setPlaybackRate
  18193. * @return {number}
  18194. * The value of `playbackRate` from the media element. A number indicating
  18195. * the current playback speed of the media, where 1 is normal speed.
  18196. *
  18197. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18198. */
  18199. 'playbackRate',
  18200. /**
  18201. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  18202. * the rate at which the media should play back upon initial startup. Changing this value
  18203. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  18204. *
  18205. * Example Values:
  18206. * - if playbackRate is set to 2, media will play twice as fast.
  18207. * - if playbackRate is set to 0.5, media will play half as fast.
  18208. *
  18209. * @method Html5.prototype.setDefaultPlaybackRate
  18210. * @return {number}
  18211. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18212. * the current playback speed of the media, where 1 is normal speed.
  18213. *
  18214. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  18215. */
  18216. 'defaultPlaybackRate',
  18217. /**
  18218. * Prevents the browser from suggesting a Picture-in-Picture context menu
  18219. * or to request Picture-in-Picture automatically in some cases.
  18220. *
  18221. * @method Html5#setDisablePictureInPicture
  18222. * @param {boolean} value
  18223. * The true value will disable Picture-in-Picture mode.
  18224. *
  18225. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18226. */
  18227. 'disablePictureInPicture',
  18228. /**
  18229. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18230. * to the browser that should sent the cookies along with the requests for the
  18231. * different assets/playlists
  18232. *
  18233. * @method Html5#setCrossOrigin
  18234. * @param {string} crossOrigin
  18235. * - anonymous indicates that the media should not sent cookies.
  18236. * - use-credentials indicates that the media should sent cookies along the requests.
  18237. *
  18238. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18239. */
  18240. 'crossOrigin'].forEach(function (prop) {
  18241. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  18242. this.el_[prop] = v;
  18243. };
  18244. });
  18245. // wrap native functions with a function
  18246. // The list is as follows:
  18247. // pause, load, play
  18248. [
  18249. /**
  18250. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  18251. * media elements `pause` function.
  18252. *
  18253. * @method Html5#pause
  18254. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  18255. */
  18256. 'pause',
  18257. /**
  18258. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  18259. * media element `load` function.
  18260. *
  18261. * @method Html5#load
  18262. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  18263. */
  18264. 'load',
  18265. /**
  18266. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  18267. * media element `play` function.
  18268. *
  18269. * @method Html5#play
  18270. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  18271. */
  18272. 'play'].forEach(function (prop) {
  18273. Html5.prototype[prop] = function () {
  18274. return this.el_[prop]();
  18275. };
  18276. });
  18277. Tech.withSourceHandlers(Html5);
  18278. /**
  18279. * Native source handler for Html5, simply passes the source to the media element.
  18280. *
  18281. * @property {Tech~SourceObject} source
  18282. * The source object
  18283. *
  18284. * @property {Html5} tech
  18285. * The instance of the HTML5 tech.
  18286. */
  18287. Html5.nativeSourceHandler = {};
  18288. /**
  18289. * Check if the media element can play the given mime type.
  18290. *
  18291. * @param {string} type
  18292. * The mimetype to check
  18293. *
  18294. * @return {string}
  18295. * 'probably', 'maybe', or '' (empty string)
  18296. */
  18297. Html5.nativeSourceHandler.canPlayType = function (type) {
  18298. // IE without MediaPlayer throws an error (#519)
  18299. try {
  18300. return Html5.TEST_VID.canPlayType(type);
  18301. } catch (e) {
  18302. return '';
  18303. }
  18304. };
  18305. /**
  18306. * Check if the media element can handle a source natively.
  18307. *
  18308. * @param {Tech~SourceObject} source
  18309. * The source object
  18310. *
  18311. * @param {Object} [options]
  18312. * Options to be passed to the tech.
  18313. *
  18314. * @return {string}
  18315. * 'probably', 'maybe', or '' (empty string).
  18316. */
  18317. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  18318. // If a type was provided we should rely on that
  18319. if (source.type) {
  18320. return Html5.nativeSourceHandler.canPlayType(source.type);
  18321. // If no type, fall back to checking 'video/[EXTENSION]'
  18322. } else if (source.src) {
  18323. const ext = getFileExtension(source.src);
  18324. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  18325. }
  18326. return '';
  18327. };
  18328. /**
  18329. * Pass the source to the native media element.
  18330. *
  18331. * @param {Tech~SourceObject} source
  18332. * The source object
  18333. *
  18334. * @param {Html5} tech
  18335. * The instance of the Html5 tech
  18336. *
  18337. * @param {Object} [options]
  18338. * The options to pass to the source
  18339. */
  18340. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  18341. tech.setSrc(source.src);
  18342. };
  18343. /**
  18344. * A noop for the native dispose function, as cleanup is not needed.
  18345. */
  18346. Html5.nativeSourceHandler.dispose = function () {};
  18347. // Register the native source handler
  18348. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  18349. Tech.registerTech('Html5', Html5);
  18350. /**
  18351. * @file player.js
  18352. */
  18353. // The following tech events are simply re-triggered
  18354. // on the player when they happen
  18355. const TECH_EVENTS_RETRIGGER = [
  18356. /**
  18357. * Fired while the user agent is downloading media data.
  18358. *
  18359. * @event Player#progress
  18360. * @type {Event}
  18361. */
  18362. /**
  18363. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  18364. *
  18365. * @private
  18366. * @method Player#handleTechProgress_
  18367. * @fires Player#progress
  18368. * @listens Tech#progress
  18369. */
  18370. 'progress',
  18371. /**
  18372. * Fires when the loading of an audio/video is aborted.
  18373. *
  18374. * @event Player#abort
  18375. * @type {Event}
  18376. */
  18377. /**
  18378. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  18379. *
  18380. * @private
  18381. * @method Player#handleTechAbort_
  18382. * @fires Player#abort
  18383. * @listens Tech#abort
  18384. */
  18385. 'abort',
  18386. /**
  18387. * Fires when the browser is intentionally not getting media data.
  18388. *
  18389. * @event Player#suspend
  18390. * @type {Event}
  18391. */
  18392. /**
  18393. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  18394. *
  18395. * @private
  18396. * @method Player#handleTechSuspend_
  18397. * @fires Player#suspend
  18398. * @listens Tech#suspend
  18399. */
  18400. 'suspend',
  18401. /**
  18402. * Fires when the current playlist is empty.
  18403. *
  18404. * @event Player#emptied
  18405. * @type {Event}
  18406. */
  18407. /**
  18408. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  18409. *
  18410. * @private
  18411. * @method Player#handleTechEmptied_
  18412. * @fires Player#emptied
  18413. * @listens Tech#emptied
  18414. */
  18415. 'emptied',
  18416. /**
  18417. * Fires when the browser is trying to get media data, but data is not available.
  18418. *
  18419. * @event Player#stalled
  18420. * @type {Event}
  18421. */
  18422. /**
  18423. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  18424. *
  18425. * @private
  18426. * @method Player#handleTechStalled_
  18427. * @fires Player#stalled
  18428. * @listens Tech#stalled
  18429. */
  18430. 'stalled',
  18431. /**
  18432. * Fires when the browser has loaded meta data for the audio/video.
  18433. *
  18434. * @event Player#loadedmetadata
  18435. * @type {Event}
  18436. */
  18437. /**
  18438. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  18439. *
  18440. * @private
  18441. * @method Player#handleTechLoadedmetadata_
  18442. * @fires Player#loadedmetadata
  18443. * @listens Tech#loadedmetadata
  18444. */
  18445. 'loadedmetadata',
  18446. /**
  18447. * Fires when the browser has loaded the current frame of the audio/video.
  18448. *
  18449. * @event Player#loadeddata
  18450. * @type {event}
  18451. */
  18452. /**
  18453. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  18454. *
  18455. * @private
  18456. * @method Player#handleTechLoaddeddata_
  18457. * @fires Player#loadeddata
  18458. * @listens Tech#loadeddata
  18459. */
  18460. 'loadeddata',
  18461. /**
  18462. * Fires when the current playback position has changed.
  18463. *
  18464. * @event Player#timeupdate
  18465. * @type {event}
  18466. */
  18467. /**
  18468. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  18469. *
  18470. * @private
  18471. * @method Player#handleTechTimeUpdate_
  18472. * @fires Player#timeupdate
  18473. * @listens Tech#timeupdate
  18474. */
  18475. 'timeupdate',
  18476. /**
  18477. * Fires when the video's intrinsic dimensions change
  18478. *
  18479. * @event Player#resize
  18480. * @type {event}
  18481. */
  18482. /**
  18483. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  18484. *
  18485. * @private
  18486. * @method Player#handleTechResize_
  18487. * @fires Player#resize
  18488. * @listens Tech#resize
  18489. */
  18490. 'resize',
  18491. /**
  18492. * Fires when the volume has been changed
  18493. *
  18494. * @event Player#volumechange
  18495. * @type {event}
  18496. */
  18497. /**
  18498. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  18499. *
  18500. * @private
  18501. * @method Player#handleTechVolumechange_
  18502. * @fires Player#volumechange
  18503. * @listens Tech#volumechange
  18504. */
  18505. 'volumechange',
  18506. /**
  18507. * Fires when the text track has been changed
  18508. *
  18509. * @event Player#texttrackchange
  18510. * @type {event}
  18511. */
  18512. /**
  18513. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  18514. *
  18515. * @private
  18516. * @method Player#handleTechTexttrackchange_
  18517. * @fires Player#texttrackchange
  18518. * @listens Tech#texttrackchange
  18519. */
  18520. 'texttrackchange'];
  18521. // events to queue when playback rate is zero
  18522. // this is a hash for the sole purpose of mapping non-camel-cased event names
  18523. // to camel-cased function names
  18524. const TECH_EVENTS_QUEUE = {
  18525. canplay: 'CanPlay',
  18526. canplaythrough: 'CanPlayThrough',
  18527. playing: 'Playing',
  18528. seeked: 'Seeked'
  18529. };
  18530. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  18531. const BREAKPOINT_CLASSES = {};
  18532. // grep: vjs-layout-tiny
  18533. // grep: vjs-layout-x-small
  18534. // grep: vjs-layout-small
  18535. // grep: vjs-layout-medium
  18536. // grep: vjs-layout-large
  18537. // grep: vjs-layout-x-large
  18538. // grep: vjs-layout-huge
  18539. BREAKPOINT_ORDER.forEach(k => {
  18540. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  18541. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  18542. });
  18543. const DEFAULT_BREAKPOINTS = {
  18544. tiny: 210,
  18545. xsmall: 320,
  18546. small: 425,
  18547. medium: 768,
  18548. large: 1440,
  18549. xlarge: 2560,
  18550. huge: Infinity
  18551. };
  18552. /**
  18553. * An instance of the `Player` class is created when any of the Video.js setup methods
  18554. * are used to initialize a video.
  18555. *
  18556. * After an instance has been created it can be accessed globally in three ways:
  18557. * 1. By calling `videojs.getPlayer('example_video_1');`
  18558. * 2. By calling `videojs('example_video_1');` (not recomended)
  18559. * 2. By using it directly via `videojs.players.example_video_1;`
  18560. *
  18561. * @extends Component
  18562. * @global
  18563. */
  18564. class Player extends Component {
  18565. /**
  18566. * Create an instance of this class.
  18567. *
  18568. * @param {Element} tag
  18569. * The original video DOM element used for configuring options.
  18570. *
  18571. * @param {Object} [options]
  18572. * Object of option names and values.
  18573. *
  18574. * @param {Function} [ready]
  18575. * Ready callback function.
  18576. */
  18577. constructor(tag, options, ready) {
  18578. // Make sure tag ID exists
  18579. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  18580. // Set Options
  18581. // The options argument overrides options set in the video tag
  18582. // which overrides globally set options.
  18583. // This latter part coincides with the load order
  18584. // (tag must exist before Player)
  18585. options = Object.assign(Player.getTagSettings(tag), options);
  18586. // Delay the initialization of children because we need to set up
  18587. // player properties first, and can't use `this` before `super()`
  18588. options.initChildren = false;
  18589. // Same with creating the element
  18590. options.createEl = false;
  18591. // don't auto mixin the evented mixin
  18592. options.evented = false;
  18593. // we don't want the player to report touch activity on itself
  18594. // see enableTouchActivity in Component
  18595. options.reportTouchActivity = false;
  18596. // If language is not set, get the closest lang attribute
  18597. if (!options.language) {
  18598. const closest = tag.closest('[lang]');
  18599. if (closest) {
  18600. options.language = closest.getAttribute('lang');
  18601. }
  18602. }
  18603. // Run base component initializing with new options
  18604. super(null, options, ready);
  18605. // Create bound methods for document listeners.
  18606. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  18607. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  18608. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  18609. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  18610. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  18611. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  18612. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  18613. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  18614. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  18615. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  18616. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  18617. // default isFullscreen_ to false
  18618. this.isFullscreen_ = false;
  18619. // create logger
  18620. this.log = createLogger(this.id_);
  18621. // Hold our own reference to fullscreen api so it can be mocked in tests
  18622. this.fsApi_ = FullscreenApi;
  18623. // Tracks when a tech changes the poster
  18624. this.isPosterFromTech_ = false;
  18625. // Holds callback info that gets queued when playback rate is zero
  18626. // and a seek is happening
  18627. this.queuedCallbacks_ = [];
  18628. // Turn off API access because we're loading a new tech that might load asynchronously
  18629. this.isReady_ = false;
  18630. // Init state hasStarted_
  18631. this.hasStarted_ = false;
  18632. // Init state userActive_
  18633. this.userActive_ = false;
  18634. // Init debugEnabled_
  18635. this.debugEnabled_ = false;
  18636. // Init state audioOnlyMode_
  18637. this.audioOnlyMode_ = false;
  18638. // Init state audioPosterMode_
  18639. this.audioPosterMode_ = false;
  18640. // Init state audioOnlyCache_
  18641. this.audioOnlyCache_ = {
  18642. playerHeight: null,
  18643. hiddenChildren: []
  18644. };
  18645. // if the global option object was accidentally blown away by
  18646. // someone, bail early with an informative error
  18647. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  18648. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  18649. }
  18650. // Store the original tag used to set options
  18651. this.tag = tag;
  18652. // Store the tag attributes used to restore html5 element
  18653. this.tagAttributes = tag && getAttributes(tag);
  18654. // Update current language
  18655. this.language(this.options_.language);
  18656. // Update Supported Languages
  18657. if (options.languages) {
  18658. // Normalise player option languages to lowercase
  18659. const languagesToLower = {};
  18660. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  18661. languagesToLower[name.toLowerCase()] = options.languages[name];
  18662. });
  18663. this.languages_ = languagesToLower;
  18664. } else {
  18665. this.languages_ = Player.prototype.options_.languages;
  18666. }
  18667. this.resetCache_();
  18668. // Set poster
  18669. this.poster_ = options.poster || '';
  18670. // Set controls
  18671. this.controls_ = !!options.controls;
  18672. // Original tag settings stored in options
  18673. // now remove immediately so native controls don't flash.
  18674. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  18675. tag.controls = false;
  18676. tag.removeAttribute('controls');
  18677. this.changingSrc_ = false;
  18678. this.playCallbacks_ = [];
  18679. this.playTerminatedQueue_ = [];
  18680. // the attribute overrides the option
  18681. if (tag.hasAttribute('autoplay')) {
  18682. this.autoplay(true);
  18683. } else {
  18684. // otherwise use the setter to validate and
  18685. // set the correct value.
  18686. this.autoplay(this.options_.autoplay);
  18687. }
  18688. // check plugins
  18689. if (options.plugins) {
  18690. Object.keys(options.plugins).forEach(name => {
  18691. if (typeof this[name] !== 'function') {
  18692. throw new Error(`plugin "${name}" does not exist`);
  18693. }
  18694. });
  18695. }
  18696. /*
  18697. * Store the internal state of scrubbing
  18698. *
  18699. * @private
  18700. * @return {Boolean} True if the user is scrubbing
  18701. */
  18702. this.scrubbing_ = false;
  18703. this.el_ = this.createEl();
  18704. // Make this an evented object and use `el_` as its event bus.
  18705. evented(this, {
  18706. eventBusKey: 'el_'
  18707. });
  18708. // listen to document and player fullscreenchange handlers so we receive those events
  18709. // before a user can receive them so we can update isFullscreen appropriately.
  18710. // make sure that we listen to fullscreenchange events before everything else to make sure that
  18711. // our isFullscreen method is updated properly for internal components as well as external.
  18712. if (this.fsApi_.requestFullscreen) {
  18713. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18714. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18715. }
  18716. if (this.fluid_) {
  18717. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  18718. }
  18719. // We also want to pass the original player options to each component and plugin
  18720. // as well so they don't need to reach back into the player for options later.
  18721. // We also need to do another copy of this.options_ so we don't end up with
  18722. // an infinite loop.
  18723. const playerOptionsCopy = merge(this.options_);
  18724. // Load plugins
  18725. if (options.plugins) {
  18726. Object.keys(options.plugins).forEach(name => {
  18727. this[name](options.plugins[name]);
  18728. });
  18729. }
  18730. // Enable debug mode to fire debugon event for all plugins.
  18731. if (options.debug) {
  18732. this.debug(true);
  18733. }
  18734. this.options_.playerOptions = playerOptionsCopy;
  18735. this.middleware_ = [];
  18736. this.playbackRates(options.playbackRates);
  18737. this.initChildren();
  18738. // Set isAudio based on whether or not an audio tag was used
  18739. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  18740. // Update controls className. Can't do this when the controls are initially
  18741. // set because the element doesn't exist yet.
  18742. if (this.controls()) {
  18743. this.addClass('vjs-controls-enabled');
  18744. } else {
  18745. this.addClass('vjs-controls-disabled');
  18746. }
  18747. // Set ARIA label and region role depending on player type
  18748. this.el_.setAttribute('role', 'region');
  18749. if (this.isAudio()) {
  18750. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  18751. } else {
  18752. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  18753. }
  18754. if (this.isAudio()) {
  18755. this.addClass('vjs-audio');
  18756. }
  18757. // TODO: Make this smarter. Toggle user state between touching/mousing
  18758. // using events, since devices can have both touch and mouse events.
  18759. // TODO: Make this check be performed again when the window switches between monitors
  18760. // (See https://github.com/videojs/video.js/issues/5683)
  18761. if (TOUCH_ENABLED) {
  18762. this.addClass('vjs-touch-enabled');
  18763. }
  18764. // iOS Safari has broken hover handling
  18765. if (!IS_IOS) {
  18766. this.addClass('vjs-workinghover');
  18767. }
  18768. // Make player easily findable by ID
  18769. Player.players[this.id_] = this;
  18770. // Add a major version class to aid css in plugins
  18771. const majorVersion = version.split('.')[0];
  18772. this.addClass(`vjs-v${majorVersion}`);
  18773. // When the player is first initialized, trigger activity so components
  18774. // like the control bar show themselves if needed
  18775. this.userActive(true);
  18776. this.reportUserActivity();
  18777. this.one('play', e => this.listenForUserActivity_(e));
  18778. this.on('keydown', e => this.handleKeyDown(e));
  18779. this.on('languagechange', e => this.handleLanguagechange(e));
  18780. this.breakpoints(this.options_.breakpoints);
  18781. this.responsive(this.options_.responsive);
  18782. // Calling both the audio mode methods after the player is fully
  18783. // setup to be able to listen to the events triggered by them
  18784. this.on('ready', () => {
  18785. // Calling the audioPosterMode method first so that
  18786. // the audioOnlyMode can take precedence when both options are set to true
  18787. this.audioPosterMode(this.options_.audioPosterMode);
  18788. this.audioOnlyMode(this.options_.audioOnlyMode);
  18789. });
  18790. }
  18791. /**
  18792. * Destroys the video player and does any necessary cleanup.
  18793. *
  18794. * This is especially helpful if you are dynamically adding and removing videos
  18795. * to/from the DOM.
  18796. *
  18797. * @fires Player#dispose
  18798. */
  18799. dispose() {
  18800. /**
  18801. * Called when the player is being disposed of.
  18802. *
  18803. * @event Player#dispose
  18804. * @type {Event}
  18805. */
  18806. this.trigger('dispose');
  18807. // prevent dispose from being called twice
  18808. this.off('dispose');
  18809. // Make sure all player-specific document listeners are unbound. This is
  18810. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18811. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  18812. if (this.styleEl_ && this.styleEl_.parentNode) {
  18813. this.styleEl_.parentNode.removeChild(this.styleEl_);
  18814. this.styleEl_ = null;
  18815. }
  18816. // Kill reference to this player
  18817. Player.players[this.id_] = null;
  18818. if (this.tag && this.tag.player) {
  18819. this.tag.player = null;
  18820. }
  18821. if (this.el_ && this.el_.player) {
  18822. this.el_.player = null;
  18823. }
  18824. if (this.tech_) {
  18825. this.tech_.dispose();
  18826. this.isPosterFromTech_ = false;
  18827. this.poster_ = '';
  18828. }
  18829. if (this.playerElIngest_) {
  18830. this.playerElIngest_ = null;
  18831. }
  18832. if (this.tag) {
  18833. this.tag = null;
  18834. }
  18835. clearCacheForPlayer(this);
  18836. // remove all event handlers for track lists
  18837. // all tracks and track listeners are removed on
  18838. // tech dispose
  18839. ALL.names.forEach(name => {
  18840. const props = ALL[name];
  18841. const list = this[props.getterName]();
  18842. // if it is not a native list
  18843. // we have to manually remove event listeners
  18844. if (list && list.off) {
  18845. list.off();
  18846. }
  18847. });
  18848. // the actual .el_ is removed here, or replaced if
  18849. super.dispose({
  18850. restoreEl: this.options_.restoreEl
  18851. });
  18852. }
  18853. /**
  18854. * Create the `Player`'s DOM element.
  18855. *
  18856. * @return {Element}
  18857. * The DOM element that gets created.
  18858. */
  18859. createEl() {
  18860. let tag = this.tag;
  18861. let el;
  18862. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  18863. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  18864. if (playerElIngest) {
  18865. el = this.el_ = tag.parentNode;
  18866. } else if (!divEmbed) {
  18867. el = this.el_ = super.createEl('div');
  18868. }
  18869. // Copy over all the attributes from the tag, including ID and class
  18870. // ID will now reference player box, not the video tag
  18871. const attrs = getAttributes(tag);
  18872. if (divEmbed) {
  18873. el = this.el_ = tag;
  18874. tag = this.tag = document.createElement('video');
  18875. while (el.children.length) {
  18876. tag.appendChild(el.firstChild);
  18877. }
  18878. if (!hasClass(el, 'video-js')) {
  18879. addClass(el, 'video-js');
  18880. }
  18881. el.appendChild(tag);
  18882. playerElIngest = this.playerElIngest_ = el;
  18883. // move properties over from our custom `video-js` element
  18884. // to our new `video` element. This will move things like
  18885. // `src` or `controls` that were set via js before the player
  18886. // was initialized.
  18887. Object.keys(el).forEach(k => {
  18888. try {
  18889. tag[k] = el[k];
  18890. } catch (e) {
  18891. // we got a a property like outerHTML which we can't actually copy, ignore it
  18892. }
  18893. });
  18894. }
  18895. // set tabindex to -1 to remove the video element from the focus order
  18896. tag.setAttribute('tabindex', '-1');
  18897. attrs.tabindex = '-1';
  18898. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  18899. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  18900. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  18901. // doesn't change behavior of Chrome if JAWS is not being used
  18902. if (IS_CHROME && IS_WINDOWS) {
  18903. tag.setAttribute('role', 'application');
  18904. attrs.role = 'application';
  18905. }
  18906. // Remove width/height attrs from tag so CSS can make it 100% width/height
  18907. tag.removeAttribute('width');
  18908. tag.removeAttribute('height');
  18909. if ('width' in attrs) {
  18910. delete attrs.width;
  18911. }
  18912. if ('height' in attrs) {
  18913. delete attrs.height;
  18914. }
  18915. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  18916. // don't copy over the class attribute to the player element when we're in a div embed
  18917. // the class is already set up properly in the divEmbed case
  18918. // and we want to make sure that the `video-js` class doesn't get lost
  18919. if (!(divEmbed && attr === 'class')) {
  18920. el.setAttribute(attr, attrs[attr]);
  18921. }
  18922. if (divEmbed) {
  18923. tag.setAttribute(attr, attrs[attr]);
  18924. }
  18925. });
  18926. // Update tag id/class for use as HTML5 playback tech
  18927. // Might think we should do this after embedding in container so .vjs-tech class
  18928. // doesn't flash 100% width/height, but class only applies with .video-js parent
  18929. tag.playerId = tag.id;
  18930. tag.id += '_html5_api';
  18931. tag.className = 'vjs-tech';
  18932. // Make player findable on elements
  18933. tag.player = el.player = this;
  18934. // Default state of video is paused
  18935. this.addClass('vjs-paused');
  18936. // Add a style element in the player that we'll use to set the width/height
  18937. // of the player in a way that's still overridable by CSS, just like the
  18938. // video element
  18939. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  18940. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  18941. const defaultsStyleEl = $('.vjs-styles-defaults');
  18942. const head = $('head');
  18943. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  18944. }
  18945. this.fill_ = false;
  18946. this.fluid_ = false;
  18947. // Pass in the width/height/aspectRatio options which will update the style el
  18948. this.width(this.options_.width);
  18949. this.height(this.options_.height);
  18950. this.fill(this.options_.fill);
  18951. this.fluid(this.options_.fluid);
  18952. this.aspectRatio(this.options_.aspectRatio);
  18953. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  18954. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  18955. // Hide any links within the video/audio tag,
  18956. // because IE doesn't hide them completely from screen readers.
  18957. const links = tag.getElementsByTagName('a');
  18958. for (let i = 0; i < links.length; i++) {
  18959. const linkEl = links.item(i);
  18960. addClass(linkEl, 'vjs-hidden');
  18961. linkEl.setAttribute('hidden', 'hidden');
  18962. }
  18963. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  18964. // keep track of the original for later so we can know if the source originally failed
  18965. tag.initNetworkState_ = tag.networkState;
  18966. // Wrap video tag in div (el/box) container
  18967. if (tag.parentNode && !playerElIngest) {
  18968. tag.parentNode.insertBefore(el, tag);
  18969. }
  18970. // insert the tag as the first child of the player element
  18971. // then manually add it to the children array so that this.addChild
  18972. // will work properly for other components
  18973. //
  18974. // Breaks iPhone, fixed in HTML5 setup.
  18975. prependTo(tag, el);
  18976. this.children_.unshift(tag);
  18977. // Set lang attr on player to ensure CSS :lang() in consistent with player
  18978. // if it's been set to something different to the doc
  18979. this.el_.setAttribute('lang', this.language_);
  18980. this.el_.setAttribute('translate', 'no');
  18981. this.el_ = el;
  18982. return el;
  18983. }
  18984. /**
  18985. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  18986. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  18987. * behavior.
  18988. *
  18989. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  18990. *
  18991. * @param {string|null} [value]
  18992. * The value to set the `Player`'s crossOrigin to. If an argument is
  18993. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  18994. *
  18995. * @return {string|null|undefined}
  18996. * - The current crossOrigin value of the `Player` when getting.
  18997. * - undefined when setting
  18998. */
  18999. crossOrigin(value) {
  19000. // `null` can be set to unset a value
  19001. if (typeof value === 'undefined') {
  19002. return this.techGet_('crossOrigin');
  19003. }
  19004. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  19005. log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  19006. return;
  19007. }
  19008. this.techCall_('setCrossOrigin', value);
  19009. if (this.posterImage) {
  19010. this.posterImage.crossOrigin(value);
  19011. }
  19012. return;
  19013. }
  19014. /**
  19015. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19016. * To get the current width use `currentWidth()`.
  19017. *
  19018. * @param {number} [value]
  19019. * The value to set the `Player`'s width to.
  19020. *
  19021. * @return {number}
  19022. * The current width of the `Player` when getting.
  19023. */
  19024. width(value) {
  19025. return this.dimension('width', value);
  19026. }
  19027. /**
  19028. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19029. * To get the current height use `currentheight()`.
  19030. *
  19031. * @param {number} [value]
  19032. * The value to set the `Player`'s height to.
  19033. *
  19034. * @return {number}
  19035. * The current height of the `Player` when getting.
  19036. */
  19037. height(value) {
  19038. return this.dimension('height', value);
  19039. }
  19040. /**
  19041. * A getter/setter for the `Player`'s width & height.
  19042. *
  19043. * @param {string} dimension
  19044. * This string can be:
  19045. * - 'width'
  19046. * - 'height'
  19047. *
  19048. * @param {number} [value]
  19049. * Value for dimension specified in the first argument.
  19050. *
  19051. * @return {number}
  19052. * The dimension arguments value when getting (width/height).
  19053. */
  19054. dimension(dimension, value) {
  19055. const privDimension = dimension + '_';
  19056. if (value === undefined) {
  19057. return this[privDimension] || 0;
  19058. }
  19059. if (value === '' || value === 'auto') {
  19060. // If an empty string is given, reset the dimension to be automatic
  19061. this[privDimension] = undefined;
  19062. this.updateStyleEl_();
  19063. return;
  19064. }
  19065. const parsedVal = parseFloat(value);
  19066. if (isNaN(parsedVal)) {
  19067. log.error(`Improper value "${value}" supplied for for ${dimension}`);
  19068. return;
  19069. }
  19070. this[privDimension] = parsedVal;
  19071. this.updateStyleEl_();
  19072. }
  19073. /**
  19074. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19075. *
  19076. * Turning this on will turn off fill mode.
  19077. *
  19078. * @param {boolean} [bool]
  19079. * - A value of true adds the class.
  19080. * - A value of false removes the class.
  19081. * - No value will be a getter.
  19082. *
  19083. * @return {boolean|undefined}
  19084. * - The value of fluid when getting.
  19085. * - `undefined` when setting.
  19086. */
  19087. fluid(bool) {
  19088. if (bool === undefined) {
  19089. return !!this.fluid_;
  19090. }
  19091. this.fluid_ = !!bool;
  19092. if (isEvented(this)) {
  19093. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19094. }
  19095. if (bool) {
  19096. this.addClass('vjs-fluid');
  19097. this.fill(false);
  19098. addEventedCallback(this, () => {
  19099. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19100. });
  19101. } else {
  19102. this.removeClass('vjs-fluid');
  19103. }
  19104. this.updateStyleEl_();
  19105. }
  19106. /**
  19107. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  19108. *
  19109. * Turning this on will turn off fluid mode.
  19110. *
  19111. * @param {boolean} [bool]
  19112. * - A value of true adds the class.
  19113. * - A value of false removes the class.
  19114. * - No value will be a getter.
  19115. *
  19116. * @return {boolean|undefined}
  19117. * - The value of fluid when getting.
  19118. * - `undefined` when setting.
  19119. */
  19120. fill(bool) {
  19121. if (bool === undefined) {
  19122. return !!this.fill_;
  19123. }
  19124. this.fill_ = !!bool;
  19125. if (bool) {
  19126. this.addClass('vjs-fill');
  19127. this.fluid(false);
  19128. } else {
  19129. this.removeClass('vjs-fill');
  19130. }
  19131. }
  19132. /**
  19133. * Get/Set the aspect ratio
  19134. *
  19135. * @param {string} [ratio]
  19136. * Aspect ratio for player
  19137. *
  19138. * @return {string|undefined}
  19139. * returns the current aspect ratio when getting
  19140. */
  19141. /**
  19142. * A getter/setter for the `Player`'s aspect ratio.
  19143. *
  19144. * @param {string} [ratio]
  19145. * The value to set the `Player`'s aspect ratio to.
  19146. *
  19147. * @return {string|undefined}
  19148. * - The current aspect ratio of the `Player` when getting.
  19149. * - undefined when setting
  19150. */
  19151. aspectRatio(ratio) {
  19152. if (ratio === undefined) {
  19153. return this.aspectRatio_;
  19154. }
  19155. // Check for width:height format
  19156. if (!/^\d+\:\d+$/.test(ratio)) {
  19157. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  19158. }
  19159. this.aspectRatio_ = ratio;
  19160. // We're assuming if you set an aspect ratio you want fluid mode,
  19161. // because in fixed mode you could calculate width and height yourself.
  19162. this.fluid(true);
  19163. this.updateStyleEl_();
  19164. }
  19165. /**
  19166. * Update styles of the `Player` element (height, width and aspect ratio).
  19167. *
  19168. * @private
  19169. * @listens Tech#loadedmetadata
  19170. */
  19171. updateStyleEl_() {
  19172. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  19173. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  19174. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  19175. const techEl = this.tech_ && this.tech_.el();
  19176. if (techEl) {
  19177. if (width >= 0) {
  19178. techEl.width = width;
  19179. }
  19180. if (height >= 0) {
  19181. techEl.height = height;
  19182. }
  19183. }
  19184. return;
  19185. }
  19186. let width;
  19187. let height;
  19188. let aspectRatio;
  19189. let idClass;
  19190. // The aspect ratio is either used directly or to calculate width and height.
  19191. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  19192. // Use any aspectRatio that's been specifically set
  19193. aspectRatio = this.aspectRatio_;
  19194. } else if (this.videoWidth() > 0) {
  19195. // Otherwise try to get the aspect ratio from the video metadata
  19196. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  19197. } else {
  19198. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  19199. aspectRatio = '16:9';
  19200. }
  19201. // Get the ratio as a decimal we can use to calculate dimensions
  19202. const ratioParts = aspectRatio.split(':');
  19203. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  19204. if (this.width_ !== undefined) {
  19205. // Use any width that's been specifically set
  19206. width = this.width_;
  19207. } else if (this.height_ !== undefined) {
  19208. // Or calculate the width from the aspect ratio if a height has been set
  19209. width = this.height_ / ratioMultiplier;
  19210. } else {
  19211. // Or use the video's metadata, or use the video el's default of 300
  19212. width = this.videoWidth() || 300;
  19213. }
  19214. if (this.height_ !== undefined) {
  19215. // Use any height that's been specifically set
  19216. height = this.height_;
  19217. } else {
  19218. // Otherwise calculate the height from the ratio and the width
  19219. height = width * ratioMultiplier;
  19220. }
  19221. // Ensure the CSS class is valid by starting with an alpha character
  19222. if (/^[^a-zA-Z]/.test(this.id())) {
  19223. idClass = 'dimensions-' + this.id();
  19224. } else {
  19225. idClass = this.id() + '-dimensions';
  19226. }
  19227. // Ensure the right class is still on the player for the style element
  19228. this.addClass(idClass);
  19229. setTextContent(this.styleEl_, `
  19230. .${idClass} {
  19231. width: ${width}px;
  19232. height: ${height}px;
  19233. }
  19234. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  19235. padding-top: ${ratioMultiplier * 100}%;
  19236. }
  19237. `);
  19238. }
  19239. /**
  19240. * Load/Create an instance of playback {@link Tech} including element
  19241. * and API methods. Then append the `Tech` element in `Player` as a child.
  19242. *
  19243. * @param {string} techName
  19244. * name of the playback technology
  19245. *
  19246. * @param {string} source
  19247. * video source
  19248. *
  19249. * @private
  19250. */
  19251. loadTech_(techName, source) {
  19252. // Pause and remove current playback technology
  19253. if (this.tech_) {
  19254. this.unloadTech_();
  19255. }
  19256. const titleTechName = toTitleCase(techName);
  19257. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  19258. // get rid of the HTML5 video tag as soon as we are using another tech
  19259. if (titleTechName !== 'Html5' && this.tag) {
  19260. Tech.getTech('Html5').disposeMediaElement(this.tag);
  19261. this.tag.player = null;
  19262. this.tag = null;
  19263. }
  19264. this.techName_ = titleTechName;
  19265. // Turn off API access because we're loading a new tech that might load asynchronously
  19266. this.isReady_ = false;
  19267. let autoplay = this.autoplay();
  19268. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  19269. // because the player is going to handle autoplay on `loadstart`
  19270. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  19271. autoplay = false;
  19272. }
  19273. // Grab tech-specific options from player options and add source and parent element to use.
  19274. const techOptions = {
  19275. source,
  19276. autoplay,
  19277. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  19278. 'playerId': this.id(),
  19279. 'techId': `${this.id()}_${camelTechName}_api`,
  19280. 'playsinline': this.options_.playsinline,
  19281. 'preload': this.options_.preload,
  19282. 'loop': this.options_.loop,
  19283. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  19284. 'muted': this.options_.muted,
  19285. 'poster': this.poster(),
  19286. 'language': this.language(),
  19287. 'playerElIngest': this.playerElIngest_ || false,
  19288. 'vtt.js': this.options_['vtt.js'],
  19289. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  19290. 'enableSourceset': this.options_.enableSourceset
  19291. };
  19292. ALL.names.forEach(name => {
  19293. const props = ALL[name];
  19294. techOptions[props.getterName] = this[props.privateName];
  19295. });
  19296. Object.assign(techOptions, this.options_[titleTechName]);
  19297. Object.assign(techOptions, this.options_[camelTechName]);
  19298. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  19299. if (this.tag) {
  19300. techOptions.tag = this.tag;
  19301. }
  19302. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  19303. techOptions.startTime = this.cache_.currentTime;
  19304. }
  19305. // Initialize tech instance
  19306. const TechClass = Tech.getTech(techName);
  19307. if (!TechClass) {
  19308. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  19309. }
  19310. this.tech_ = new TechClass(techOptions);
  19311. // player.triggerReady is always async, so don't need this to be async
  19312. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  19313. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  19314. // Listen to all HTML5-defined events and trigger them on the player
  19315. TECH_EVENTS_RETRIGGER.forEach(event => {
  19316. this.on(this.tech_, event, e => this[`handleTech${toTitleCase(event)}_`](e));
  19317. });
  19318. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  19319. this.on(this.tech_, event, eventObj => {
  19320. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  19321. this.queuedCallbacks_.push({
  19322. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  19323. event: eventObj
  19324. });
  19325. return;
  19326. }
  19327. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  19328. });
  19329. });
  19330. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  19331. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  19332. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  19333. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  19334. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  19335. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  19336. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  19337. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  19338. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  19339. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  19340. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  19341. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  19342. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  19343. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  19344. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  19345. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  19346. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  19347. this.usingNativeControls(this.techGet_('controls'));
  19348. if (this.controls() && !this.usingNativeControls()) {
  19349. this.addTechControlsListeners_();
  19350. }
  19351. // Add the tech element in the DOM if it was not already there
  19352. // Make sure to not insert the original video element if using Html5
  19353. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  19354. prependTo(this.tech_.el(), this.el());
  19355. }
  19356. // Get rid of the original video tag reference after the first tech is loaded
  19357. if (this.tag) {
  19358. this.tag.player = null;
  19359. this.tag = null;
  19360. }
  19361. }
  19362. /**
  19363. * Unload and dispose of the current playback {@link Tech}.
  19364. *
  19365. * @private
  19366. */
  19367. unloadTech_() {
  19368. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  19369. ALL.names.forEach(name => {
  19370. const props = ALL[name];
  19371. this[props.privateName] = this[props.getterName]();
  19372. });
  19373. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  19374. this.isReady_ = false;
  19375. this.tech_.dispose();
  19376. this.tech_ = false;
  19377. if (this.isPosterFromTech_) {
  19378. this.poster_ = '';
  19379. this.trigger('posterchange');
  19380. }
  19381. this.isPosterFromTech_ = false;
  19382. }
  19383. /**
  19384. * Return a reference to the current {@link Tech}.
  19385. * It will print a warning by default about the danger of using the tech directly
  19386. * but any argument that is passed in will silence the warning.
  19387. *
  19388. * @param {*} [safety]
  19389. * Anything passed in to silence the warning
  19390. *
  19391. * @return {Tech}
  19392. * The Tech
  19393. */
  19394. tech(safety) {
  19395. if (safety === undefined) {
  19396. log.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\n');
  19397. }
  19398. return this.tech_;
  19399. }
  19400. /**
  19401. * Set up click and touch listeners for the playback element
  19402. *
  19403. * - On desktops: a click on the video itself will toggle playback
  19404. * - On mobile devices: a click on the video toggles controls
  19405. * which is done by toggling the user state between active and
  19406. * inactive
  19407. * - A tap can signal that a user has become active or has become inactive
  19408. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  19409. * quick tap should hide them again (signaling the user is in an inactive
  19410. * viewing state)
  19411. * - In addition to this, we still want the user to be considered inactive after
  19412. * a few seconds of inactivity.
  19413. *
  19414. * > Note: the only part of iOS interaction we can't mimic with this setup
  19415. * is a touch and hold on the video element counting as activity in order to
  19416. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  19417. * on any controls will still keep the user active
  19418. *
  19419. * @private
  19420. */
  19421. addTechControlsListeners_() {
  19422. // Make sure to remove all the previous listeners in case we are called multiple times.
  19423. this.removeTechControlsListeners_();
  19424. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  19425. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19426. // If the controls were hidden we don't want that to change without a tap event
  19427. // so we'll check if the controls were already showing before reporting user
  19428. // activity
  19429. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19430. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19431. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19432. // The tap listener needs to come after the touchend listener because the tap
  19433. // listener cancels out any reportedUserActivity when setting userActive(false)
  19434. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  19435. }
  19436. /**
  19437. * Remove the listeners used for click and tap controls. This is needed for
  19438. * toggling to controls disabled, where a tap/touch should do nothing.
  19439. *
  19440. * @private
  19441. */
  19442. removeTechControlsListeners_() {
  19443. // We don't want to just use `this.off()` because there might be other needed
  19444. // listeners added by techs that extend this.
  19445. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  19446. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19447. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19448. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19449. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  19450. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19451. }
  19452. /**
  19453. * Player waits for the tech to be ready
  19454. *
  19455. * @private
  19456. */
  19457. handleTechReady_() {
  19458. this.triggerReady();
  19459. // Keep the same volume as before
  19460. if (this.cache_.volume) {
  19461. this.techCall_('setVolume', this.cache_.volume);
  19462. }
  19463. // Look if the tech found a higher resolution poster while loading
  19464. this.handleTechPosterChange_();
  19465. // Update the duration if available
  19466. this.handleTechDurationChange_();
  19467. }
  19468. /**
  19469. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  19470. *
  19471. * @fires Player#loadstart
  19472. * @listens Tech#loadstart
  19473. * @private
  19474. */
  19475. handleTechLoadStart_() {
  19476. // TODO: Update to use `emptied` event instead. See #1277.
  19477. this.removeClass('vjs-ended', 'vjs-seeking');
  19478. // reset the error state
  19479. this.error(null);
  19480. // Update the duration
  19481. this.handleTechDurationChange_();
  19482. if (!this.paused()) {
  19483. /**
  19484. * Fired when the user agent begins looking for media data
  19485. *
  19486. * @event Player#loadstart
  19487. * @type {Event}
  19488. */
  19489. this.trigger('loadstart');
  19490. } else {
  19491. // reset the hasStarted state
  19492. this.hasStarted(false);
  19493. this.trigger('loadstart');
  19494. }
  19495. // autoplay happens after loadstart for the browser,
  19496. // so we mimic that behavior
  19497. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  19498. }
  19499. /**
  19500. * Handle autoplay string values, rather than the typical boolean
  19501. * values that should be handled by the tech. Note that this is not
  19502. * part of any specification. Valid values and what they do can be
  19503. * found on the autoplay getter at Player#autoplay()
  19504. */
  19505. manualAutoplay_(type) {
  19506. if (!this.tech_ || typeof type !== 'string') {
  19507. return;
  19508. }
  19509. // Save original muted() value, set muted to true, and attempt to play().
  19510. // On promise rejection, restore muted from saved value
  19511. const resolveMuted = () => {
  19512. const previouslyMuted = this.muted();
  19513. this.muted(true);
  19514. const restoreMuted = () => {
  19515. this.muted(previouslyMuted);
  19516. };
  19517. // restore muted on play terminatation
  19518. this.playTerminatedQueue_.push(restoreMuted);
  19519. const mutedPromise = this.play();
  19520. if (!isPromise(mutedPromise)) {
  19521. return;
  19522. }
  19523. return mutedPromise.catch(err => {
  19524. restoreMuted();
  19525. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  19526. });
  19527. };
  19528. let promise;
  19529. // if muted defaults to true
  19530. // the only thing we can do is call play
  19531. if (type === 'any' && !this.muted()) {
  19532. promise = this.play();
  19533. if (isPromise(promise)) {
  19534. promise = promise.catch(resolveMuted);
  19535. }
  19536. } else if (type === 'muted' && !this.muted()) {
  19537. promise = resolveMuted();
  19538. } else {
  19539. promise = this.play();
  19540. }
  19541. if (!isPromise(promise)) {
  19542. return;
  19543. }
  19544. return promise.then(() => {
  19545. this.trigger({
  19546. type: 'autoplay-success',
  19547. autoplay: type
  19548. });
  19549. }).catch(() => {
  19550. this.trigger({
  19551. type: 'autoplay-failure',
  19552. autoplay: type
  19553. });
  19554. });
  19555. }
  19556. /**
  19557. * Update the internal source caches so that we return the correct source from
  19558. * `src()`, `currentSource()`, and `currentSources()`.
  19559. *
  19560. * > Note: `currentSources` will not be updated if the source that is passed in exists
  19561. * in the current `currentSources` cache.
  19562. *
  19563. *
  19564. * @param {Tech~SourceObject} srcObj
  19565. * A string or object source to update our caches to.
  19566. */
  19567. updateSourceCaches_(srcObj = '') {
  19568. let src = srcObj;
  19569. let type = '';
  19570. if (typeof src !== 'string') {
  19571. src = srcObj.src;
  19572. type = srcObj.type;
  19573. }
  19574. // make sure all the caches are set to default values
  19575. // to prevent null checking
  19576. this.cache_.source = this.cache_.source || {};
  19577. this.cache_.sources = this.cache_.sources || [];
  19578. // try to get the type of the src that was passed in
  19579. if (src && !type) {
  19580. type = findMimetype(this, src);
  19581. }
  19582. // update `currentSource` cache always
  19583. this.cache_.source = merge({}, srcObj, {
  19584. src,
  19585. type
  19586. });
  19587. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  19588. const sourceElSources = [];
  19589. const sourceEls = this.$$('source');
  19590. const matchingSourceEls = [];
  19591. for (let i = 0; i < sourceEls.length; i++) {
  19592. const sourceObj = getAttributes(sourceEls[i]);
  19593. sourceElSources.push(sourceObj);
  19594. if (sourceObj.src && sourceObj.src === src) {
  19595. matchingSourceEls.push(sourceObj.src);
  19596. }
  19597. }
  19598. // if we have matching source els but not matching sources
  19599. // the current source cache is not up to date
  19600. if (matchingSourceEls.length && !matchingSources.length) {
  19601. this.cache_.sources = sourceElSources;
  19602. // if we don't have matching source or source els set the
  19603. // sources cache to the `currentSource` cache
  19604. } else if (!matchingSources.length) {
  19605. this.cache_.sources = [this.cache_.source];
  19606. }
  19607. // update the tech `src` cache
  19608. this.cache_.src = src;
  19609. }
  19610. /**
  19611. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  19612. * causing the media element to reload.
  19613. *
  19614. * It will fire for the initial source and each subsequent source.
  19615. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  19616. *
  19617. * The event object for this event contains a `src` property that will contain the source
  19618. * that was available when the event was triggered. This is generally only necessary if Video.js
  19619. * is switching techs while the source was being changed.
  19620. *
  19621. * It is also fired when `load` is called on the player (or media element)
  19622. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  19623. * says that the resource selection algorithm needs to be aborted and restarted.
  19624. * In this case, it is very likely that the `src` property will be set to the
  19625. * empty string `""` to indicate we do not know what the source will be but
  19626. * that it is changing.
  19627. *
  19628. * *This event is currently still experimental and may change in minor releases.*
  19629. * __To use this, pass `enableSourceset` option to the player.__
  19630. *
  19631. * @event Player#sourceset
  19632. * @type {Event}
  19633. * @prop {string} src
  19634. * The source url available when the `sourceset` was triggered.
  19635. * It will be an empty string if we cannot know what the source is
  19636. * but know that the source will change.
  19637. */
  19638. /**
  19639. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  19640. *
  19641. * @fires Player#sourceset
  19642. * @listens Tech#sourceset
  19643. * @private
  19644. */
  19645. handleTechSourceset_(event) {
  19646. // only update the source cache when the source
  19647. // was not updated using the player api
  19648. if (!this.changingSrc_) {
  19649. let updateSourceCaches = src => this.updateSourceCaches_(src);
  19650. const playerSrc = this.currentSource().src;
  19651. const eventSrc = event.src;
  19652. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  19653. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  19654. // if both the tech source and the player source were updated we assume
  19655. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  19656. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  19657. updateSourceCaches = () => {};
  19658. }
  19659. }
  19660. // update the source to the initial source right away
  19661. // in some cases this will be empty string
  19662. updateSourceCaches(eventSrc);
  19663. // if the `sourceset` `src` was an empty string
  19664. // wait for a `loadstart` to update the cache to `currentSrc`.
  19665. // If a sourceset happens before a `loadstart`, we reset the state
  19666. if (!event.src) {
  19667. this.tech_.any(['sourceset', 'loadstart'], e => {
  19668. // if a sourceset happens before a `loadstart` there
  19669. // is nothing to do as this `handleTechSourceset_`
  19670. // will be called again and this will be handled there.
  19671. if (e.type === 'sourceset') {
  19672. return;
  19673. }
  19674. const techSrc = this.techGet('currentSrc');
  19675. this.lastSource_.tech = techSrc;
  19676. this.updateSourceCaches_(techSrc);
  19677. });
  19678. }
  19679. }
  19680. this.lastSource_ = {
  19681. player: this.currentSource().src,
  19682. tech: event.src
  19683. };
  19684. this.trigger({
  19685. src: event.src,
  19686. type: 'sourceset'
  19687. });
  19688. }
  19689. /**
  19690. * Add/remove the vjs-has-started class
  19691. *
  19692. *
  19693. * @param {boolean} request
  19694. * - true: adds the class
  19695. * - false: remove the class
  19696. *
  19697. * @return {boolean}
  19698. * the boolean value of hasStarted_
  19699. */
  19700. hasStarted(request) {
  19701. if (request === undefined) {
  19702. // act as getter, if we have no request to change
  19703. return this.hasStarted_;
  19704. }
  19705. if (request === this.hasStarted_) {
  19706. return;
  19707. }
  19708. this.hasStarted_ = request;
  19709. if (this.hasStarted_) {
  19710. this.addClass('vjs-has-started');
  19711. } else {
  19712. this.removeClass('vjs-has-started');
  19713. }
  19714. }
  19715. /**
  19716. * Fired whenever the media begins or resumes playback
  19717. *
  19718. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  19719. * @fires Player#play
  19720. * @listens Tech#play
  19721. * @private
  19722. */
  19723. handleTechPlay_() {
  19724. this.removeClass('vjs-ended', 'vjs-paused');
  19725. this.addClass('vjs-playing');
  19726. // hide the poster when the user hits play
  19727. this.hasStarted(true);
  19728. /**
  19729. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  19730. * playback has started or resumed.
  19731. *
  19732. * @event Player#play
  19733. * @type {Event}
  19734. */
  19735. this.trigger('play');
  19736. }
  19737. /**
  19738. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  19739. *
  19740. * If there were any events queued while the playback rate was zero, fire
  19741. * those events now.
  19742. *
  19743. * @private
  19744. * @method Player#handleTechRateChange_
  19745. * @fires Player#ratechange
  19746. * @listens Tech#ratechange
  19747. */
  19748. handleTechRateChange_() {
  19749. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  19750. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  19751. this.queuedCallbacks_ = [];
  19752. }
  19753. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  19754. /**
  19755. * Fires when the playing speed of the audio/video is changed
  19756. *
  19757. * @event Player#ratechange
  19758. * @type {event}
  19759. */
  19760. this.trigger('ratechange');
  19761. }
  19762. /**
  19763. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  19764. *
  19765. * @fires Player#waiting
  19766. * @listens Tech#waiting
  19767. * @private
  19768. */
  19769. handleTechWaiting_() {
  19770. this.addClass('vjs-waiting');
  19771. /**
  19772. * A readyState change on the DOM element has caused playback to stop.
  19773. *
  19774. * @event Player#waiting
  19775. * @type {Event}
  19776. */
  19777. this.trigger('waiting');
  19778. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  19779. // premature removal of the waiting class, wait for the time to change.
  19780. const timeWhenWaiting = this.currentTime();
  19781. const timeUpdateListener = () => {
  19782. if (timeWhenWaiting !== this.currentTime()) {
  19783. this.removeClass('vjs-waiting');
  19784. this.off('timeupdate', timeUpdateListener);
  19785. }
  19786. };
  19787. this.on('timeupdate', timeUpdateListener);
  19788. }
  19789. /**
  19790. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  19791. * > Note: This is not consistent between browsers. See #1351
  19792. *
  19793. * @fires Player#canplay
  19794. * @listens Tech#canplay
  19795. * @private
  19796. */
  19797. handleTechCanPlay_() {
  19798. this.removeClass('vjs-waiting');
  19799. /**
  19800. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  19801. *
  19802. * @event Player#canplay
  19803. * @type {Event}
  19804. */
  19805. this.trigger('canplay');
  19806. }
  19807. /**
  19808. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  19809. *
  19810. * @fires Player#canplaythrough
  19811. * @listens Tech#canplaythrough
  19812. * @private
  19813. */
  19814. handleTechCanPlayThrough_() {
  19815. this.removeClass('vjs-waiting');
  19816. /**
  19817. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  19818. * entire media file can be played without buffering.
  19819. *
  19820. * @event Player#canplaythrough
  19821. * @type {Event}
  19822. */
  19823. this.trigger('canplaythrough');
  19824. }
  19825. /**
  19826. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  19827. *
  19828. * @fires Player#playing
  19829. * @listens Tech#playing
  19830. * @private
  19831. */
  19832. handleTechPlaying_() {
  19833. this.removeClass('vjs-waiting');
  19834. /**
  19835. * The media is no longer blocked from playback, and has started playing.
  19836. *
  19837. * @event Player#playing
  19838. * @type {Event}
  19839. */
  19840. this.trigger('playing');
  19841. }
  19842. /**
  19843. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  19844. *
  19845. * @fires Player#seeking
  19846. * @listens Tech#seeking
  19847. * @private
  19848. */
  19849. handleTechSeeking_() {
  19850. this.addClass('vjs-seeking');
  19851. /**
  19852. * Fired whenever the player is jumping to a new time
  19853. *
  19854. * @event Player#seeking
  19855. * @type {Event}
  19856. */
  19857. this.trigger('seeking');
  19858. }
  19859. /**
  19860. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  19861. *
  19862. * @fires Player#seeked
  19863. * @listens Tech#seeked
  19864. * @private
  19865. */
  19866. handleTechSeeked_() {
  19867. this.removeClass('vjs-seeking', 'vjs-ended');
  19868. /**
  19869. * Fired when the player has finished jumping to a new time
  19870. *
  19871. * @event Player#seeked
  19872. * @type {Event}
  19873. */
  19874. this.trigger('seeked');
  19875. }
  19876. /**
  19877. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  19878. *
  19879. * @fires Player#pause
  19880. * @listens Tech#pause
  19881. * @private
  19882. */
  19883. handleTechPause_() {
  19884. this.removeClass('vjs-playing');
  19885. this.addClass('vjs-paused');
  19886. /**
  19887. * Fired whenever the media has been paused
  19888. *
  19889. * @event Player#pause
  19890. * @type {Event}
  19891. */
  19892. this.trigger('pause');
  19893. }
  19894. /**
  19895. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  19896. *
  19897. * @fires Player#ended
  19898. * @listens Tech#ended
  19899. * @private
  19900. */
  19901. handleTechEnded_() {
  19902. this.addClass('vjs-ended');
  19903. this.removeClass('vjs-waiting');
  19904. if (this.options_.loop) {
  19905. this.currentTime(0);
  19906. this.play();
  19907. } else if (!this.paused()) {
  19908. this.pause();
  19909. }
  19910. /**
  19911. * Fired when the end of the media resource is reached (currentTime == duration)
  19912. *
  19913. * @event Player#ended
  19914. * @type {Event}
  19915. */
  19916. this.trigger('ended');
  19917. }
  19918. /**
  19919. * Fired when the duration of the media resource is first known or changed
  19920. *
  19921. * @listens Tech#durationchange
  19922. * @private
  19923. */
  19924. handleTechDurationChange_() {
  19925. this.duration(this.techGet_('duration'));
  19926. }
  19927. /**
  19928. * Handle a click on the media element to play/pause
  19929. *
  19930. * @param {Event} event
  19931. * the event that caused this function to trigger
  19932. *
  19933. * @listens Tech#click
  19934. * @private
  19935. */
  19936. handleTechClick_(event) {
  19937. // When controls are disabled a click should not toggle playback because
  19938. // the click is considered a control
  19939. if (!this.controls_) {
  19940. return;
  19941. }
  19942. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  19943. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  19944. this.options_.userActions.click.call(this, event);
  19945. } else if (this.paused()) {
  19946. silencePromise(this.play());
  19947. } else {
  19948. this.pause();
  19949. }
  19950. }
  19951. }
  19952. /**
  19953. * Handle a double-click on the media element to enter/exit fullscreen
  19954. *
  19955. * @param {Event} event
  19956. * the event that caused this function to trigger
  19957. *
  19958. * @listens Tech#dblclick
  19959. * @private
  19960. */
  19961. handleTechDoubleClick_(event) {
  19962. if (!this.controls_) {
  19963. return;
  19964. }
  19965. // we do not want to toggle fullscreen state
  19966. // when double-clicking inside a control bar or a modal
  19967. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  19968. if (!inAllowedEls) {
  19969. /*
  19970. * options.userActions.doubleClick
  19971. *
  19972. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  19973. * Set to `false` to disable double-click handling
  19974. * Set to a function to substitute an external double-click handler
  19975. */
  19976. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  19977. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  19978. this.options_.userActions.doubleClick.call(this, event);
  19979. } else if (this.isFullscreen()) {
  19980. this.exitFullscreen();
  19981. } else {
  19982. this.requestFullscreen();
  19983. }
  19984. }
  19985. }
  19986. }
  19987. /**
  19988. * Handle a tap on the media element. It will toggle the user
  19989. * activity state, which hides and shows the controls.
  19990. *
  19991. * @listens Tech#tap
  19992. * @private
  19993. */
  19994. handleTechTap_() {
  19995. this.userActive(!this.userActive());
  19996. }
  19997. /**
  19998. * Handle touch to start
  19999. *
  20000. * @listens Tech#touchstart
  20001. * @private
  20002. */
  20003. handleTechTouchStart_() {
  20004. this.userWasActive = this.userActive();
  20005. }
  20006. /**
  20007. * Handle touch to move
  20008. *
  20009. * @listens Tech#touchmove
  20010. * @private
  20011. */
  20012. handleTechTouchMove_() {
  20013. if (this.userWasActive) {
  20014. this.reportUserActivity();
  20015. }
  20016. }
  20017. /**
  20018. * Handle touch to end
  20019. *
  20020. * @param {Event} event
  20021. * the touchend event that triggered
  20022. * this function
  20023. *
  20024. * @listens Tech#touchend
  20025. * @private
  20026. */
  20027. handleTechTouchEnd_(event) {
  20028. // Stop the mouse events from also happening
  20029. if (event.cancelable) {
  20030. event.preventDefault();
  20031. }
  20032. }
  20033. /**
  20034. * @private
  20035. */
  20036. toggleFullscreenClass_() {
  20037. if (this.isFullscreen()) {
  20038. this.addClass('vjs-fullscreen');
  20039. } else {
  20040. this.removeClass('vjs-fullscreen');
  20041. }
  20042. }
  20043. /**
  20044. * when the document fschange event triggers it calls this
  20045. */
  20046. documentFullscreenChange_(e) {
  20047. const targetPlayer = e.target.player;
  20048. // if another player was fullscreen
  20049. // do a null check for targetPlayer because older firefox's would put document as e.target
  20050. if (targetPlayer && targetPlayer !== this) {
  20051. return;
  20052. }
  20053. const el = this.el();
  20054. let isFs = document[this.fsApi_.fullscreenElement] === el;
  20055. if (!isFs && el.matches) {
  20056. isFs = el.matches(':' + this.fsApi_.fullscreen);
  20057. } else if (!isFs && el.msMatchesSelector) {
  20058. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  20059. }
  20060. this.isFullscreen(isFs);
  20061. }
  20062. /**
  20063. * Handle Tech Fullscreen Change
  20064. *
  20065. * @param {Event} event
  20066. * the fullscreenchange event that triggered this function
  20067. *
  20068. * @param {Object} data
  20069. * the data that was sent with the event
  20070. *
  20071. * @private
  20072. * @listens Tech#fullscreenchange
  20073. * @fires Player#fullscreenchange
  20074. */
  20075. handleTechFullscreenChange_(event, data) {
  20076. if (data) {
  20077. if (data.nativeIOSFullscreen) {
  20078. this.addClass('vjs-ios-native-fs');
  20079. this.tech_.one('webkitendfullscreen', () => {
  20080. this.removeClass('vjs-ios-native-fs');
  20081. });
  20082. }
  20083. this.isFullscreen(data.isFullscreen);
  20084. }
  20085. }
  20086. handleTechFullscreenError_(event, err) {
  20087. this.trigger('fullscreenerror', err);
  20088. }
  20089. /**
  20090. * @private
  20091. */
  20092. togglePictureInPictureClass_() {
  20093. if (this.isInPictureInPicture()) {
  20094. this.addClass('vjs-picture-in-picture');
  20095. } else {
  20096. this.removeClass('vjs-picture-in-picture');
  20097. }
  20098. }
  20099. /**
  20100. * Handle Tech Enter Picture-in-Picture.
  20101. *
  20102. * @param {Event} event
  20103. * the enterpictureinpicture event that triggered this function
  20104. *
  20105. * @private
  20106. * @listens Tech#enterpictureinpicture
  20107. */
  20108. handleTechEnterPictureInPicture_(event) {
  20109. this.isInPictureInPicture(true);
  20110. }
  20111. /**
  20112. * Handle Tech Leave Picture-in-Picture.
  20113. *
  20114. * @param {Event} event
  20115. * the leavepictureinpicture event that triggered this function
  20116. *
  20117. * @private
  20118. * @listens Tech#leavepictureinpicture
  20119. */
  20120. handleTechLeavePictureInPicture_(event) {
  20121. this.isInPictureInPicture(false);
  20122. }
  20123. /**
  20124. * Fires when an error occurred during the loading of an audio/video.
  20125. *
  20126. * @private
  20127. * @listens Tech#error
  20128. */
  20129. handleTechError_() {
  20130. const error = this.tech_.error();
  20131. this.error(error);
  20132. }
  20133. /**
  20134. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  20135. *
  20136. * @fires Player#textdata
  20137. * @listens Tech#textdata
  20138. * @private
  20139. */
  20140. handleTechTextData_() {
  20141. let data = null;
  20142. if (arguments.length > 1) {
  20143. data = arguments[1];
  20144. }
  20145. /**
  20146. * Fires when we get a textdata event from tech
  20147. *
  20148. * @event Player#textdata
  20149. * @type {Event}
  20150. */
  20151. this.trigger('textdata', data);
  20152. }
  20153. /**
  20154. * Get object for cached values.
  20155. *
  20156. * @return {Object}
  20157. * get the current object cache
  20158. */
  20159. getCache() {
  20160. return this.cache_;
  20161. }
  20162. /**
  20163. * Resets the internal cache object.
  20164. *
  20165. * Using this function outside the player constructor or reset method may
  20166. * have unintended side-effects.
  20167. *
  20168. * @private
  20169. */
  20170. resetCache_() {
  20171. this.cache_ = {
  20172. // Right now, the currentTime is not _really_ cached because it is always
  20173. // retrieved from the tech (see: currentTime). However, for completeness,
  20174. // we set it to zero here to ensure that if we do start actually caching
  20175. // it, we reset it along with everything else.
  20176. currentTime: 0,
  20177. initTime: 0,
  20178. inactivityTimeout: this.options_.inactivityTimeout,
  20179. duration: NaN,
  20180. lastVolume: 1,
  20181. lastPlaybackRate: this.defaultPlaybackRate(),
  20182. media: null,
  20183. src: '',
  20184. source: {},
  20185. sources: [],
  20186. playbackRates: [],
  20187. volume: 1
  20188. };
  20189. }
  20190. /**
  20191. * Pass values to the playback tech
  20192. *
  20193. * @param {string} [method]
  20194. * the method to call
  20195. *
  20196. * @param {Object} arg
  20197. * the argument to pass
  20198. *
  20199. * @private
  20200. */
  20201. techCall_(method, arg) {
  20202. // If it's not ready yet, call method when it is
  20203. this.ready(function () {
  20204. if (method in allowedSetters) {
  20205. return set(this.middleware_, this.tech_, method, arg);
  20206. } else if (method in allowedMediators) {
  20207. return mediate(this.middleware_, this.tech_, method, arg);
  20208. }
  20209. try {
  20210. if (this.tech_) {
  20211. this.tech_[method](arg);
  20212. }
  20213. } catch (e) {
  20214. log(e);
  20215. throw e;
  20216. }
  20217. }, true);
  20218. }
  20219. /**
  20220. * Mediate attempt to call playback tech method
  20221. * and return the value of the method called.
  20222. *
  20223. * @param {string} method
  20224. * Tech method
  20225. *
  20226. * @return {*}
  20227. * Value returned by the tech method called, undefined if tech
  20228. * is not ready or tech method is not present
  20229. *
  20230. * @private
  20231. */
  20232. techGet_(method) {
  20233. if (!this.tech_ || !this.tech_.isReady_) {
  20234. return;
  20235. }
  20236. if (method in allowedGetters) {
  20237. return get(this.middleware_, this.tech_, method);
  20238. } else if (method in allowedMediators) {
  20239. return mediate(this.middleware_, this.tech_, method);
  20240. }
  20241. // Log error when playback tech object is present but method
  20242. // is undefined or unavailable
  20243. try {
  20244. return this.tech_[method]();
  20245. } catch (e) {
  20246. // When building additional tech libs, an expected method may not be defined yet
  20247. if (this.tech_[method] === undefined) {
  20248. log(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  20249. throw e;
  20250. }
  20251. // When a method isn't available on the object it throws a TypeError
  20252. if (e.name === 'TypeError') {
  20253. log(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  20254. this.tech_.isReady_ = false;
  20255. throw e;
  20256. }
  20257. // If error unknown, just log and throw
  20258. log(e);
  20259. throw e;
  20260. }
  20261. }
  20262. /**
  20263. * Attempt to begin playback at the first opportunity.
  20264. *
  20265. * @return {Promise|undefined}
  20266. * Returns a promise if the browser supports Promises (or one
  20267. * was passed in as an option). This promise will be resolved on
  20268. * the return value of play. If this is undefined it will fulfill the
  20269. * promise chain otherwise the promise chain will be fulfilled when
  20270. * the promise from play is fulfilled.
  20271. */
  20272. play() {
  20273. return new Promise(resolve => {
  20274. this.play_(resolve);
  20275. });
  20276. }
  20277. /**
  20278. * The actual logic for play, takes a callback that will be resolved on the
  20279. * return value of play. This allows us to resolve to the play promise if there
  20280. * is one on modern browsers.
  20281. *
  20282. * @private
  20283. * @param {Function} [callback]
  20284. * The callback that should be called when the techs play is actually called
  20285. */
  20286. play_(callback = silencePromise) {
  20287. this.playCallbacks_.push(callback);
  20288. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  20289. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  20290. // treat calls to play_ somewhat like the `one` event function
  20291. if (this.waitToPlay_) {
  20292. this.off(['ready', 'loadstart'], this.waitToPlay_);
  20293. this.waitToPlay_ = null;
  20294. }
  20295. // if the player/tech is not ready or the src itself is not ready
  20296. // queue up a call to play on `ready` or `loadstart`
  20297. if (!this.isReady_ || !isSrcReady) {
  20298. this.waitToPlay_ = e => {
  20299. this.play_();
  20300. };
  20301. this.one(['ready', 'loadstart'], this.waitToPlay_);
  20302. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  20303. // in that case, we need to prime the video element by calling load so it'll be ready in time
  20304. if (!isSrcReady && isSafariOrIOS) {
  20305. this.load();
  20306. }
  20307. return;
  20308. }
  20309. // If the player/tech is ready and we have a source, we can attempt playback.
  20310. const val = this.techGet_('play');
  20311. // For native playback, reset the progress bar if we get a play call from a replay.
  20312. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  20313. if (isNativeReplay) {
  20314. this.resetProgressBar_();
  20315. }
  20316. // play was terminated if the returned value is null
  20317. if (val === null) {
  20318. this.runPlayTerminatedQueue_();
  20319. } else {
  20320. this.runPlayCallbacks_(val);
  20321. }
  20322. }
  20323. /**
  20324. * These functions will be run when if play is terminated. If play
  20325. * runPlayCallbacks_ is run these function will not be run. This allows us
  20326. * to differentiate between a terminated play and an actual call to play.
  20327. */
  20328. runPlayTerminatedQueue_() {
  20329. const queue = this.playTerminatedQueue_.slice(0);
  20330. this.playTerminatedQueue_ = [];
  20331. queue.forEach(function (q) {
  20332. q();
  20333. });
  20334. }
  20335. /**
  20336. * When a callback to play is delayed we have to run these
  20337. * callbacks when play is actually called on the tech. This function
  20338. * runs the callbacks that were delayed and accepts the return value
  20339. * from the tech.
  20340. *
  20341. * @param {undefined|Promise} val
  20342. * The return value from the tech.
  20343. */
  20344. runPlayCallbacks_(val) {
  20345. const callbacks = this.playCallbacks_.slice(0);
  20346. this.playCallbacks_ = [];
  20347. // clear play terminatedQueue since we finished a real play
  20348. this.playTerminatedQueue_ = [];
  20349. callbacks.forEach(function (cb) {
  20350. cb(val);
  20351. });
  20352. }
  20353. /**
  20354. * Pause the video playback
  20355. *
  20356. * @return {Player}
  20357. * A reference to the player object this function was called on
  20358. */
  20359. pause() {
  20360. this.techCall_('pause');
  20361. }
  20362. /**
  20363. * Check if the player is paused or has yet to play
  20364. *
  20365. * @return {boolean}
  20366. * - false: if the media is currently playing
  20367. * - true: if media is not currently playing
  20368. */
  20369. paused() {
  20370. // The initial state of paused should be true (in Safari it's actually false)
  20371. return this.techGet_('paused') === false ? false : true;
  20372. }
  20373. /**
  20374. * Get a TimeRange object representing the current ranges of time that the user
  20375. * has played.
  20376. *
  20377. * @return { import('./utils/time').TimeRange }
  20378. * A time range object that represents all the increments of time that have
  20379. * been played.
  20380. */
  20381. played() {
  20382. return this.techGet_('played') || createTimeRanges(0, 0);
  20383. }
  20384. /**
  20385. * Returns whether or not the user is "scrubbing". Scrubbing is
  20386. * when the user has clicked the progress bar handle and is
  20387. * dragging it along the progress bar.
  20388. *
  20389. * @param {boolean} [isScrubbing]
  20390. * whether the user is or is not scrubbing
  20391. *
  20392. * @return {boolean}
  20393. * The value of scrubbing when getting
  20394. */
  20395. scrubbing(isScrubbing) {
  20396. if (typeof isScrubbing === 'undefined') {
  20397. return this.scrubbing_;
  20398. }
  20399. this.scrubbing_ = !!isScrubbing;
  20400. this.techCall_('setScrubbing', this.scrubbing_);
  20401. if (isScrubbing) {
  20402. this.addClass('vjs-scrubbing');
  20403. } else {
  20404. this.removeClass('vjs-scrubbing');
  20405. }
  20406. }
  20407. /**
  20408. * Get or set the current time (in seconds)
  20409. *
  20410. * @param {number|string} [seconds]
  20411. * The time to seek to in seconds
  20412. *
  20413. * @return {number}
  20414. * - the current time in seconds when getting
  20415. */
  20416. currentTime(seconds) {
  20417. if (typeof seconds !== 'undefined') {
  20418. if (seconds < 0) {
  20419. seconds = 0;
  20420. }
  20421. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  20422. this.cache_.initTime = seconds;
  20423. this.off('canplay', this.boundApplyInitTime_);
  20424. this.one('canplay', this.boundApplyInitTime_);
  20425. return;
  20426. }
  20427. this.techCall_('setCurrentTime', seconds);
  20428. this.cache_.initTime = 0;
  20429. return;
  20430. }
  20431. // cache last currentTime and return. default to 0 seconds
  20432. //
  20433. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  20434. // currentTime when scrubbing, but may not provide much performance benefit after all.
  20435. // Should be tested. Also something has to read the actual current time or the cache will
  20436. // never get updated.
  20437. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  20438. return this.cache_.currentTime;
  20439. }
  20440. /**
  20441. * Apply the value of initTime stored in cache as currentTime.
  20442. *
  20443. * @private
  20444. */
  20445. applyInitTime_() {
  20446. this.currentTime(this.cache_.initTime);
  20447. }
  20448. /**
  20449. * Normally gets the length in time of the video in seconds;
  20450. * in all but the rarest use cases an argument will NOT be passed to the method
  20451. *
  20452. * > **NOTE**: The video must have started loading before the duration can be
  20453. * known, and depending on preload behaviour may not be known until the video starts
  20454. * playing.
  20455. *
  20456. * @fires Player#durationchange
  20457. *
  20458. * @param {number} [seconds]
  20459. * The duration of the video to set in seconds
  20460. *
  20461. * @return {number}
  20462. * - The duration of the video in seconds when getting
  20463. */
  20464. duration(seconds) {
  20465. if (seconds === undefined) {
  20466. // return NaN if the duration is not known
  20467. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  20468. }
  20469. seconds = parseFloat(seconds);
  20470. // Standardize on Infinity for signaling video is live
  20471. if (seconds < 0) {
  20472. seconds = Infinity;
  20473. }
  20474. if (seconds !== this.cache_.duration) {
  20475. // Cache the last set value for optimized scrubbing
  20476. this.cache_.duration = seconds;
  20477. if (seconds === Infinity) {
  20478. this.addClass('vjs-live');
  20479. } else {
  20480. this.removeClass('vjs-live');
  20481. }
  20482. if (!isNaN(seconds)) {
  20483. // Do not fire durationchange unless the duration value is known.
  20484. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  20485. /**
  20486. * @event Player#durationchange
  20487. * @type {Event}
  20488. */
  20489. this.trigger('durationchange');
  20490. }
  20491. }
  20492. }
  20493. /**
  20494. * Calculates how much time is left in the video. Not part
  20495. * of the native video API.
  20496. *
  20497. * @return {number}
  20498. * The time remaining in seconds
  20499. */
  20500. remainingTime() {
  20501. return this.duration() - this.currentTime();
  20502. }
  20503. /**
  20504. * A remaining time function that is intended to be used when
  20505. * the time is to be displayed directly to the user.
  20506. *
  20507. * @return {number}
  20508. * The rounded time remaining in seconds
  20509. */
  20510. remainingTimeDisplay() {
  20511. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  20512. }
  20513. //
  20514. // Kind of like an array of portions of the video that have been downloaded.
  20515. /**
  20516. * Get a TimeRange object with an array of the times of the video
  20517. * that have been downloaded. If you just want the percent of the
  20518. * video that's been downloaded, use bufferedPercent.
  20519. *
  20520. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  20521. *
  20522. * @return { import('./utils/time').TimeRange }
  20523. * A mock {@link TimeRanges} object (following HTML spec)
  20524. */
  20525. buffered() {
  20526. let buffered = this.techGet_('buffered');
  20527. if (!buffered || !buffered.length) {
  20528. buffered = createTimeRanges(0, 0);
  20529. }
  20530. return buffered;
  20531. }
  20532. /**
  20533. * Get the percent (as a decimal) of the video that's been downloaded.
  20534. * This method is not a part of the native HTML video API.
  20535. *
  20536. * @return {number}
  20537. * A decimal between 0 and 1 representing the percent
  20538. * that is buffered 0 being 0% and 1 being 100%
  20539. */
  20540. bufferedPercent() {
  20541. return bufferedPercent(this.buffered(), this.duration());
  20542. }
  20543. /**
  20544. * Get the ending time of the last buffered time range
  20545. * This is used in the progress bar to encapsulate all time ranges.
  20546. *
  20547. * @return {number}
  20548. * The end of the last buffered time range
  20549. */
  20550. bufferedEnd() {
  20551. const buffered = this.buffered();
  20552. const duration = this.duration();
  20553. let end = buffered.end(buffered.length - 1);
  20554. if (end > duration) {
  20555. end = duration;
  20556. }
  20557. return end;
  20558. }
  20559. /**
  20560. * Get or set the current volume of the media
  20561. *
  20562. * @param {number} [percentAsDecimal]
  20563. * The new volume as a decimal percent:
  20564. * - 0 is muted/0%/off
  20565. * - 1.0 is 100%/full
  20566. * - 0.5 is half volume or 50%
  20567. *
  20568. * @return {number}
  20569. * The current volume as a percent when getting
  20570. */
  20571. volume(percentAsDecimal) {
  20572. let vol;
  20573. if (percentAsDecimal !== undefined) {
  20574. // Force value to between 0 and 1
  20575. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  20576. this.cache_.volume = vol;
  20577. this.techCall_('setVolume', vol);
  20578. if (vol > 0) {
  20579. this.lastVolume_(vol);
  20580. }
  20581. return;
  20582. }
  20583. // Default to 1 when returning current volume.
  20584. vol = parseFloat(this.techGet_('volume'));
  20585. return isNaN(vol) ? 1 : vol;
  20586. }
  20587. /**
  20588. * Get the current muted state, or turn mute on or off
  20589. *
  20590. * @param {boolean} [muted]
  20591. * - true to mute
  20592. * - false to unmute
  20593. *
  20594. * @return {boolean}
  20595. * - true if mute is on and getting
  20596. * - false if mute is off and getting
  20597. */
  20598. muted(muted) {
  20599. if (muted !== undefined) {
  20600. this.techCall_('setMuted', muted);
  20601. return;
  20602. }
  20603. return this.techGet_('muted') || false;
  20604. }
  20605. /**
  20606. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  20607. * indicates the state of muted on initial playback.
  20608. *
  20609. * ```js
  20610. * var myPlayer = videojs('some-player-id');
  20611. *
  20612. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  20613. *
  20614. * // get, should be false
  20615. * console.log(myPlayer.defaultMuted());
  20616. * // set to true
  20617. * myPlayer.defaultMuted(true);
  20618. * // get should be true
  20619. * console.log(myPlayer.defaultMuted());
  20620. * ```
  20621. *
  20622. * @param {boolean} [defaultMuted]
  20623. * - true to mute
  20624. * - false to unmute
  20625. *
  20626. * @return {boolean|Player}
  20627. * - true if defaultMuted is on and getting
  20628. * - false if defaultMuted is off and getting
  20629. * - A reference to the current player when setting
  20630. */
  20631. defaultMuted(defaultMuted) {
  20632. if (defaultMuted !== undefined) {
  20633. return this.techCall_('setDefaultMuted', defaultMuted);
  20634. }
  20635. return this.techGet_('defaultMuted') || false;
  20636. }
  20637. /**
  20638. * Get the last volume, or set it
  20639. *
  20640. * @param {number} [percentAsDecimal]
  20641. * The new last volume as a decimal percent:
  20642. * - 0 is muted/0%/off
  20643. * - 1.0 is 100%/full
  20644. * - 0.5 is half volume or 50%
  20645. *
  20646. * @return {number}
  20647. * the current value of lastVolume as a percent when getting
  20648. *
  20649. * @private
  20650. */
  20651. lastVolume_(percentAsDecimal) {
  20652. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  20653. this.cache_.lastVolume = percentAsDecimal;
  20654. return;
  20655. }
  20656. return this.cache_.lastVolume;
  20657. }
  20658. /**
  20659. * Check if current tech can support native fullscreen
  20660. * (e.g. with built in controls like iOS)
  20661. *
  20662. * @return {boolean}
  20663. * if native fullscreen is supported
  20664. */
  20665. supportsFullScreen() {
  20666. return this.techGet_('supportsFullScreen') || false;
  20667. }
  20668. /**
  20669. * Check if the player is in fullscreen mode or tell the player that it
  20670. * is or is not in fullscreen mode.
  20671. *
  20672. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  20673. * property and instead document.fullscreenElement is used. But isFullscreen is
  20674. * still a valuable property for internal player workings.
  20675. *
  20676. * @param {boolean} [isFS]
  20677. * Set the players current fullscreen state
  20678. *
  20679. * @return {boolean}
  20680. * - true if fullscreen is on and getting
  20681. * - false if fullscreen is off and getting
  20682. */
  20683. isFullscreen(isFS) {
  20684. if (isFS !== undefined) {
  20685. const oldValue = this.isFullscreen_;
  20686. this.isFullscreen_ = Boolean(isFS);
  20687. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  20688. // this is the only place where we trigger fullscreenchange events for older browsers
  20689. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  20690. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  20691. /**
  20692. * @event Player#fullscreenchange
  20693. * @type {Event}
  20694. */
  20695. this.trigger('fullscreenchange');
  20696. }
  20697. this.toggleFullscreenClass_();
  20698. return;
  20699. }
  20700. return this.isFullscreen_;
  20701. }
  20702. /**
  20703. * Increase the size of the video to full screen
  20704. * In some browsers, full screen is not supported natively, so it enters
  20705. * "full window mode", where the video fills the browser window.
  20706. * In browsers and devices that support native full screen, sometimes the
  20707. * browser's default controls will be shown, and not the Video.js custom skin.
  20708. * This includes most mobile devices (iOS, Android) and older versions of
  20709. * Safari.
  20710. *
  20711. * @param {Object} [fullscreenOptions]
  20712. * Override the player fullscreen options
  20713. *
  20714. * @fires Player#fullscreenchange
  20715. */
  20716. requestFullscreen(fullscreenOptions) {
  20717. if (this.isInPictureInPicture()) {
  20718. this.exitPictureInPicture();
  20719. }
  20720. const self = this;
  20721. return new Promise((resolve, reject) => {
  20722. function offHandler() {
  20723. self.off('fullscreenerror', errorHandler);
  20724. self.off('fullscreenchange', changeHandler);
  20725. }
  20726. function changeHandler() {
  20727. offHandler();
  20728. resolve();
  20729. }
  20730. function errorHandler(e, err) {
  20731. offHandler();
  20732. reject(err);
  20733. }
  20734. self.one('fullscreenchange', changeHandler);
  20735. self.one('fullscreenerror', errorHandler);
  20736. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  20737. if (promise) {
  20738. promise.then(offHandler, offHandler);
  20739. promise.then(resolve, reject);
  20740. }
  20741. });
  20742. }
  20743. requestFullscreenHelper_(fullscreenOptions) {
  20744. let fsOptions;
  20745. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  20746. // Use defaults or player configured option unless passed directly to this method.
  20747. if (!this.fsApi_.prefixed) {
  20748. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  20749. if (fullscreenOptions !== undefined) {
  20750. fsOptions = fullscreenOptions;
  20751. }
  20752. }
  20753. // This method works as follows:
  20754. // 1. if a fullscreen api is available, use it
  20755. // 1. call requestFullscreen with potential options
  20756. // 2. if we got a promise from above, use it to update isFullscreen()
  20757. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  20758. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  20759. // 3. otherwise, use "fullWindow" mode
  20760. if (this.fsApi_.requestFullscreen) {
  20761. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  20762. // Even on browsers with promise support this may not return a promise
  20763. if (promise) {
  20764. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  20765. }
  20766. return promise;
  20767. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20768. // we can't take the video.js controls fullscreen but we can go fullscreen
  20769. // with native controls
  20770. this.techCall_('enterFullScreen');
  20771. } else {
  20772. // fullscreen isn't supported so we'll just stretch the video element to
  20773. // fill the viewport
  20774. this.enterFullWindow();
  20775. }
  20776. }
  20777. /**
  20778. * Return the video to its normal size after having been in full screen mode
  20779. *
  20780. * @fires Player#fullscreenchange
  20781. */
  20782. exitFullscreen() {
  20783. const self = this;
  20784. return new Promise((resolve, reject) => {
  20785. function offHandler() {
  20786. self.off('fullscreenerror', errorHandler);
  20787. self.off('fullscreenchange', changeHandler);
  20788. }
  20789. function changeHandler() {
  20790. offHandler();
  20791. resolve();
  20792. }
  20793. function errorHandler(e, err) {
  20794. offHandler();
  20795. reject(err);
  20796. }
  20797. self.one('fullscreenchange', changeHandler);
  20798. self.one('fullscreenerror', errorHandler);
  20799. const promise = self.exitFullscreenHelper_();
  20800. if (promise) {
  20801. promise.then(offHandler, offHandler);
  20802. // map the promise to our resolve/reject methods
  20803. promise.then(resolve, reject);
  20804. }
  20805. });
  20806. }
  20807. exitFullscreenHelper_() {
  20808. if (this.fsApi_.requestFullscreen) {
  20809. const promise = document[this.fsApi_.exitFullscreen]();
  20810. // Even on browsers with promise support this may not return a promise
  20811. if (promise) {
  20812. // we're splitting the promise here, so, we want to catch the
  20813. // potential error so that this chain doesn't have unhandled errors
  20814. silencePromise(promise.then(() => this.isFullscreen(false)));
  20815. }
  20816. return promise;
  20817. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20818. this.techCall_('exitFullScreen');
  20819. } else {
  20820. this.exitFullWindow();
  20821. }
  20822. }
  20823. /**
  20824. * When fullscreen isn't supported we can stretch the
  20825. * video container to as wide as the browser will let us.
  20826. *
  20827. * @fires Player#enterFullWindow
  20828. */
  20829. enterFullWindow() {
  20830. this.isFullscreen(true);
  20831. this.isFullWindow = true;
  20832. // Storing original doc overflow value to return to when fullscreen is off
  20833. this.docOrigOverflow = document.documentElement.style.overflow;
  20834. // Add listener for esc key to exit fullscreen
  20835. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  20836. // Hide any scroll bars
  20837. document.documentElement.style.overflow = 'hidden';
  20838. // Apply fullscreen styles
  20839. addClass(document.body, 'vjs-full-window');
  20840. /**
  20841. * @event Player#enterFullWindow
  20842. * @type {Event}
  20843. */
  20844. this.trigger('enterFullWindow');
  20845. }
  20846. /**
  20847. * Check for call to either exit full window or
  20848. * full screen on ESC key
  20849. *
  20850. * @param {string} event
  20851. * Event to check for key press
  20852. */
  20853. fullWindowOnEscKey(event) {
  20854. if (keycode.isEventKey(event, 'Esc')) {
  20855. if (this.isFullscreen() === true) {
  20856. if (!this.isFullWindow) {
  20857. this.exitFullscreen();
  20858. } else {
  20859. this.exitFullWindow();
  20860. }
  20861. }
  20862. }
  20863. }
  20864. /**
  20865. * Exit full window
  20866. *
  20867. * @fires Player#exitFullWindow
  20868. */
  20869. exitFullWindow() {
  20870. this.isFullscreen(false);
  20871. this.isFullWindow = false;
  20872. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  20873. // Unhide scroll bars.
  20874. document.documentElement.style.overflow = this.docOrigOverflow;
  20875. // Remove fullscreen styles
  20876. removeClass(document.body, 'vjs-full-window');
  20877. // Resize the box, controller, and poster to original sizes
  20878. // this.positionAll();
  20879. /**
  20880. * @event Player#exitFullWindow
  20881. * @type {Event}
  20882. */
  20883. this.trigger('exitFullWindow');
  20884. }
  20885. /**
  20886. * Disable Picture-in-Picture mode.
  20887. *
  20888. * @param {boolean} value
  20889. * - true will disable Picture-in-Picture mode
  20890. * - false will enable Picture-in-Picture mode
  20891. */
  20892. disablePictureInPicture(value) {
  20893. if (value === undefined) {
  20894. return this.techGet_('disablePictureInPicture');
  20895. }
  20896. this.techCall_('setDisablePictureInPicture', value);
  20897. this.options_.disablePictureInPicture = value;
  20898. this.trigger('disablepictureinpicturechanged');
  20899. }
  20900. /**
  20901. * Check if the player is in Picture-in-Picture mode or tell the player that it
  20902. * is or is not in Picture-in-Picture mode.
  20903. *
  20904. * @param {boolean} [isPiP]
  20905. * Set the players current Picture-in-Picture state
  20906. *
  20907. * @return {boolean}
  20908. * - true if Picture-in-Picture is on and getting
  20909. * - false if Picture-in-Picture is off and getting
  20910. */
  20911. isInPictureInPicture(isPiP) {
  20912. if (isPiP !== undefined) {
  20913. this.isInPictureInPicture_ = !!isPiP;
  20914. this.togglePictureInPictureClass_();
  20915. return;
  20916. }
  20917. return !!this.isInPictureInPicture_;
  20918. }
  20919. /**
  20920. * Create a floating video window always on top of other windows so that users may
  20921. * continue consuming media while they interact with other content sites, or
  20922. * applications on their device.
  20923. *
  20924. * This can use document picture-in-picture or element picture in picture
  20925. *
  20926. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  20927. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  20928. *
  20929. *
  20930. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  20931. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  20932. *
  20933. * @fires Player#enterpictureinpicture
  20934. *
  20935. * @return {Promise}
  20936. * A promise with a Picture-in-Picture window.
  20937. */
  20938. requestPictureInPicture() {
  20939. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  20940. const pipContainer = document.createElement(this.el().tagName);
  20941. pipContainer.classList = this.el().classList;
  20942. pipContainer.classList.add('vjs-pip-container');
  20943. if (this.posterImage) {
  20944. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  20945. }
  20946. if (this.titleBar) {
  20947. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  20948. }
  20949. pipContainer.appendChild(createEl('p', {
  20950. className: 'vjs-pip-text'
  20951. }, {}, this.localize('Playing in picture-in-picture')));
  20952. return window.documentPictureInPicture.requestWindow({
  20953. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  20954. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  20955. copyStyleSheets: true
  20956. }).then(pipWindow => {
  20957. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  20958. pipWindow.document.body.append(this.el_);
  20959. pipWindow.document.body.classList.add('vjs-pip-window');
  20960. this.player_.isInPictureInPicture(true);
  20961. this.player_.trigger('enterpictureinpicture');
  20962. // Listen for the PiP closing event to move the video back.
  20963. pipWindow.addEventListener('unload', event => {
  20964. const pipVideo = event.target.querySelector('.video-js');
  20965. pipContainer.replaceWith(pipVideo);
  20966. this.player_.isInPictureInPicture(false);
  20967. this.player_.trigger('leavepictureinpicture');
  20968. });
  20969. return pipWindow;
  20970. });
  20971. }
  20972. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  20973. /**
  20974. * This event fires when the player enters picture in picture mode
  20975. *
  20976. * @event Player#enterpictureinpicture
  20977. * @type {Event}
  20978. */
  20979. return this.techGet_('requestPictureInPicture');
  20980. }
  20981. return Promise.reject('No PiP mode is available');
  20982. }
  20983. /**
  20984. * Exit Picture-in-Picture mode.
  20985. *
  20986. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  20987. *
  20988. * @fires Player#leavepictureinpicture
  20989. *
  20990. * @return {Promise}
  20991. * A promise.
  20992. */
  20993. exitPictureInPicture() {
  20994. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  20995. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  20996. window.documentPictureInPicture.window.close();
  20997. return Promise.resolve();
  20998. }
  20999. if ('pictureInPictureEnabled' in document) {
  21000. /**
  21001. * This event fires when the player leaves picture in picture mode
  21002. *
  21003. * @event Player#leavepictureinpicture
  21004. * @type {Event}
  21005. */
  21006. return document.exitPictureInPicture();
  21007. }
  21008. }
  21009. /**
  21010. * Called when this Player has focus and a key gets pressed down, or when
  21011. * any Component of this player receives a key press that it doesn't handle.
  21012. * This allows player-wide hotkeys (either as defined below, or optionally
  21013. * by an external function).
  21014. *
  21015. * @param {Event} event
  21016. * The `keydown` event that caused this function to be called.
  21017. *
  21018. * @listens keydown
  21019. */
  21020. handleKeyDown(event) {
  21021. const {
  21022. userActions
  21023. } = this.options_;
  21024. // Bail out if hotkeys are not configured.
  21025. if (!userActions || !userActions.hotkeys) {
  21026. return;
  21027. }
  21028. // Function that determines whether or not to exclude an element from
  21029. // hotkeys handling.
  21030. const excludeElement = el => {
  21031. const tagName = el.tagName.toLowerCase();
  21032. // The first and easiest test is for `contenteditable` elements.
  21033. if (el.isContentEditable) {
  21034. return true;
  21035. }
  21036. // Inputs matching these types will still trigger hotkey handling as
  21037. // they are not text inputs.
  21038. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  21039. if (tagName === 'input') {
  21040. return allowedInputTypes.indexOf(el.type) === -1;
  21041. }
  21042. // The final test is by tag name. These tags will be excluded entirely.
  21043. const excludedTags = ['textarea'];
  21044. return excludedTags.indexOf(tagName) !== -1;
  21045. };
  21046. // Bail out if the user is focused on an interactive form element.
  21047. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  21048. return;
  21049. }
  21050. if (typeof userActions.hotkeys === 'function') {
  21051. userActions.hotkeys.call(this, event);
  21052. } else {
  21053. this.handleHotkeys(event);
  21054. }
  21055. }
  21056. /**
  21057. * Called when this Player receives a hotkey keydown event.
  21058. * Supported player-wide hotkeys are:
  21059. *
  21060. * f - toggle fullscreen
  21061. * m - toggle mute
  21062. * k or Space - toggle play/pause
  21063. *
  21064. * @param {Event} event
  21065. * The `keydown` event that caused this function to be called.
  21066. */
  21067. handleHotkeys(event) {
  21068. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  21069. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  21070. const {
  21071. fullscreenKey = keydownEvent => keycode.isEventKey(keydownEvent, 'f'),
  21072. muteKey = keydownEvent => keycode.isEventKey(keydownEvent, 'm'),
  21073. playPauseKey = keydownEvent => keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space')
  21074. } = hotkeys;
  21075. if (fullscreenKey.call(this, event)) {
  21076. event.preventDefault();
  21077. event.stopPropagation();
  21078. const FSToggle = Component.getComponent('FullscreenToggle');
  21079. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  21080. FSToggle.prototype.handleClick.call(this, event);
  21081. }
  21082. } else if (muteKey.call(this, event)) {
  21083. event.preventDefault();
  21084. event.stopPropagation();
  21085. const MuteToggle = Component.getComponent('MuteToggle');
  21086. MuteToggle.prototype.handleClick.call(this, event);
  21087. } else if (playPauseKey.call(this, event)) {
  21088. event.preventDefault();
  21089. event.stopPropagation();
  21090. const PlayToggle = Component.getComponent('PlayToggle');
  21091. PlayToggle.prototype.handleClick.call(this, event);
  21092. }
  21093. }
  21094. /**
  21095. * Check whether the player can play a given mimetype
  21096. *
  21097. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  21098. *
  21099. * @param {string} type
  21100. * The mimetype to check
  21101. *
  21102. * @return {string}
  21103. * 'probably', 'maybe', or '' (empty string)
  21104. */
  21105. canPlayType(type) {
  21106. let can;
  21107. // Loop through each playback technology in the options order
  21108. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  21109. const techName = j[i];
  21110. let tech = Tech.getTech(techName);
  21111. // Support old behavior of techs being registered as components.
  21112. // Remove once that deprecated behavior is removed.
  21113. if (!tech) {
  21114. tech = Component.getComponent(techName);
  21115. }
  21116. // Check if the current tech is defined before continuing
  21117. if (!tech) {
  21118. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21119. continue;
  21120. }
  21121. // Check if the browser supports this technology
  21122. if (tech.isSupported()) {
  21123. can = tech.canPlayType(type);
  21124. if (can) {
  21125. return can;
  21126. }
  21127. }
  21128. }
  21129. return '';
  21130. }
  21131. /**
  21132. * Select source based on tech-order or source-order
  21133. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  21134. * defaults to tech-order selection
  21135. *
  21136. * @param {Array} sources
  21137. * The sources for a media asset
  21138. *
  21139. * @return {Object|boolean}
  21140. * Object of source and tech order or false
  21141. */
  21142. selectSource(sources) {
  21143. // Get only the techs specified in `techOrder` that exist and are supported by the
  21144. // current platform
  21145. const techs = this.options_.techOrder.map(techName => {
  21146. return [techName, Tech.getTech(techName)];
  21147. }).filter(([techName, tech]) => {
  21148. // Check if the current tech is defined before continuing
  21149. if (tech) {
  21150. // Check if the browser supports this technology
  21151. return tech.isSupported();
  21152. }
  21153. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21154. return false;
  21155. });
  21156. // Iterate over each `innerArray` element once per `outerArray` element and execute
  21157. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  21158. // that value.
  21159. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  21160. let found;
  21161. outerArray.some(outerChoice => {
  21162. return innerArray.some(innerChoice => {
  21163. found = tester(outerChoice, innerChoice);
  21164. if (found) {
  21165. return true;
  21166. }
  21167. });
  21168. });
  21169. return found;
  21170. };
  21171. let foundSourceAndTech;
  21172. const flip = fn => (a, b) => fn(b, a);
  21173. const finder = ([techName, tech], source) => {
  21174. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  21175. return {
  21176. source,
  21177. tech: techName
  21178. };
  21179. }
  21180. };
  21181. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  21182. // to select from them based on their priority.
  21183. if (this.options_.sourceOrder) {
  21184. // Source-first ordering
  21185. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  21186. } else {
  21187. // Tech-first ordering
  21188. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  21189. }
  21190. return foundSourceAndTech || false;
  21191. }
  21192. /**
  21193. * Executes source setting and getting logic
  21194. *
  21195. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21196. * A SourceObject, an array of SourceObjects, or a string referencing
  21197. * a URL to a media source. It is _highly recommended_ that an object
  21198. * or array of objects is used here, so that source selection
  21199. * algorithms can take the `type` into account.
  21200. *
  21201. * If not provided, this method acts as a getter.
  21202. * @param {boolean} isRetry
  21203. * Indicates whether this is being called internally as a result of a retry
  21204. *
  21205. * @return {string|undefined}
  21206. * If the `source` argument is missing, returns the current source
  21207. * URL. Otherwise, returns nothing/undefined.
  21208. */
  21209. handleSrc_(source, isRetry) {
  21210. // getter usage
  21211. if (typeof source === 'undefined') {
  21212. return this.cache_.src || '';
  21213. }
  21214. // Reset retry behavior for new source
  21215. if (this.resetRetryOnError_) {
  21216. this.resetRetryOnError_();
  21217. }
  21218. // filter out invalid sources and turn our source into
  21219. // an array of source objects
  21220. const sources = filterSource(source);
  21221. // if a source was passed in then it is invalid because
  21222. // it was filtered to a zero length Array. So we have to
  21223. // show an error
  21224. if (!sources.length) {
  21225. this.setTimeout(function () {
  21226. this.error({
  21227. code: 4,
  21228. message: this.options_.notSupportedMessage
  21229. });
  21230. }, 0);
  21231. return;
  21232. }
  21233. // initial sources
  21234. this.changingSrc_ = true;
  21235. // Only update the cached source list if we are not retrying a new source after error,
  21236. // since in that case we want to include the failed source(s) in the cache
  21237. if (!isRetry) {
  21238. this.cache_.sources = sources;
  21239. }
  21240. this.updateSourceCaches_(sources[0]);
  21241. // middlewareSource is the source after it has been changed by middleware
  21242. setSource(this, sources[0], (middlewareSource, mws) => {
  21243. this.middleware_ = mws;
  21244. // since sourceSet is async we have to update the cache again after we select a source since
  21245. // the source that is selected could be out of order from the cache update above this callback.
  21246. if (!isRetry) {
  21247. this.cache_.sources = sources;
  21248. }
  21249. this.updateSourceCaches_(middlewareSource);
  21250. const err = this.src_(middlewareSource);
  21251. if (err) {
  21252. if (sources.length > 1) {
  21253. return this.handleSrc_(sources.slice(1));
  21254. }
  21255. this.changingSrc_ = false;
  21256. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  21257. this.setTimeout(function () {
  21258. this.error({
  21259. code: 4,
  21260. message: this.options_.notSupportedMessage
  21261. });
  21262. }, 0);
  21263. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  21264. // this needs a better comment about why this is needed
  21265. this.triggerReady();
  21266. return;
  21267. }
  21268. setTech(mws, this.tech_);
  21269. });
  21270. // Try another available source if this one fails before playback.
  21271. if (sources.length > 1) {
  21272. const retry = () => {
  21273. // Remove the error modal
  21274. this.error(null);
  21275. this.handleSrc_(sources.slice(1), true);
  21276. };
  21277. const stopListeningForErrors = () => {
  21278. this.off('error', retry);
  21279. };
  21280. this.one('error', retry);
  21281. this.one('playing', stopListeningForErrors);
  21282. this.resetRetryOnError_ = () => {
  21283. this.off('error', retry);
  21284. this.off('playing', stopListeningForErrors);
  21285. };
  21286. }
  21287. }
  21288. /**
  21289. * Get or set the video source.
  21290. *
  21291. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21292. * A SourceObject, an array of SourceObjects, or a string referencing
  21293. * a URL to a media source. It is _highly recommended_ that an object
  21294. * or array of objects is used here, so that source selection
  21295. * algorithms can take the `type` into account.
  21296. *
  21297. * If not provided, this method acts as a getter.
  21298. *
  21299. * @return {string|undefined}
  21300. * If the `source` argument is missing, returns the current source
  21301. * URL. Otherwise, returns nothing/undefined.
  21302. */
  21303. src(source) {
  21304. return this.handleSrc_(source, false);
  21305. }
  21306. /**
  21307. * Set the source object on the tech, returns a boolean that indicates whether
  21308. * there is a tech that can play the source or not
  21309. *
  21310. * @param {Tech~SourceObject} source
  21311. * The source object to set on the Tech
  21312. *
  21313. * @return {boolean}
  21314. * - True if there is no Tech to playback this source
  21315. * - False otherwise
  21316. *
  21317. * @private
  21318. */
  21319. src_(source) {
  21320. const sourceTech = this.selectSource([source]);
  21321. if (!sourceTech) {
  21322. return true;
  21323. }
  21324. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  21325. this.changingSrc_ = true;
  21326. // load this technology with the chosen source
  21327. this.loadTech_(sourceTech.tech, sourceTech.source);
  21328. this.tech_.ready(() => {
  21329. this.changingSrc_ = false;
  21330. });
  21331. return false;
  21332. }
  21333. // wait until the tech is ready to set the source
  21334. // and set it synchronously if possible (#2326)
  21335. this.ready(function () {
  21336. // The setSource tech method was added with source handlers
  21337. // so older techs won't support it
  21338. // We need to check the direct prototype for the case where subclasses
  21339. // of the tech do not support source handlers
  21340. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  21341. this.techCall_('setSource', source);
  21342. } else {
  21343. this.techCall_('src', source.src);
  21344. }
  21345. this.changingSrc_ = false;
  21346. }, true);
  21347. return false;
  21348. }
  21349. /**
  21350. * Begin loading the src data.
  21351. */
  21352. load() {
  21353. this.techCall_('load');
  21354. }
  21355. /**
  21356. * Reset the player. Loads the first tech in the techOrder,
  21357. * removes all the text tracks in the existing `tech`,
  21358. * and calls `reset` on the `tech`.
  21359. */
  21360. reset() {
  21361. if (this.paused()) {
  21362. this.doReset_();
  21363. } else {
  21364. const playPromise = this.play();
  21365. silencePromise(playPromise.then(() => this.doReset_()));
  21366. }
  21367. }
  21368. doReset_() {
  21369. if (this.tech_) {
  21370. this.tech_.clearTracks('text');
  21371. }
  21372. this.resetCache_();
  21373. this.poster('');
  21374. this.loadTech_(this.options_.techOrder[0], null);
  21375. this.techCall_('reset');
  21376. this.resetControlBarUI_();
  21377. if (isEvented(this)) {
  21378. this.trigger('playerreset');
  21379. }
  21380. }
  21381. /**
  21382. * Reset Control Bar's UI by calling sub-methods that reset
  21383. * all of Control Bar's components
  21384. */
  21385. resetControlBarUI_() {
  21386. this.resetProgressBar_();
  21387. this.resetPlaybackRate_();
  21388. this.resetVolumeBar_();
  21389. }
  21390. /**
  21391. * Reset tech's progress so progress bar is reset in the UI
  21392. */
  21393. resetProgressBar_() {
  21394. this.currentTime(0);
  21395. const {
  21396. currentTimeDisplay,
  21397. durationDisplay,
  21398. progressControl,
  21399. remainingTimeDisplay
  21400. } = this.controlBar || {};
  21401. const {
  21402. seekBar
  21403. } = progressControl || {};
  21404. if (currentTimeDisplay) {
  21405. currentTimeDisplay.updateContent();
  21406. }
  21407. if (durationDisplay) {
  21408. durationDisplay.updateContent();
  21409. }
  21410. if (remainingTimeDisplay) {
  21411. remainingTimeDisplay.updateContent();
  21412. }
  21413. if (seekBar) {
  21414. seekBar.update();
  21415. if (seekBar.loadProgressBar) {
  21416. seekBar.loadProgressBar.update();
  21417. }
  21418. }
  21419. }
  21420. /**
  21421. * Reset Playback ratio
  21422. */
  21423. resetPlaybackRate_() {
  21424. this.playbackRate(this.defaultPlaybackRate());
  21425. this.handleTechRateChange_();
  21426. }
  21427. /**
  21428. * Reset Volume bar
  21429. */
  21430. resetVolumeBar_() {
  21431. this.volume(1.0);
  21432. this.trigger('volumechange');
  21433. }
  21434. /**
  21435. * Returns all of the current source objects.
  21436. *
  21437. * @return {Tech~SourceObject[]}
  21438. * The current source objects
  21439. */
  21440. currentSources() {
  21441. const source = this.currentSource();
  21442. const sources = [];
  21443. // assume `{}` or `{ src }`
  21444. if (Object.keys(source).length !== 0) {
  21445. sources.push(source);
  21446. }
  21447. return this.cache_.sources || sources;
  21448. }
  21449. /**
  21450. * Returns the current source object.
  21451. *
  21452. * @return {Tech~SourceObject}
  21453. * The current source object
  21454. */
  21455. currentSource() {
  21456. return this.cache_.source || {};
  21457. }
  21458. /**
  21459. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  21460. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  21461. *
  21462. * @return {string}
  21463. * The current source
  21464. */
  21465. currentSrc() {
  21466. return this.currentSource() && this.currentSource().src || '';
  21467. }
  21468. /**
  21469. * Get the current source type e.g. video/mp4
  21470. * This can allow you rebuild the current source object so that you could load the same
  21471. * source and tech later
  21472. *
  21473. * @return {string}
  21474. * The source MIME type
  21475. */
  21476. currentType() {
  21477. return this.currentSource() && this.currentSource().type || '';
  21478. }
  21479. /**
  21480. * Get or set the preload attribute
  21481. *
  21482. * @param {boolean} [value]
  21483. * - true means that we should preload
  21484. * - false means that we should not preload
  21485. *
  21486. * @return {string}
  21487. * The preload attribute value when getting
  21488. */
  21489. preload(value) {
  21490. if (value !== undefined) {
  21491. this.techCall_('setPreload', value);
  21492. this.options_.preload = value;
  21493. return;
  21494. }
  21495. return this.techGet_('preload');
  21496. }
  21497. /**
  21498. * Get or set the autoplay option. When this is a boolean it will
  21499. * modify the attribute on the tech. When this is a string the attribute on
  21500. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  21501. *
  21502. * @param {boolean|string} [value]
  21503. * - true: autoplay using the browser behavior
  21504. * - false: do not autoplay
  21505. * - 'play': call play() on every loadstart
  21506. * - 'muted': call muted() then play() on every loadstart
  21507. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  21508. * - *: values other than those listed here will be set `autoplay` to true
  21509. *
  21510. * @return {boolean|string}
  21511. * The current value of autoplay when getting
  21512. */
  21513. autoplay(value) {
  21514. // getter usage
  21515. if (value === undefined) {
  21516. return this.options_.autoplay || false;
  21517. }
  21518. let techAutoplay;
  21519. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  21520. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  21521. this.options_.autoplay = value;
  21522. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  21523. techAutoplay = false;
  21524. // any falsy value sets autoplay to false in the browser,
  21525. // lets do the same
  21526. } else if (!value) {
  21527. this.options_.autoplay = false;
  21528. // any other value (ie truthy) sets autoplay to true
  21529. } else {
  21530. this.options_.autoplay = true;
  21531. }
  21532. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  21533. // if we don't have a tech then we do not queue up
  21534. // a setAutoplay call on tech ready. We do this because the
  21535. // autoplay option will be passed in the constructor and we
  21536. // do not need to set it twice
  21537. if (this.tech_) {
  21538. this.techCall_('setAutoplay', techAutoplay);
  21539. }
  21540. }
  21541. /**
  21542. * Set or unset the playsinline attribute.
  21543. * Playsinline tells the browser that non-fullscreen playback is preferred.
  21544. *
  21545. * @param {boolean} [value]
  21546. * - true means that we should try to play inline by default
  21547. * - false means that we should use the browser's default playback mode,
  21548. * which in most cases is inline. iOS Safari is a notable exception
  21549. * and plays fullscreen by default.
  21550. *
  21551. * @return {string|Player}
  21552. * - the current value of playsinline
  21553. * - the player when setting
  21554. *
  21555. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  21556. */
  21557. playsinline(value) {
  21558. if (value !== undefined) {
  21559. this.techCall_('setPlaysinline', value);
  21560. this.options_.playsinline = value;
  21561. return this;
  21562. }
  21563. return this.techGet_('playsinline');
  21564. }
  21565. /**
  21566. * Get or set the loop attribute on the video element.
  21567. *
  21568. * @param {boolean} [value]
  21569. * - true means that we should loop the video
  21570. * - false means that we should not loop the video
  21571. *
  21572. * @return {boolean}
  21573. * The current value of loop when getting
  21574. */
  21575. loop(value) {
  21576. if (value !== undefined) {
  21577. this.techCall_('setLoop', value);
  21578. this.options_.loop = value;
  21579. return;
  21580. }
  21581. return this.techGet_('loop');
  21582. }
  21583. /**
  21584. * Get or set the poster image source url
  21585. *
  21586. * @fires Player#posterchange
  21587. *
  21588. * @param {string} [src]
  21589. * Poster image source URL
  21590. *
  21591. * @return {string}
  21592. * The current value of poster when getting
  21593. */
  21594. poster(src) {
  21595. if (src === undefined) {
  21596. return this.poster_;
  21597. }
  21598. // The correct way to remove a poster is to set as an empty string
  21599. // other falsey values will throw errors
  21600. if (!src) {
  21601. src = '';
  21602. }
  21603. if (src === this.poster_) {
  21604. return;
  21605. }
  21606. // update the internal poster variable
  21607. this.poster_ = src;
  21608. // update the tech's poster
  21609. this.techCall_('setPoster', src);
  21610. this.isPosterFromTech_ = false;
  21611. // alert components that the poster has been set
  21612. /**
  21613. * This event fires when the poster image is changed on the player.
  21614. *
  21615. * @event Player#posterchange
  21616. * @type {Event}
  21617. */
  21618. this.trigger('posterchange');
  21619. }
  21620. /**
  21621. * Some techs (e.g. YouTube) can provide a poster source in an
  21622. * asynchronous way. We want the poster component to use this
  21623. * poster source so that it covers up the tech's controls.
  21624. * (YouTube's play button). However we only want to use this
  21625. * source if the player user hasn't set a poster through
  21626. * the normal APIs.
  21627. *
  21628. * @fires Player#posterchange
  21629. * @listens Tech#posterchange
  21630. * @private
  21631. */
  21632. handleTechPosterChange_() {
  21633. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  21634. const newPoster = this.tech_.poster() || '';
  21635. if (newPoster !== this.poster_) {
  21636. this.poster_ = newPoster;
  21637. this.isPosterFromTech_ = true;
  21638. // Let components know the poster has changed
  21639. this.trigger('posterchange');
  21640. }
  21641. }
  21642. }
  21643. /**
  21644. * Get or set whether or not the controls are showing.
  21645. *
  21646. * @fires Player#controlsenabled
  21647. *
  21648. * @param {boolean} [bool]
  21649. * - true to turn controls on
  21650. * - false to turn controls off
  21651. *
  21652. * @return {boolean}
  21653. * The current value of controls when getting
  21654. */
  21655. controls(bool) {
  21656. if (bool === undefined) {
  21657. return !!this.controls_;
  21658. }
  21659. bool = !!bool;
  21660. // Don't trigger a change event unless it actually changed
  21661. if (this.controls_ === bool) {
  21662. return;
  21663. }
  21664. this.controls_ = bool;
  21665. if (this.usingNativeControls()) {
  21666. this.techCall_('setControls', bool);
  21667. }
  21668. if (this.controls_) {
  21669. this.removeClass('vjs-controls-disabled');
  21670. this.addClass('vjs-controls-enabled');
  21671. /**
  21672. * @event Player#controlsenabled
  21673. * @type {Event}
  21674. */
  21675. this.trigger('controlsenabled');
  21676. if (!this.usingNativeControls()) {
  21677. this.addTechControlsListeners_();
  21678. }
  21679. } else {
  21680. this.removeClass('vjs-controls-enabled');
  21681. this.addClass('vjs-controls-disabled');
  21682. /**
  21683. * @event Player#controlsdisabled
  21684. * @type {Event}
  21685. */
  21686. this.trigger('controlsdisabled');
  21687. if (!this.usingNativeControls()) {
  21688. this.removeTechControlsListeners_();
  21689. }
  21690. }
  21691. }
  21692. /**
  21693. * Toggle native controls on/off. Native controls are the controls built into
  21694. * devices (e.g. default iPhone controls) or other techs
  21695. * (e.g. Vimeo Controls)
  21696. * **This should only be set by the current tech, because only the tech knows
  21697. * if it can support native controls**
  21698. *
  21699. * @fires Player#usingnativecontrols
  21700. * @fires Player#usingcustomcontrols
  21701. *
  21702. * @param {boolean} [bool]
  21703. * - true to turn native controls on
  21704. * - false to turn native controls off
  21705. *
  21706. * @return {boolean}
  21707. * The current value of native controls when getting
  21708. */
  21709. usingNativeControls(bool) {
  21710. if (bool === undefined) {
  21711. return !!this.usingNativeControls_;
  21712. }
  21713. bool = !!bool;
  21714. // Don't trigger a change event unless it actually changed
  21715. if (this.usingNativeControls_ === bool) {
  21716. return;
  21717. }
  21718. this.usingNativeControls_ = bool;
  21719. if (this.usingNativeControls_) {
  21720. this.addClass('vjs-using-native-controls');
  21721. /**
  21722. * player is using the native device controls
  21723. *
  21724. * @event Player#usingnativecontrols
  21725. * @type {Event}
  21726. */
  21727. this.trigger('usingnativecontrols');
  21728. } else {
  21729. this.removeClass('vjs-using-native-controls');
  21730. /**
  21731. * player is using the custom HTML controls
  21732. *
  21733. * @event Player#usingcustomcontrols
  21734. * @type {Event}
  21735. */
  21736. this.trigger('usingcustomcontrols');
  21737. }
  21738. }
  21739. /**
  21740. * Set or get the current MediaError
  21741. *
  21742. * @fires Player#error
  21743. *
  21744. * @param {MediaError|string|number} [err]
  21745. * A MediaError or a string/number to be turned
  21746. * into a MediaError
  21747. *
  21748. * @return {MediaError|null}
  21749. * The current MediaError when getting (or null)
  21750. */
  21751. error(err) {
  21752. if (err === undefined) {
  21753. return this.error_ || null;
  21754. }
  21755. // allow hooks to modify error object
  21756. hooks('beforeerror').forEach(hookFunction => {
  21757. const newErr = hookFunction(this, err);
  21758. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  21759. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  21760. return;
  21761. }
  21762. err = newErr;
  21763. });
  21764. // Suppress the first error message for no compatible source until
  21765. // user interaction
  21766. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  21767. const triggerSuppressedError = function () {
  21768. this.error(err);
  21769. };
  21770. this.options_.suppressNotSupportedError = false;
  21771. this.any(['click', 'touchstart'], triggerSuppressedError);
  21772. this.one('loadstart', function () {
  21773. this.off(['click', 'touchstart'], triggerSuppressedError);
  21774. });
  21775. return;
  21776. }
  21777. // restoring to default
  21778. if (err === null) {
  21779. this.error_ = err;
  21780. this.removeClass('vjs-error');
  21781. if (this.errorDisplay) {
  21782. this.errorDisplay.close();
  21783. }
  21784. return;
  21785. }
  21786. this.error_ = new MediaError(err);
  21787. // add the vjs-error classname to the player
  21788. this.addClass('vjs-error');
  21789. // log the name of the error type and any message
  21790. // IE11 logs "[object object]" and required you to expand message to see error object
  21791. log.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  21792. /**
  21793. * @event Player#error
  21794. * @type {Event}
  21795. */
  21796. this.trigger('error');
  21797. // notify hooks of the per player error
  21798. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  21799. return;
  21800. }
  21801. /**
  21802. * Report user activity
  21803. *
  21804. * @param {Object} event
  21805. * Event object
  21806. */
  21807. reportUserActivity(event) {
  21808. this.userActivity_ = true;
  21809. }
  21810. /**
  21811. * Get/set if user is active
  21812. *
  21813. * @fires Player#useractive
  21814. * @fires Player#userinactive
  21815. *
  21816. * @param {boolean} [bool]
  21817. * - true if the user is active
  21818. * - false if the user is inactive
  21819. *
  21820. * @return {boolean}
  21821. * The current value of userActive when getting
  21822. */
  21823. userActive(bool) {
  21824. if (bool === undefined) {
  21825. return this.userActive_;
  21826. }
  21827. bool = !!bool;
  21828. if (bool === this.userActive_) {
  21829. return;
  21830. }
  21831. this.userActive_ = bool;
  21832. if (this.userActive_) {
  21833. this.userActivity_ = true;
  21834. this.removeClass('vjs-user-inactive');
  21835. this.addClass('vjs-user-active');
  21836. /**
  21837. * @event Player#useractive
  21838. * @type {Event}
  21839. */
  21840. this.trigger('useractive');
  21841. return;
  21842. }
  21843. // Chrome/Safari/IE have bugs where when you change the cursor it can
  21844. // trigger a mousemove event. This causes an issue when you're hiding
  21845. // the cursor when the user is inactive, and a mousemove signals user
  21846. // activity. Making it impossible to go into inactive mode. Specifically
  21847. // this happens in fullscreen when we really need to hide the cursor.
  21848. //
  21849. // When this gets resolved in ALL browsers it can be removed
  21850. // https://code.google.com/p/chromium/issues/detail?id=103041
  21851. if (this.tech_) {
  21852. this.tech_.one('mousemove', function (e) {
  21853. e.stopPropagation();
  21854. e.preventDefault();
  21855. });
  21856. }
  21857. this.userActivity_ = false;
  21858. this.removeClass('vjs-user-active');
  21859. this.addClass('vjs-user-inactive');
  21860. /**
  21861. * @event Player#userinactive
  21862. * @type {Event}
  21863. */
  21864. this.trigger('userinactive');
  21865. }
  21866. /**
  21867. * Listen for user activity based on timeout value
  21868. *
  21869. * @private
  21870. */
  21871. listenForUserActivity_() {
  21872. let mouseInProgress;
  21873. let lastMoveX;
  21874. let lastMoveY;
  21875. const handleActivity = bind_(this, this.reportUserActivity);
  21876. const handleMouseMove = function (e) {
  21877. // #1068 - Prevent mousemove spamming
  21878. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  21879. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  21880. lastMoveX = e.screenX;
  21881. lastMoveY = e.screenY;
  21882. handleActivity();
  21883. }
  21884. };
  21885. const handleMouseDown = function () {
  21886. handleActivity();
  21887. // For as long as the they are touching the device or have their mouse down,
  21888. // we consider them active even if they're not moving their finger or mouse.
  21889. // So we want to continue to update that they are active
  21890. this.clearInterval(mouseInProgress);
  21891. // Setting userActivity=true now and setting the interval to the same time
  21892. // as the activityCheck interval (250) should ensure we never miss the
  21893. // next activityCheck
  21894. mouseInProgress = this.setInterval(handleActivity, 250);
  21895. };
  21896. const handleMouseUpAndMouseLeave = function (event) {
  21897. handleActivity();
  21898. // Stop the interval that maintains activity if the mouse/touch is down
  21899. this.clearInterval(mouseInProgress);
  21900. };
  21901. // Any mouse movement will be considered user activity
  21902. this.on('mousedown', handleMouseDown);
  21903. this.on('mousemove', handleMouseMove);
  21904. this.on('mouseup', handleMouseUpAndMouseLeave);
  21905. this.on('mouseleave', handleMouseUpAndMouseLeave);
  21906. const controlBar = this.getChild('controlBar');
  21907. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  21908. // controlBar would no longer be hidden by default timeout.
  21909. if (controlBar && !IS_IOS && !IS_ANDROID) {
  21910. controlBar.on('mouseenter', function (event) {
  21911. if (this.player().options_.inactivityTimeout !== 0) {
  21912. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  21913. }
  21914. this.player().options_.inactivityTimeout = 0;
  21915. });
  21916. controlBar.on('mouseleave', function (event) {
  21917. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  21918. });
  21919. }
  21920. // Listen for keyboard navigation
  21921. // Shouldn't need to use inProgress interval because of key repeat
  21922. this.on('keydown', handleActivity);
  21923. this.on('keyup', handleActivity);
  21924. // Run an interval every 250 milliseconds instead of stuffing everything into
  21925. // the mousemove/touchmove function itself, to prevent performance degradation.
  21926. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  21927. // then gets picked up by this loop
  21928. // http://ejohn.org/blog/learning-from-twitter/
  21929. let inactivityTimeout;
  21930. this.setInterval(function () {
  21931. // Check to see if mouse/touch activity has happened
  21932. if (!this.userActivity_) {
  21933. return;
  21934. }
  21935. // Reset the activity tracker
  21936. this.userActivity_ = false;
  21937. // If the user state was inactive, set the state to active
  21938. this.userActive(true);
  21939. // Clear any existing inactivity timeout to start the timer over
  21940. this.clearTimeout(inactivityTimeout);
  21941. const timeout = this.options_.inactivityTimeout;
  21942. if (timeout <= 0) {
  21943. return;
  21944. }
  21945. // In <timeout> milliseconds, if no more activity has occurred the
  21946. // user will be considered inactive
  21947. inactivityTimeout = this.setTimeout(function () {
  21948. // Protect against the case where the inactivityTimeout can trigger just
  21949. // before the next user activity is picked up by the activity check loop
  21950. // causing a flicker
  21951. if (!this.userActivity_) {
  21952. this.userActive(false);
  21953. }
  21954. }, timeout);
  21955. }, 250);
  21956. }
  21957. /**
  21958. * Gets or sets the current playback rate. A playback rate of
  21959. * 1.0 represents normal speed and 0.5 would indicate half-speed
  21960. * playback, for instance.
  21961. *
  21962. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  21963. *
  21964. * @param {number} [rate]
  21965. * New playback rate to set.
  21966. *
  21967. * @return {number}
  21968. * The current playback rate when getting or 1.0
  21969. */
  21970. playbackRate(rate) {
  21971. if (rate !== undefined) {
  21972. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  21973. // that is registered above
  21974. this.techCall_('setPlaybackRate', rate);
  21975. return;
  21976. }
  21977. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  21978. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  21979. }
  21980. return 1.0;
  21981. }
  21982. /**
  21983. * Gets or sets the current default playback rate. A default playback rate of
  21984. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  21985. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  21986. * not the current playbackRate.
  21987. *
  21988. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  21989. *
  21990. * @param {number} [rate]
  21991. * New default playback rate to set.
  21992. *
  21993. * @return {number|Player}
  21994. * - The default playback rate when getting or 1.0
  21995. * - the player when setting
  21996. */
  21997. defaultPlaybackRate(rate) {
  21998. if (rate !== undefined) {
  21999. return this.techCall_('setDefaultPlaybackRate', rate);
  22000. }
  22001. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22002. return this.techGet_('defaultPlaybackRate');
  22003. }
  22004. return 1.0;
  22005. }
  22006. /**
  22007. * Gets or sets the audio flag
  22008. *
  22009. * @param {boolean} bool
  22010. * - true signals that this is an audio player
  22011. * - false signals that this is not an audio player
  22012. *
  22013. * @return {boolean}
  22014. * The current value of isAudio when getting
  22015. */
  22016. isAudio(bool) {
  22017. if (bool !== undefined) {
  22018. this.isAudio_ = !!bool;
  22019. return;
  22020. }
  22021. return !!this.isAudio_;
  22022. }
  22023. enableAudioOnlyUI_() {
  22024. // Update styling immediately to show the control bar so we can get its height
  22025. this.addClass('vjs-audio-only-mode');
  22026. const playerChildren = this.children();
  22027. const controlBar = this.getChild('ControlBar');
  22028. const controlBarHeight = controlBar && controlBar.currentHeight();
  22029. // Hide all player components except the control bar. Control bar components
  22030. // needed only for video are hidden with CSS
  22031. playerChildren.forEach(child => {
  22032. if (child === controlBar) {
  22033. return;
  22034. }
  22035. if (child.el_ && !child.hasClass('vjs-hidden')) {
  22036. child.hide();
  22037. this.audioOnlyCache_.hiddenChildren.push(child);
  22038. }
  22039. });
  22040. this.audioOnlyCache_.playerHeight = this.currentHeight();
  22041. // Set the player height the same as the control bar
  22042. this.height(controlBarHeight);
  22043. this.trigger('audioonlymodechange');
  22044. }
  22045. disableAudioOnlyUI_() {
  22046. this.removeClass('vjs-audio-only-mode');
  22047. // Show player components that were previously hidden
  22048. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  22049. // Reset player height
  22050. this.height(this.audioOnlyCache_.playerHeight);
  22051. this.trigger('audioonlymodechange');
  22052. }
  22053. /**
  22054. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  22055. *
  22056. * Setting this to `true` will hide all player components except the control bar,
  22057. * as well as control bar components needed only for video.
  22058. *
  22059. * @param {boolean} [value]
  22060. * The value to set audioOnlyMode to.
  22061. *
  22062. * @return {Promise|boolean}
  22063. * A Promise is returned when setting the state, and a boolean when getting
  22064. * the present state
  22065. */
  22066. audioOnlyMode(value) {
  22067. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  22068. return this.audioOnlyMode_;
  22069. }
  22070. this.audioOnlyMode_ = value;
  22071. // Enable Audio Only Mode
  22072. if (value) {
  22073. const exitPromises = [];
  22074. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  22075. if (this.isInPictureInPicture()) {
  22076. exitPromises.push(this.exitPictureInPicture());
  22077. }
  22078. if (this.isFullscreen()) {
  22079. exitPromises.push(this.exitFullscreen());
  22080. }
  22081. if (this.audioPosterMode()) {
  22082. exitPromises.push(this.audioPosterMode(false));
  22083. }
  22084. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  22085. }
  22086. // Disable Audio Only Mode
  22087. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  22088. }
  22089. enablePosterModeUI_() {
  22090. // Hide the video element and show the poster image to enable posterModeUI
  22091. const tech = this.tech_ && this.tech_;
  22092. tech.hide();
  22093. this.addClass('vjs-audio-poster-mode');
  22094. this.trigger('audiopostermodechange');
  22095. }
  22096. disablePosterModeUI_() {
  22097. // Show the video element and hide the poster image to disable posterModeUI
  22098. const tech = this.tech_ && this.tech_;
  22099. tech.show();
  22100. this.removeClass('vjs-audio-poster-mode');
  22101. this.trigger('audiopostermodechange');
  22102. }
  22103. /**
  22104. * Get the current audioPosterMode state or set audioPosterMode to true or false
  22105. *
  22106. * @param {boolean} [value]
  22107. * The value to set audioPosterMode to.
  22108. *
  22109. * @return {Promise|boolean}
  22110. * A Promise is returned when setting the state, and a boolean when getting
  22111. * the present state
  22112. */
  22113. audioPosterMode(value) {
  22114. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  22115. return this.audioPosterMode_;
  22116. }
  22117. this.audioPosterMode_ = value;
  22118. if (value) {
  22119. if (this.audioOnlyMode()) {
  22120. const audioOnlyModePromise = this.audioOnlyMode(false);
  22121. return audioOnlyModePromise.then(() => {
  22122. // enable audio poster mode after audio only mode is disabled
  22123. this.enablePosterModeUI_();
  22124. });
  22125. }
  22126. return Promise.resolve().then(() => {
  22127. // enable audio poster mode
  22128. this.enablePosterModeUI_();
  22129. });
  22130. }
  22131. return Promise.resolve().then(() => {
  22132. // disable audio poster mode
  22133. this.disablePosterModeUI_();
  22134. });
  22135. }
  22136. /**
  22137. * A helper method for adding a {@link TextTrack} to our
  22138. * {@link TextTrackList}.
  22139. *
  22140. * In addition to the W3C settings we allow adding additional info through options.
  22141. *
  22142. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  22143. *
  22144. * @param {string} [kind]
  22145. * the kind of TextTrack you are adding
  22146. *
  22147. * @param {string} [label]
  22148. * the label to give the TextTrack label
  22149. *
  22150. * @param {string} [language]
  22151. * the language to set on the TextTrack
  22152. *
  22153. * @return {TextTrack|undefined}
  22154. * the TextTrack that was added or undefined
  22155. * if there is no tech
  22156. */
  22157. addTextTrack(kind, label, language) {
  22158. if (this.tech_) {
  22159. return this.tech_.addTextTrack(kind, label, language);
  22160. }
  22161. }
  22162. /**
  22163. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  22164. *
  22165. * @param {Object} options
  22166. * Options to pass to {@link HTMLTrackElement} during creation. See
  22167. * {@link HTMLTrackElement} for object properties that you should use.
  22168. *
  22169. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  22170. * from the TextTrackList and HtmlTrackElementList
  22171. * after a source change
  22172. *
  22173. * @return { import('./tracks/html-track-element').default }
  22174. * the HTMLTrackElement that was created and added
  22175. * to the HtmlTrackElementList and the remote
  22176. * TextTrackList
  22177. *
  22178. */
  22179. addRemoteTextTrack(options, manualCleanup) {
  22180. if (this.tech_) {
  22181. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  22182. }
  22183. }
  22184. /**
  22185. * Remove a remote {@link TextTrack} from the respective
  22186. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  22187. *
  22188. * @param {Object} track
  22189. * Remote {@link TextTrack} to remove
  22190. *
  22191. * @return {undefined}
  22192. * does not return anything
  22193. */
  22194. removeRemoteTextTrack(obj = {}) {
  22195. let {
  22196. track
  22197. } = obj;
  22198. if (!track) {
  22199. track = obj;
  22200. }
  22201. // destructure the input into an object with a track argument, defaulting to arguments[0]
  22202. // default the whole argument to an empty object if nothing was passed in
  22203. if (this.tech_) {
  22204. return this.tech_.removeRemoteTextTrack(track);
  22205. }
  22206. }
  22207. /**
  22208. * Gets available media playback quality metrics as specified by the W3C's Media
  22209. * Playback Quality API.
  22210. *
  22211. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  22212. *
  22213. * @return {Object|undefined}
  22214. * An object with supported media playback quality metrics or undefined if there
  22215. * is no tech or the tech does not support it.
  22216. */
  22217. getVideoPlaybackQuality() {
  22218. return this.techGet_('getVideoPlaybackQuality');
  22219. }
  22220. /**
  22221. * Get video width
  22222. *
  22223. * @return {number}
  22224. * current video width
  22225. */
  22226. videoWidth() {
  22227. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  22228. }
  22229. /**
  22230. * Get video height
  22231. *
  22232. * @return {number}
  22233. * current video height
  22234. */
  22235. videoHeight() {
  22236. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  22237. }
  22238. /**
  22239. * The player's language code.
  22240. *
  22241. * Changing the language will trigger
  22242. * [languagechange]{@link Player#event:languagechange}
  22243. * which Components can use to update control text.
  22244. * ClickableComponent will update its control text by default on
  22245. * [languagechange]{@link Player#event:languagechange}.
  22246. *
  22247. * @fires Player#languagechange
  22248. *
  22249. * @param {string} [code]
  22250. * the language code to set the player to
  22251. *
  22252. * @return {string}
  22253. * The current language code when getting
  22254. */
  22255. language(code) {
  22256. if (code === undefined) {
  22257. return this.language_;
  22258. }
  22259. if (this.language_ !== String(code).toLowerCase()) {
  22260. this.language_ = String(code).toLowerCase();
  22261. // during first init, it's possible some things won't be evented
  22262. if (isEvented(this)) {
  22263. /**
  22264. * fires when the player language change
  22265. *
  22266. * @event Player#languagechange
  22267. * @type {Event}
  22268. */
  22269. this.trigger('languagechange');
  22270. }
  22271. }
  22272. }
  22273. /**
  22274. * Get the player's language dictionary
  22275. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  22276. * Languages specified directly in the player options have precedence
  22277. *
  22278. * @return {Array}
  22279. * An array of of supported languages
  22280. */
  22281. languages() {
  22282. return merge(Player.prototype.options_.languages, this.languages_);
  22283. }
  22284. /**
  22285. * returns a JavaScript object representing the current track
  22286. * information. **DOES not return it as JSON**
  22287. *
  22288. * @return {Object}
  22289. * Object representing the current of track info
  22290. */
  22291. toJSON() {
  22292. const options = merge(this.options_);
  22293. const tracks = options.tracks;
  22294. options.tracks = [];
  22295. for (let i = 0; i < tracks.length; i++) {
  22296. let track = tracks[i];
  22297. // deep merge tracks and null out player so no circular references
  22298. track = merge(track);
  22299. track.player = undefined;
  22300. options.tracks[i] = track;
  22301. }
  22302. return options;
  22303. }
  22304. /**
  22305. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  22306. * component) that immediately overlays the player with arbitrary
  22307. * content and removes itself when closed.
  22308. *
  22309. * @param {string|Function|Element|Array|null} content
  22310. * Same as {@link ModalDialog#content}'s param of the same name.
  22311. * The most straight-forward usage is to provide a string or DOM
  22312. * element.
  22313. *
  22314. * @param {Object} [options]
  22315. * Extra options which will be passed on to the {@link ModalDialog}.
  22316. *
  22317. * @return {ModalDialog}
  22318. * the {@link ModalDialog} that was created
  22319. */
  22320. createModal(content, options) {
  22321. options = options || {};
  22322. options.content = content || '';
  22323. const modal = new ModalDialog(this, options);
  22324. this.addChild(modal);
  22325. modal.on('dispose', () => {
  22326. this.removeChild(modal);
  22327. });
  22328. modal.open();
  22329. return modal;
  22330. }
  22331. /**
  22332. * Change breakpoint classes when the player resizes.
  22333. *
  22334. * @private
  22335. */
  22336. updateCurrentBreakpoint_() {
  22337. if (!this.responsive()) {
  22338. return;
  22339. }
  22340. const currentBreakpoint = this.currentBreakpoint();
  22341. const currentWidth = this.currentWidth();
  22342. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  22343. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  22344. const maxWidth = this.breakpoints_[candidateBreakpoint];
  22345. if (currentWidth <= maxWidth) {
  22346. // The current breakpoint did not change, nothing to do.
  22347. if (currentBreakpoint === candidateBreakpoint) {
  22348. return;
  22349. }
  22350. // Only remove a class if there is a current breakpoint.
  22351. if (currentBreakpoint) {
  22352. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  22353. }
  22354. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  22355. this.breakpoint_ = candidateBreakpoint;
  22356. break;
  22357. }
  22358. }
  22359. }
  22360. /**
  22361. * Removes the current breakpoint.
  22362. *
  22363. * @private
  22364. */
  22365. removeCurrentBreakpoint_() {
  22366. const className = this.currentBreakpointClass();
  22367. this.breakpoint_ = '';
  22368. if (className) {
  22369. this.removeClass(className);
  22370. }
  22371. }
  22372. /**
  22373. * Get or set breakpoints on the player.
  22374. *
  22375. * Calling this method with an object or `true` will remove any previous
  22376. * custom breakpoints and start from the defaults again.
  22377. *
  22378. * @param {Object|boolean} [breakpoints]
  22379. * If an object is given, it can be used to provide custom
  22380. * breakpoints. If `true` is given, will set default breakpoints.
  22381. * If this argument is not given, will simply return the current
  22382. * breakpoints.
  22383. *
  22384. * @param {number} [breakpoints.tiny]
  22385. * The maximum width for the "vjs-layout-tiny" class.
  22386. *
  22387. * @param {number} [breakpoints.xsmall]
  22388. * The maximum width for the "vjs-layout-x-small" class.
  22389. *
  22390. * @param {number} [breakpoints.small]
  22391. * The maximum width for the "vjs-layout-small" class.
  22392. *
  22393. * @param {number} [breakpoints.medium]
  22394. * The maximum width for the "vjs-layout-medium" class.
  22395. *
  22396. * @param {number} [breakpoints.large]
  22397. * The maximum width for the "vjs-layout-large" class.
  22398. *
  22399. * @param {number} [breakpoints.xlarge]
  22400. * The maximum width for the "vjs-layout-x-large" class.
  22401. *
  22402. * @param {number} [breakpoints.huge]
  22403. * The maximum width for the "vjs-layout-huge" class.
  22404. *
  22405. * @return {Object}
  22406. * An object mapping breakpoint names to maximum width values.
  22407. */
  22408. breakpoints(breakpoints) {
  22409. // Used as a getter.
  22410. if (breakpoints === undefined) {
  22411. return Object.assign(this.breakpoints_);
  22412. }
  22413. this.breakpoint_ = '';
  22414. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  22415. // When breakpoint definitions change, we need to update the currently
  22416. // selected breakpoint.
  22417. this.updateCurrentBreakpoint_();
  22418. // Clone the breakpoints before returning.
  22419. return Object.assign(this.breakpoints_);
  22420. }
  22421. /**
  22422. * Get or set a flag indicating whether or not this player should adjust
  22423. * its UI based on its dimensions.
  22424. *
  22425. * @param {boolean} value
  22426. * Should be `true` if the player should adjust its UI based on its
  22427. * dimensions; otherwise, should be `false`.
  22428. *
  22429. * @return {boolean}
  22430. * Will be `true` if this player should adjust its UI based on its
  22431. * dimensions; otherwise, will be `false`.
  22432. */
  22433. responsive(value) {
  22434. // Used as a getter.
  22435. if (value === undefined) {
  22436. return this.responsive_;
  22437. }
  22438. value = Boolean(value);
  22439. const current = this.responsive_;
  22440. // Nothing changed.
  22441. if (value === current) {
  22442. return;
  22443. }
  22444. // The value actually changed, set it.
  22445. this.responsive_ = value;
  22446. // Start listening for breakpoints and set the initial breakpoint if the
  22447. // player is now responsive.
  22448. if (value) {
  22449. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  22450. this.updateCurrentBreakpoint_();
  22451. // Stop listening for breakpoints if the player is no longer responsive.
  22452. } else {
  22453. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  22454. this.removeCurrentBreakpoint_();
  22455. }
  22456. return value;
  22457. }
  22458. /**
  22459. * Get current breakpoint name, if any.
  22460. *
  22461. * @return {string}
  22462. * If there is currently a breakpoint set, returns a the key from the
  22463. * breakpoints object matching it. Otherwise, returns an empty string.
  22464. */
  22465. currentBreakpoint() {
  22466. return this.breakpoint_;
  22467. }
  22468. /**
  22469. * Get the current breakpoint class name.
  22470. *
  22471. * @return {string}
  22472. * The matching class name (e.g. `"vjs-layout-tiny"` or
  22473. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  22474. * there is no current breakpoint.
  22475. */
  22476. currentBreakpointClass() {
  22477. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  22478. }
  22479. /**
  22480. * An object that describes a single piece of media.
  22481. *
  22482. * Properties that are not part of this type description will be retained; so,
  22483. * this can be viewed as a generic metadata storage mechanism as well.
  22484. *
  22485. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  22486. * @typedef {Object} Player~MediaObject
  22487. *
  22488. * @property {string} [album]
  22489. * Unused, except if this object is passed to the `MediaSession`
  22490. * API.
  22491. *
  22492. * @property {string} [artist]
  22493. * Unused, except if this object is passed to the `MediaSession`
  22494. * API.
  22495. *
  22496. * @property {Object[]} [artwork]
  22497. * Unused, except if this object is passed to the `MediaSession`
  22498. * API. If not specified, will be populated via the `poster`, if
  22499. * available.
  22500. *
  22501. * @property {string} [poster]
  22502. * URL to an image that will display before playback.
  22503. *
  22504. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  22505. * A single source object, an array of source objects, or a string
  22506. * referencing a URL to a media source. It is _highly recommended_
  22507. * that an object or array of objects is used here, so that source
  22508. * selection algorithms can take the `type` into account.
  22509. *
  22510. * @property {string} [title]
  22511. * Unused, except if this object is passed to the `MediaSession`
  22512. * API.
  22513. *
  22514. * @property {Object[]} [textTracks]
  22515. * An array of objects to be used to create text tracks, following
  22516. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  22517. * For ease of removal, these will be created as "remote" text
  22518. * tracks and set to automatically clean up on source changes.
  22519. *
  22520. * These objects may have properties like `src`, `kind`, `label`,
  22521. * and `language`, see {@link Tech#createRemoteTextTrack}.
  22522. */
  22523. /**
  22524. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  22525. *
  22526. * @param {Player~MediaObject} media
  22527. * A media object.
  22528. *
  22529. * @param {Function} ready
  22530. * A callback to be called when the player is ready.
  22531. */
  22532. loadMedia(media, ready) {
  22533. if (!media || typeof media !== 'object') {
  22534. return;
  22535. }
  22536. this.reset();
  22537. // Clone the media object so it cannot be mutated from outside.
  22538. this.cache_.media = merge(media);
  22539. const {
  22540. artist,
  22541. artwork,
  22542. description,
  22543. poster,
  22544. src,
  22545. textTracks,
  22546. title
  22547. } = this.cache_.media;
  22548. // If `artwork` is not given, create it using `poster`.
  22549. if (!artwork && poster) {
  22550. this.cache_.media.artwork = [{
  22551. src: poster,
  22552. type: getMimetype(poster)
  22553. }];
  22554. }
  22555. if (src) {
  22556. this.src(src);
  22557. }
  22558. if (poster) {
  22559. this.poster(poster);
  22560. }
  22561. if (Array.isArray(textTracks)) {
  22562. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  22563. }
  22564. if (this.titleBar) {
  22565. this.titleBar.update({
  22566. title,
  22567. description: description || artist || ''
  22568. });
  22569. }
  22570. this.ready(ready);
  22571. }
  22572. /**
  22573. * Get a clone of the current {@link Player~MediaObject} for this player.
  22574. *
  22575. * If the `loadMedia` method has not been used, will attempt to return a
  22576. * {@link Player~MediaObject} based on the current state of the player.
  22577. *
  22578. * @return {Player~MediaObject}
  22579. */
  22580. getMedia() {
  22581. if (!this.cache_.media) {
  22582. const poster = this.poster();
  22583. const src = this.currentSources();
  22584. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  22585. kind: tt.kind,
  22586. label: tt.label,
  22587. language: tt.language,
  22588. src: tt.src
  22589. }));
  22590. const media = {
  22591. src,
  22592. textTracks
  22593. };
  22594. if (poster) {
  22595. media.poster = poster;
  22596. media.artwork = [{
  22597. src: media.poster,
  22598. type: getMimetype(media.poster)
  22599. }];
  22600. }
  22601. return media;
  22602. }
  22603. return merge(this.cache_.media);
  22604. }
  22605. /**
  22606. * Gets tag settings
  22607. *
  22608. * @param {Element} tag
  22609. * The player tag
  22610. *
  22611. * @return {Object}
  22612. * An object containing all of the settings
  22613. * for a player tag
  22614. */
  22615. static getTagSettings(tag) {
  22616. const baseOptions = {
  22617. sources: [],
  22618. tracks: []
  22619. };
  22620. const tagOptions = getAttributes(tag);
  22621. const dataSetup = tagOptions['data-setup'];
  22622. if (hasClass(tag, 'vjs-fill')) {
  22623. tagOptions.fill = true;
  22624. }
  22625. if (hasClass(tag, 'vjs-fluid')) {
  22626. tagOptions.fluid = true;
  22627. }
  22628. // Check if data-setup attr exists.
  22629. if (dataSetup !== null) {
  22630. // Parse options JSON
  22631. // If empty string, make it a parsable json object.
  22632. const [err, data] = safeParseTuple(dataSetup || '{}');
  22633. if (err) {
  22634. log.error(err);
  22635. }
  22636. Object.assign(tagOptions, data);
  22637. }
  22638. Object.assign(baseOptions, tagOptions);
  22639. // Get tag children settings
  22640. if (tag.hasChildNodes()) {
  22641. const children = tag.childNodes;
  22642. for (let i = 0, j = children.length; i < j; i++) {
  22643. const child = children[i];
  22644. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  22645. const childName = child.nodeName.toLowerCase();
  22646. if (childName === 'source') {
  22647. baseOptions.sources.push(getAttributes(child));
  22648. } else if (childName === 'track') {
  22649. baseOptions.tracks.push(getAttributes(child));
  22650. }
  22651. }
  22652. }
  22653. return baseOptions;
  22654. }
  22655. /**
  22656. * Set debug mode to enable/disable logs at info level.
  22657. *
  22658. * @param {boolean} enabled
  22659. * @fires Player#debugon
  22660. * @fires Player#debugoff
  22661. */
  22662. debug(enabled) {
  22663. if (enabled === undefined) {
  22664. return this.debugEnabled_;
  22665. }
  22666. if (enabled) {
  22667. this.trigger('debugon');
  22668. this.previousLogLevel_ = this.log.level;
  22669. this.log.level('debug');
  22670. this.debugEnabled_ = true;
  22671. } else {
  22672. this.trigger('debugoff');
  22673. this.log.level(this.previousLogLevel_);
  22674. this.previousLogLevel_ = undefined;
  22675. this.debugEnabled_ = false;
  22676. }
  22677. }
  22678. /**
  22679. * Set or get current playback rates.
  22680. * Takes an array and updates the playback rates menu with the new items.
  22681. * Pass in an empty array to hide the menu.
  22682. * Values other than arrays are ignored.
  22683. *
  22684. * @fires Player#playbackrateschange
  22685. * @param {number[]} newRates
  22686. * The new rates that the playback rates menu should update to.
  22687. * An empty array will hide the menu
  22688. * @return {number[]} When used as a getter will return the current playback rates
  22689. */
  22690. playbackRates(newRates) {
  22691. if (newRates === undefined) {
  22692. return this.cache_.playbackRates;
  22693. }
  22694. // ignore any value that isn't an array
  22695. if (!Array.isArray(newRates)) {
  22696. return;
  22697. }
  22698. // ignore any arrays that don't only contain numbers
  22699. if (!newRates.every(rate => typeof rate === 'number')) {
  22700. return;
  22701. }
  22702. this.cache_.playbackRates = newRates;
  22703. /**
  22704. * fires when the playback rates in a player are changed
  22705. *
  22706. * @event Player#playbackrateschange
  22707. * @type {Event}
  22708. */
  22709. this.trigger('playbackrateschange');
  22710. }
  22711. }
  22712. /**
  22713. * Get the {@link VideoTrackList}
  22714. *
  22715. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  22716. *
  22717. * @return {VideoTrackList}
  22718. * the current video track list
  22719. *
  22720. * @method Player.prototype.videoTracks
  22721. */
  22722. /**
  22723. * Get the {@link AudioTrackList}
  22724. *
  22725. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  22726. *
  22727. * @return {AudioTrackList}
  22728. * the current audio track list
  22729. *
  22730. * @method Player.prototype.audioTracks
  22731. */
  22732. /**
  22733. * Get the {@link TextTrackList}
  22734. *
  22735. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  22736. *
  22737. * @return {TextTrackList}
  22738. * the current text track list
  22739. *
  22740. * @method Player.prototype.textTracks
  22741. */
  22742. /**
  22743. * Get the remote {@link TextTrackList}
  22744. *
  22745. * @return {TextTrackList}
  22746. * The current remote text track list
  22747. *
  22748. * @method Player.prototype.remoteTextTracks
  22749. */
  22750. /**
  22751. * Get the remote {@link HtmlTrackElementList} tracks.
  22752. *
  22753. * @return {HtmlTrackElementList}
  22754. * The current remote text track element list
  22755. *
  22756. * @method Player.prototype.remoteTextTrackEls
  22757. */
  22758. ALL.names.forEach(function (name) {
  22759. const props = ALL[name];
  22760. Player.prototype[props.getterName] = function () {
  22761. if (this.tech_) {
  22762. return this.tech_[props.getterName]();
  22763. }
  22764. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  22765. // these will be passed to the tech during loading
  22766. this[props.privateName] = this[props.privateName] || new props.ListClass();
  22767. return this[props.privateName];
  22768. };
  22769. });
  22770. /**
  22771. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  22772. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  22773. * behavior.
  22774. *
  22775. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  22776. *
  22777. * @param {string} [value]
  22778. * The value to set the `Player`'s crossorigin to. If an argument is
  22779. * given, must be one of `anonymous` or `use-credentials`.
  22780. *
  22781. * @return {string|undefined}
  22782. * - The current crossorigin value of the `Player` when getting.
  22783. * - undefined when setting
  22784. */
  22785. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  22786. /**
  22787. * Global enumeration of players.
  22788. *
  22789. * The keys are the player IDs and the values are either the {@link Player}
  22790. * instance or `null` for disposed players.
  22791. *
  22792. * @type {Object}
  22793. */
  22794. Player.players = {};
  22795. const navigator = window.navigator;
  22796. /*
  22797. * Player instance options, surfaced using options
  22798. * options = Player.prototype.options_
  22799. * Make changes in options, not here.
  22800. *
  22801. * @type {Object}
  22802. * @private
  22803. */
  22804. Player.prototype.options_ = {
  22805. // Default order of fallback technology
  22806. techOrder: Tech.defaultTechOrder_,
  22807. html5: {},
  22808. // enable sourceset by default
  22809. enableSourceset: true,
  22810. // default inactivity timeout
  22811. inactivityTimeout: 2000,
  22812. // default playback rates
  22813. playbackRates: [],
  22814. // Add playback rate selection by adding rates
  22815. // 'playbackRates': [0.5, 1, 1.5, 2],
  22816. liveui: false,
  22817. // Included control sets
  22818. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  22819. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  22820. // locales and their language translations
  22821. languages: {},
  22822. // Default message to show when a video cannot be played.
  22823. notSupportedMessage: 'No compatible source was found for this media.',
  22824. normalizeAutoplay: false,
  22825. fullscreen: {
  22826. options: {
  22827. navigationUI: 'hide'
  22828. }
  22829. },
  22830. breakpoints: {},
  22831. responsive: false,
  22832. audioOnlyMode: false,
  22833. audioPosterMode: false
  22834. };
  22835. [
  22836. /**
  22837. * Returns whether or not the player is in the "ended" state.
  22838. *
  22839. * @return {Boolean} True if the player is in the ended state, false if not.
  22840. * @method Player#ended
  22841. */
  22842. 'ended',
  22843. /**
  22844. * Returns whether or not the player is in the "seeking" state.
  22845. *
  22846. * @return {Boolean} True if the player is in the seeking state, false if not.
  22847. * @method Player#seeking
  22848. */
  22849. 'seeking',
  22850. /**
  22851. * Returns the TimeRanges of the media that are currently available
  22852. * for seeking to.
  22853. *
  22854. * @return {TimeRanges} the seekable intervals of the media timeline
  22855. * @method Player#seekable
  22856. */
  22857. 'seekable',
  22858. /**
  22859. * Returns the current state of network activity for the element, from
  22860. * the codes in the list below.
  22861. * - NETWORK_EMPTY (numeric value 0)
  22862. * The element has not yet been initialised. All attributes are in
  22863. * their initial states.
  22864. * - NETWORK_IDLE (numeric value 1)
  22865. * The element's resource selection algorithm is active and has
  22866. * selected a resource, but it is not actually using the network at
  22867. * this time.
  22868. * - NETWORK_LOADING (numeric value 2)
  22869. * The user agent is actively trying to download data.
  22870. * - NETWORK_NO_SOURCE (numeric value 3)
  22871. * The element's resource selection algorithm is active, but it has
  22872. * not yet found a resource to use.
  22873. *
  22874. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  22875. * @return {number} the current network activity state
  22876. * @method Player#networkState
  22877. */
  22878. 'networkState',
  22879. /**
  22880. * Returns a value that expresses the current state of the element
  22881. * with respect to rendering the current playback position, from the
  22882. * codes in the list below.
  22883. * - HAVE_NOTHING (numeric value 0)
  22884. * No information regarding the media resource is available.
  22885. * - HAVE_METADATA (numeric value 1)
  22886. * Enough of the resource has been obtained that the duration of the
  22887. * resource is available.
  22888. * - HAVE_CURRENT_DATA (numeric value 2)
  22889. * Data for the immediate current playback position is available.
  22890. * - HAVE_FUTURE_DATA (numeric value 3)
  22891. * Data for the immediate current playback position is available, as
  22892. * well as enough data for the user agent to advance the current
  22893. * playback position in the direction of playback.
  22894. * - HAVE_ENOUGH_DATA (numeric value 4)
  22895. * The user agent estimates that enough data is available for
  22896. * playback to proceed uninterrupted.
  22897. *
  22898. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  22899. * @return {number} the current playback rendering state
  22900. * @method Player#readyState
  22901. */
  22902. 'readyState'].forEach(function (fn) {
  22903. Player.prototype[fn] = function () {
  22904. return this.techGet_(fn);
  22905. };
  22906. });
  22907. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  22908. Player.prototype[`handleTech${toTitleCase(event)}_`] = function () {
  22909. return this.trigger(event);
  22910. };
  22911. });
  22912. /**
  22913. * Fired when the player has initial duration and dimension information
  22914. *
  22915. * @event Player#loadedmetadata
  22916. * @type {Event}
  22917. */
  22918. /**
  22919. * Fired when the player has downloaded data at the current playback position
  22920. *
  22921. * @event Player#loadeddata
  22922. * @type {Event}
  22923. */
  22924. /**
  22925. * Fired when the current playback position has changed *
  22926. * During playback this is fired every 15-250 milliseconds, depending on the
  22927. * playback technology in use.
  22928. *
  22929. * @event Player#timeupdate
  22930. * @type {Event}
  22931. */
  22932. /**
  22933. * Fired when the volume changes
  22934. *
  22935. * @event Player#volumechange
  22936. * @type {Event}
  22937. */
  22938. /**
  22939. * Reports whether or not a player has a plugin available.
  22940. *
  22941. * This does not report whether or not the plugin has ever been initialized
  22942. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  22943. *
  22944. * @method Player#hasPlugin
  22945. * @param {string} name
  22946. * The name of a plugin.
  22947. *
  22948. * @return {boolean}
  22949. * Whether or not this player has the requested plugin available.
  22950. */
  22951. /**
  22952. * Reports whether or not a player is using a plugin by name.
  22953. *
  22954. * For basic plugins, this only reports whether the plugin has _ever_ been
  22955. * initialized on this player.
  22956. *
  22957. * @method Player#usingPlugin
  22958. * @param {string} name
  22959. * The name of a plugin.
  22960. *
  22961. * @return {boolean}
  22962. * Whether or not this player is using the requested plugin.
  22963. */
  22964. Component.registerComponent('Player', Player);
  22965. /**
  22966. * @file plugin.js
  22967. */
  22968. /**
  22969. * The base plugin name.
  22970. *
  22971. * @private
  22972. * @constant
  22973. * @type {string}
  22974. */
  22975. const BASE_PLUGIN_NAME = 'plugin';
  22976. /**
  22977. * The key on which a player's active plugins cache is stored.
  22978. *
  22979. * @private
  22980. * @constant
  22981. * @type {string}
  22982. */
  22983. const PLUGIN_CACHE_KEY = 'activePlugins_';
  22984. /**
  22985. * Stores registered plugins in a private space.
  22986. *
  22987. * @private
  22988. * @type {Object}
  22989. */
  22990. const pluginStorage = {};
  22991. /**
  22992. * Reports whether or not a plugin has been registered.
  22993. *
  22994. * @private
  22995. * @param {string} name
  22996. * The name of a plugin.
  22997. *
  22998. * @return {boolean}
  22999. * Whether or not the plugin has been registered.
  23000. */
  23001. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  23002. /**
  23003. * Get a single registered plugin by name.
  23004. *
  23005. * @private
  23006. * @param {string} name
  23007. * The name of a plugin.
  23008. *
  23009. * @return {typeof Plugin|Function|undefined}
  23010. * The plugin (or undefined).
  23011. */
  23012. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  23013. /**
  23014. * Marks a plugin as "active" on a player.
  23015. *
  23016. * Also, ensures that the player has an object for tracking active plugins.
  23017. *
  23018. * @private
  23019. * @param {Player} player
  23020. * A Video.js player instance.
  23021. *
  23022. * @param {string} name
  23023. * The name of a plugin.
  23024. */
  23025. const markPluginAsActive = (player, name) => {
  23026. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  23027. player[PLUGIN_CACHE_KEY][name] = true;
  23028. };
  23029. /**
  23030. * Triggers a pair of plugin setup events.
  23031. *
  23032. * @private
  23033. * @param {Player} player
  23034. * A Video.js player instance.
  23035. *
  23036. * @param {Plugin~PluginEventHash} hash
  23037. * A plugin event hash.
  23038. *
  23039. * @param {boolean} [before]
  23040. * If true, prefixes the event name with "before". In other words,
  23041. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  23042. */
  23043. const triggerSetupEvent = (player, hash, before) => {
  23044. const eventName = (before ? 'before' : '') + 'pluginsetup';
  23045. player.trigger(eventName, hash);
  23046. player.trigger(eventName + ':' + hash.name, hash);
  23047. };
  23048. /**
  23049. * Takes a basic plugin function and returns a wrapper function which marks
  23050. * on the player that the plugin has been activated.
  23051. *
  23052. * @private
  23053. * @param {string} name
  23054. * The name of the plugin.
  23055. *
  23056. * @param {Function} plugin
  23057. * The basic plugin.
  23058. *
  23059. * @return {Function}
  23060. * A wrapper function for the given plugin.
  23061. */
  23062. const createBasicPlugin = function (name, plugin) {
  23063. const basicPluginWrapper = function () {
  23064. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  23065. // regardless, but we want the hash to be consistent with the hash provided
  23066. // for advanced plugins.
  23067. //
  23068. // The only potentially counter-intuitive thing here is the `instance` in
  23069. // the "pluginsetup" event is the value returned by the `plugin` function.
  23070. triggerSetupEvent(this, {
  23071. name,
  23072. plugin,
  23073. instance: null
  23074. }, true);
  23075. const instance = plugin.apply(this, arguments);
  23076. markPluginAsActive(this, name);
  23077. triggerSetupEvent(this, {
  23078. name,
  23079. plugin,
  23080. instance
  23081. });
  23082. return instance;
  23083. };
  23084. Object.keys(plugin).forEach(function (prop) {
  23085. basicPluginWrapper[prop] = plugin[prop];
  23086. });
  23087. return basicPluginWrapper;
  23088. };
  23089. /**
  23090. * Takes a plugin sub-class and returns a factory function for generating
  23091. * instances of it.
  23092. *
  23093. * This factory function will replace itself with an instance of the requested
  23094. * sub-class of Plugin.
  23095. *
  23096. * @private
  23097. * @param {string} name
  23098. * The name of the plugin.
  23099. *
  23100. * @param {Plugin} PluginSubClass
  23101. * The advanced plugin.
  23102. *
  23103. * @return {Function}
  23104. */
  23105. const createPluginFactory = (name, PluginSubClass) => {
  23106. // Add a `name` property to the plugin prototype so that each plugin can
  23107. // refer to itself by name.
  23108. PluginSubClass.prototype.name = name;
  23109. return function (...args) {
  23110. triggerSetupEvent(this, {
  23111. name,
  23112. plugin: PluginSubClass,
  23113. instance: null
  23114. }, true);
  23115. const instance = new PluginSubClass(...[this, ...args]);
  23116. // The plugin is replaced by a function that returns the current instance.
  23117. this[name] = () => instance;
  23118. triggerSetupEvent(this, instance.getEventHash());
  23119. return instance;
  23120. };
  23121. };
  23122. /**
  23123. * Parent class for all advanced plugins.
  23124. *
  23125. * @mixes module:evented~EventedMixin
  23126. * @mixes module:stateful~StatefulMixin
  23127. * @fires Player#beforepluginsetup
  23128. * @fires Player#beforepluginsetup:$name
  23129. * @fires Player#pluginsetup
  23130. * @fires Player#pluginsetup:$name
  23131. * @listens Player#dispose
  23132. * @throws {Error}
  23133. * If attempting to instantiate the base {@link Plugin} class
  23134. * directly instead of via a sub-class.
  23135. */
  23136. class Plugin {
  23137. /**
  23138. * Creates an instance of this class.
  23139. *
  23140. * Sub-classes should call `super` to ensure plugins are properly initialized.
  23141. *
  23142. * @param {Player} player
  23143. * A Video.js player instance.
  23144. */
  23145. constructor(player) {
  23146. if (this.constructor === Plugin) {
  23147. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  23148. }
  23149. this.player = player;
  23150. if (!this.log) {
  23151. this.log = this.player.log.createLogger(this.name);
  23152. }
  23153. // Make this object evented, but remove the added `trigger` method so we
  23154. // use the prototype version instead.
  23155. evented(this);
  23156. delete this.trigger;
  23157. stateful(this, this.constructor.defaultState);
  23158. markPluginAsActive(player, this.name);
  23159. // Auto-bind the dispose method so we can use it as a listener and unbind
  23160. // it later easily.
  23161. this.dispose = this.dispose.bind(this);
  23162. // If the player is disposed, dispose the plugin.
  23163. player.on('dispose', this.dispose);
  23164. }
  23165. /**
  23166. * Get the version of the plugin that was set on <pluginName>.VERSION
  23167. */
  23168. version() {
  23169. return this.constructor.VERSION;
  23170. }
  23171. /**
  23172. * Each event triggered by plugins includes a hash of additional data with
  23173. * conventional properties.
  23174. *
  23175. * This returns that object or mutates an existing hash.
  23176. *
  23177. * @param {Object} [hash={}]
  23178. * An object to be used as event an event hash.
  23179. *
  23180. * @return {Plugin~PluginEventHash}
  23181. * An event hash object with provided properties mixed-in.
  23182. */
  23183. getEventHash(hash = {}) {
  23184. hash.name = this.name;
  23185. hash.plugin = this.constructor;
  23186. hash.instance = this;
  23187. return hash;
  23188. }
  23189. /**
  23190. * Triggers an event on the plugin object and overrides
  23191. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  23192. *
  23193. * @param {string|Object} event
  23194. * An event type or an object with a type property.
  23195. *
  23196. * @param {Object} [hash={}]
  23197. * Additional data hash to merge with a
  23198. * {@link Plugin~PluginEventHash|PluginEventHash}.
  23199. *
  23200. * @return {boolean}
  23201. * Whether or not default was prevented.
  23202. */
  23203. trigger(event, hash = {}) {
  23204. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  23205. }
  23206. /**
  23207. * Handles "statechanged" events on the plugin. No-op by default, override by
  23208. * subclassing.
  23209. *
  23210. * @abstract
  23211. * @param {Event} e
  23212. * An event object provided by a "statechanged" event.
  23213. *
  23214. * @param {Object} e.changes
  23215. * An object describing changes that occurred with the "statechanged"
  23216. * event.
  23217. */
  23218. handleStateChanged(e) {}
  23219. /**
  23220. * Disposes a plugin.
  23221. *
  23222. * Subclasses can override this if they want, but for the sake of safety,
  23223. * it's probably best to subscribe the "dispose" event.
  23224. *
  23225. * @fires Plugin#dispose
  23226. */
  23227. dispose() {
  23228. const {
  23229. name,
  23230. player
  23231. } = this;
  23232. /**
  23233. * Signals that a advanced plugin is about to be disposed.
  23234. *
  23235. * @event Plugin#dispose
  23236. * @type {Event}
  23237. */
  23238. this.trigger('dispose');
  23239. this.off();
  23240. player.off('dispose', this.dispose);
  23241. // Eliminate any possible sources of leaking memory by clearing up
  23242. // references between the player and the plugin instance and nulling out
  23243. // the plugin's state and replacing methods with a function that throws.
  23244. player[PLUGIN_CACHE_KEY][name] = false;
  23245. this.player = this.state = null;
  23246. // Finally, replace the plugin name on the player with a new factory
  23247. // function, so that the plugin is ready to be set up again.
  23248. player[name] = createPluginFactory(name, pluginStorage[name]);
  23249. }
  23250. /**
  23251. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  23252. *
  23253. * @param {string|Function} plugin
  23254. * If a string, matches the name of a plugin. If a function, will be
  23255. * tested directly.
  23256. *
  23257. * @return {boolean}
  23258. * Whether or not a plugin is a basic plugin.
  23259. */
  23260. static isBasic(plugin) {
  23261. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  23262. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  23263. }
  23264. /**
  23265. * Register a Video.js plugin.
  23266. *
  23267. * @param {string} name
  23268. * The name of the plugin to be registered. Must be a string and
  23269. * must not match an existing plugin or a method on the `Player`
  23270. * prototype.
  23271. *
  23272. * @param {typeof Plugin|Function} plugin
  23273. * A sub-class of `Plugin` or a function for basic plugins.
  23274. *
  23275. * @return {typeof Plugin|Function}
  23276. * For advanced plugins, a factory function for that plugin. For
  23277. * basic plugins, a wrapper function that initializes the plugin.
  23278. */
  23279. static registerPlugin(name, plugin) {
  23280. if (typeof name !== 'string') {
  23281. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  23282. }
  23283. if (pluginExists(name)) {
  23284. log.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  23285. } else if (Player.prototype.hasOwnProperty(name)) {
  23286. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  23287. }
  23288. if (typeof plugin !== 'function') {
  23289. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  23290. }
  23291. pluginStorage[name] = plugin;
  23292. // Add a player prototype method for all sub-classed plugins (but not for
  23293. // the base Plugin class).
  23294. if (name !== BASE_PLUGIN_NAME) {
  23295. if (Plugin.isBasic(plugin)) {
  23296. Player.prototype[name] = createBasicPlugin(name, plugin);
  23297. } else {
  23298. Player.prototype[name] = createPluginFactory(name, plugin);
  23299. }
  23300. }
  23301. return plugin;
  23302. }
  23303. /**
  23304. * De-register a Video.js plugin.
  23305. *
  23306. * @param {string} name
  23307. * The name of the plugin to be de-registered. Must be a string that
  23308. * matches an existing plugin.
  23309. *
  23310. * @throws {Error}
  23311. * If an attempt is made to de-register the base plugin.
  23312. */
  23313. static deregisterPlugin(name) {
  23314. if (name === BASE_PLUGIN_NAME) {
  23315. throw new Error('Cannot de-register base plugin.');
  23316. }
  23317. if (pluginExists(name)) {
  23318. delete pluginStorage[name];
  23319. delete Player.prototype[name];
  23320. }
  23321. }
  23322. /**
  23323. * Gets an object containing multiple Video.js plugins.
  23324. *
  23325. * @param {Array} [names]
  23326. * If provided, should be an array of plugin names. Defaults to _all_
  23327. * plugin names.
  23328. *
  23329. * @return {Object|undefined}
  23330. * An object containing plugin(s) associated with their name(s) or
  23331. * `undefined` if no matching plugins exist).
  23332. */
  23333. static getPlugins(names = Object.keys(pluginStorage)) {
  23334. let result;
  23335. names.forEach(name => {
  23336. const plugin = getPlugin(name);
  23337. if (plugin) {
  23338. result = result || {};
  23339. result[name] = plugin;
  23340. }
  23341. });
  23342. return result;
  23343. }
  23344. /**
  23345. * Gets a plugin's version, if available
  23346. *
  23347. * @param {string} name
  23348. * The name of a plugin.
  23349. *
  23350. * @return {string}
  23351. * The plugin's version or an empty string.
  23352. */
  23353. static getPluginVersion(name) {
  23354. const plugin = getPlugin(name);
  23355. return plugin && plugin.VERSION || '';
  23356. }
  23357. }
  23358. /**
  23359. * Gets a plugin by name if it exists.
  23360. *
  23361. * @static
  23362. * @method getPlugin
  23363. * @memberOf Plugin
  23364. * @param {string} name
  23365. * The name of a plugin.
  23366. *
  23367. * @returns {typeof Plugin|Function|undefined}
  23368. * The plugin (or `undefined`).
  23369. */
  23370. Plugin.getPlugin = getPlugin;
  23371. /**
  23372. * The name of the base plugin class as it is registered.
  23373. *
  23374. * @type {string}
  23375. */
  23376. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  23377. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  23378. /**
  23379. * Documented in player.js
  23380. *
  23381. * @ignore
  23382. */
  23383. Player.prototype.usingPlugin = function (name) {
  23384. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  23385. };
  23386. /**
  23387. * Documented in player.js
  23388. *
  23389. * @ignore
  23390. */
  23391. Player.prototype.hasPlugin = function (name) {
  23392. return !!pluginExists(name);
  23393. };
  23394. /**
  23395. * Signals that a plugin is about to be set up on a player.
  23396. *
  23397. * @event Player#beforepluginsetup
  23398. * @type {Plugin~PluginEventHash}
  23399. */
  23400. /**
  23401. * Signals that a plugin is about to be set up on a player - by name. The name
  23402. * is the name of the plugin.
  23403. *
  23404. * @event Player#beforepluginsetup:$name
  23405. * @type {Plugin~PluginEventHash}
  23406. */
  23407. /**
  23408. * Signals that a plugin has just been set up on a player.
  23409. *
  23410. * @event Player#pluginsetup
  23411. * @type {Plugin~PluginEventHash}
  23412. */
  23413. /**
  23414. * Signals that a plugin has just been set up on a player - by name. The name
  23415. * is the name of the plugin.
  23416. *
  23417. * @event Player#pluginsetup:$name
  23418. * @type {Plugin~PluginEventHash}
  23419. */
  23420. /**
  23421. * @typedef {Object} Plugin~PluginEventHash
  23422. *
  23423. * @property {string} instance
  23424. * For basic plugins, the return value of the plugin function. For
  23425. * advanced plugins, the plugin instance on which the event is fired.
  23426. *
  23427. * @property {string} name
  23428. * The name of the plugin.
  23429. *
  23430. * @property {string} plugin
  23431. * For basic plugins, the plugin function. For advanced plugins, the
  23432. * plugin class/constructor.
  23433. */
  23434. /**
  23435. * @file deprecate.js
  23436. * @module deprecate
  23437. */
  23438. /**
  23439. * Decorate a function with a deprecation message the first time it is called.
  23440. *
  23441. * @param {string} message
  23442. * A deprecation message to log the first time the returned function
  23443. * is called.
  23444. *
  23445. * @param {Function} fn
  23446. * The function to be deprecated.
  23447. *
  23448. * @return {Function}
  23449. * A wrapper function that will log a deprecation warning the first
  23450. * time it is called. The return value will be the return value of
  23451. * the wrapped function.
  23452. */
  23453. function deprecate(message, fn) {
  23454. let warned = false;
  23455. return function (...args) {
  23456. if (!warned) {
  23457. log.warn(message);
  23458. }
  23459. warned = true;
  23460. return fn.apply(this, args);
  23461. };
  23462. }
  23463. /**
  23464. * Internal function used to mark a function as deprecated in the next major
  23465. * version with consistent messaging.
  23466. *
  23467. * @param {number} major The major version where it will be removed
  23468. * @param {string} oldName The old function name
  23469. * @param {string} newName The new function name
  23470. * @param {Function} fn The function to deprecate
  23471. * @return {Function} The decorated function
  23472. */
  23473. function deprecateForMajor(major, oldName, newName, fn) {
  23474. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  23475. }
  23476. /**
  23477. * @file video.js
  23478. * @module videojs
  23479. */
  23480. /**
  23481. * Normalize an `id` value by trimming off a leading `#`
  23482. *
  23483. * @private
  23484. * @param {string} id
  23485. * A string, maybe with a leading `#`.
  23486. *
  23487. * @return {string}
  23488. * The string, without any leading `#`.
  23489. */
  23490. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  23491. /**
  23492. * A callback that is called when a component is ready. Does not have any
  23493. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  23494. *
  23495. * @callback ReadyCallback
  23496. */
  23497. /**
  23498. * The `videojs()` function doubles as the main function for users to create a
  23499. * {@link Player} instance as well as the main library namespace.
  23500. *
  23501. * It can also be used as a getter for a pre-existing {@link Player} instance.
  23502. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  23503. * purpose because it avoids any potential for unintended initialization.
  23504. *
  23505. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  23506. * of our JSDoc template, we cannot properly document this as both a function
  23507. * and a namespace, so its function signature is documented here.
  23508. *
  23509. * #### Arguments
  23510. * ##### id
  23511. * string|Element, **required**
  23512. *
  23513. * Video element or video element ID.
  23514. *
  23515. * ##### options
  23516. * Object, optional
  23517. *
  23518. * Options object for providing settings.
  23519. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23520. *
  23521. * ##### ready
  23522. * {@link Component~ReadyCallback}, optional
  23523. *
  23524. * A function to be called when the {@link Player} and {@link Tech} are ready.
  23525. *
  23526. * #### Return Value
  23527. *
  23528. * The `videojs()` function returns a {@link Player} instance.
  23529. *
  23530. * @namespace
  23531. *
  23532. * @borrows AudioTrack as AudioTrack
  23533. * @borrows Component.getComponent as getComponent
  23534. * @borrows module:events.on as on
  23535. * @borrows module:events.one as one
  23536. * @borrows module:events.off as off
  23537. * @borrows module:events.trigger as trigger
  23538. * @borrows EventTarget as EventTarget
  23539. * @borrows module:middleware.use as use
  23540. * @borrows Player.players as players
  23541. * @borrows Plugin.registerPlugin as registerPlugin
  23542. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  23543. * @borrows Plugin.getPlugins as getPlugins
  23544. * @borrows Plugin.getPlugin as getPlugin
  23545. * @borrows Plugin.getPluginVersion as getPluginVersion
  23546. * @borrows Tech.getTech as getTech
  23547. * @borrows Tech.registerTech as registerTech
  23548. * @borrows TextTrack as TextTrack
  23549. * @borrows VideoTrack as VideoTrack
  23550. *
  23551. * @param {string|Element} id
  23552. * Video element or video element ID.
  23553. *
  23554. * @param {Object} [options]
  23555. * Options object for providing settings.
  23556. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23557. *
  23558. * @param {ReadyCallback} [ready]
  23559. * A function to be called when the {@link Player} and {@link Tech} are
  23560. * ready.
  23561. *
  23562. * @return {Player}
  23563. * The `videojs()` function returns a {@link Player|Player} instance.
  23564. */
  23565. function videojs(id, options, ready) {
  23566. let player = videojs.getPlayer(id);
  23567. if (player) {
  23568. if (options) {
  23569. log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  23570. }
  23571. if (ready) {
  23572. player.ready(ready);
  23573. }
  23574. return player;
  23575. }
  23576. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  23577. if (!isEl(el)) {
  23578. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  23579. }
  23580. // document.body.contains(el) will only check if el is contained within that one document.
  23581. // This causes problems for elements in iframes.
  23582. // Instead, use the element's ownerDocument instead of the global document.
  23583. // This will make sure that the element is indeed in the dom of that document.
  23584. // Additionally, check that the document in question has a default view.
  23585. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  23586. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  23587. log.warn('The element supplied is not included in the DOM');
  23588. }
  23589. options = options || {};
  23590. // Store a copy of the el before modification, if it is to be restored in destroy()
  23591. // If div ingest, store the parent div
  23592. if (options.restoreEl === true) {
  23593. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  23594. }
  23595. hooks('beforesetup').forEach(hookFunction => {
  23596. const opts = hookFunction(el, merge(options));
  23597. if (!isObject(opts) || Array.isArray(opts)) {
  23598. log.error('please return an object in beforesetup hooks');
  23599. return;
  23600. }
  23601. options = merge(options, opts);
  23602. });
  23603. // We get the current "Player" component here in case an integration has
  23604. // replaced it with a custom player.
  23605. const PlayerComponent = Component.getComponent('Player');
  23606. player = new PlayerComponent(el, options, ready);
  23607. hooks('setup').forEach(hookFunction => hookFunction(player));
  23608. return player;
  23609. }
  23610. videojs.hooks_ = hooks_;
  23611. videojs.hooks = hooks;
  23612. videojs.hook = hook;
  23613. videojs.hookOnce = hookOnce;
  23614. videojs.removeHook = removeHook;
  23615. // Add default styles
  23616. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  23617. let style = $('.vjs-styles-defaults');
  23618. if (!style) {
  23619. style = createStyleElement('vjs-styles-defaults');
  23620. const head = $('head');
  23621. if (head) {
  23622. head.insertBefore(style, head.firstChild);
  23623. }
  23624. setTextContent(style, `
  23625. .video-js {
  23626. width: 300px;
  23627. height: 150px;
  23628. }
  23629. .vjs-fluid:not(.vjs-audio-only-mode) {
  23630. padding-top: 56.25%
  23631. }
  23632. `);
  23633. }
  23634. }
  23635. // Run Auto-load players
  23636. // You have to wait at least once in case this script is loaded after your
  23637. // video in the DOM (weird behavior only with minified version)
  23638. autoSetupTimeout(1, videojs);
  23639. /**
  23640. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  23641. *
  23642. * @type {string}
  23643. */
  23644. videojs.VERSION = version;
  23645. /**
  23646. * The global options object. These are the settings that take effect
  23647. * if no overrides are specified when the player is created.
  23648. *
  23649. * @type {Object}
  23650. */
  23651. videojs.options = Player.prototype.options_;
  23652. /**
  23653. * Get an object with the currently created players, keyed by player ID
  23654. *
  23655. * @return {Object}
  23656. * The created players
  23657. */
  23658. videojs.getPlayers = () => Player.players;
  23659. /**
  23660. * Get a single player based on an ID or DOM element.
  23661. *
  23662. * This is useful if you want to check if an element or ID has an associated
  23663. * Video.js player, but not create one if it doesn't.
  23664. *
  23665. * @param {string|Element} id
  23666. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  23667. * or a string matching the `id` of such an element.
  23668. *
  23669. * @return {Player|undefined}
  23670. * A player instance or `undefined` if there is no player instance
  23671. * matching the argument.
  23672. */
  23673. videojs.getPlayer = id => {
  23674. const players = Player.players;
  23675. let tag;
  23676. if (typeof id === 'string') {
  23677. const nId = normalizeId(id);
  23678. const player = players[nId];
  23679. if (player) {
  23680. return player;
  23681. }
  23682. tag = $('#' + nId);
  23683. } else {
  23684. tag = id;
  23685. }
  23686. if (isEl(tag)) {
  23687. const {
  23688. player,
  23689. playerId
  23690. } = tag;
  23691. // Element may have a `player` property referring to an already created
  23692. // player instance. If so, return that.
  23693. if (player || players[playerId]) {
  23694. return player || players[playerId];
  23695. }
  23696. }
  23697. };
  23698. /**
  23699. * Returns an array of all current players.
  23700. *
  23701. * @return {Array}
  23702. * An array of all players. The array will be in the order that
  23703. * `Object.keys` provides, which could potentially vary between
  23704. * JavaScript engines.
  23705. *
  23706. */
  23707. videojs.getAllPlayers = () =>
  23708. // Disposed players leave a key with a `null` value, so we need to make sure
  23709. // we filter those out.
  23710. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  23711. videojs.players = Player.players;
  23712. videojs.getComponent = Component.getComponent;
  23713. /**
  23714. * Register a component so it can referred to by name. Used when adding to other
  23715. * components, either through addChild `component.addChild('myComponent')` or through
  23716. * default children options `{ children: ['myComponent'] }`.
  23717. *
  23718. * > NOTE: You could also just initialize the component before adding.
  23719. * `component.addChild(new MyComponent());`
  23720. *
  23721. * @param {string} name
  23722. * The class name of the component
  23723. *
  23724. * @param {Component} comp
  23725. * The component class
  23726. *
  23727. * @return {Component}
  23728. * The newly registered component
  23729. */
  23730. videojs.registerComponent = (name, comp) => {
  23731. if (Tech.isTech(comp)) {
  23732. log.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  23733. }
  23734. Component.registerComponent.call(Component, name, comp);
  23735. };
  23736. videojs.getTech = Tech.getTech;
  23737. videojs.registerTech = Tech.registerTech;
  23738. videojs.use = use;
  23739. /**
  23740. * An object that can be returned by a middleware to signify
  23741. * that the middleware is being terminated.
  23742. *
  23743. * @type {object}
  23744. * @property {object} middleware.TERMINATOR
  23745. */
  23746. Object.defineProperty(videojs, 'middleware', {
  23747. value: {},
  23748. writeable: false,
  23749. enumerable: true
  23750. });
  23751. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  23752. value: TERMINATOR,
  23753. writeable: false,
  23754. enumerable: true
  23755. });
  23756. /**
  23757. * A reference to the {@link module:browser|browser utility module} as an object.
  23758. *
  23759. * @type {Object}
  23760. * @see {@link module:browser|browser}
  23761. */
  23762. videojs.browser = browser;
  23763. /**
  23764. * A reference to the {@link module:obj|obj utility module} as an object.
  23765. *
  23766. * @type {Object}
  23767. * @see {@link module:obj|obj}
  23768. */
  23769. videojs.obj = Obj;
  23770. /**
  23771. * Deprecated reference to the {@link module:obj.merge|merge function}
  23772. *
  23773. * @type {Function}
  23774. * @see {@link module:obj.merge|merge}
  23775. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  23776. */
  23777. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge);
  23778. /**
  23779. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  23780. *
  23781. * @type {Function}
  23782. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  23783. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  23784. */
  23785. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  23786. /**
  23787. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  23788. *
  23789. * @type {Function}
  23790. * @see {@link module:fn.bind_|fn.bind_}
  23791. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  23792. */
  23793. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  23794. videojs.registerPlugin = Plugin.registerPlugin;
  23795. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  23796. /**
  23797. * Deprecated method to register a plugin with Video.js
  23798. *
  23799. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  23800. *
  23801. * @param {string} name
  23802. * The plugin name
  23803. *
  23804. * @param {Plugin|Function} plugin
  23805. * The plugin sub-class or function
  23806. */
  23807. videojs.plugin = (name, plugin) => {
  23808. log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  23809. return Plugin.registerPlugin(name, plugin);
  23810. };
  23811. videojs.getPlugins = Plugin.getPlugins;
  23812. videojs.getPlugin = Plugin.getPlugin;
  23813. videojs.getPluginVersion = Plugin.getPluginVersion;
  23814. /**
  23815. * Adding languages so that they're available to all players.
  23816. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  23817. *
  23818. * @param {string} code
  23819. * The language code or dictionary property
  23820. *
  23821. * @param {Object} data
  23822. * The data values to be translated
  23823. *
  23824. * @return {Object}
  23825. * The resulting language dictionary object
  23826. */
  23827. videojs.addLanguage = function (code, data) {
  23828. code = ('' + code).toLowerCase();
  23829. videojs.options.languages = merge(videojs.options.languages, {
  23830. [code]: data
  23831. });
  23832. return videojs.options.languages[code];
  23833. };
  23834. /**
  23835. * A reference to the {@link module:log|log utility module} as an object.
  23836. *
  23837. * @type {Function}
  23838. * @see {@link module:log|log}
  23839. */
  23840. videojs.log = log;
  23841. videojs.createLogger = createLogger;
  23842. /**
  23843. * A reference to the {@link module:time|time utility module} as an object.
  23844. *
  23845. * @type {Object}
  23846. * @see {@link module:time|time}
  23847. */
  23848. videojs.time = Time;
  23849. /**
  23850. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23851. *
  23852. * @type {Function}
  23853. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23854. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23855. */
  23856. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges);
  23857. /**
  23858. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23859. *
  23860. * @type {Function}
  23861. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23862. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23863. */
  23864. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges);
  23865. /**
  23866. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  23867. *
  23868. * @type {Function}
  23869. * @see {@link module:time.formatTime|formatTime}
  23870. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  23871. */
  23872. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  23873. /**
  23874. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  23875. *
  23876. * @type {Function}
  23877. * @see {@link module:time.setFormatTime|setFormatTime}
  23878. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  23879. */
  23880. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  23881. /**
  23882. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  23883. *
  23884. * @type {Function}
  23885. * @see {@link module:time.resetFormatTime|resetFormatTime}
  23886. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  23887. */
  23888. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  23889. /**
  23890. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  23891. *
  23892. * @type {Function}
  23893. * @see {@link module:url.parseUrl|parseUrl}
  23894. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  23895. */
  23896. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  23897. /**
  23898. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  23899. *
  23900. * @type {Function}
  23901. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  23902. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  23903. */
  23904. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  23905. videojs.EventTarget = EventTarget;
  23906. videojs.any = any;
  23907. videojs.on = on;
  23908. videojs.one = one;
  23909. videojs.off = off;
  23910. videojs.trigger = trigger;
  23911. /**
  23912. * A cross-browser XMLHttpRequest wrapper.
  23913. *
  23914. * @function
  23915. * @param {Object} options
  23916. * Settings for the request.
  23917. *
  23918. * @return {XMLHttpRequest|XDomainRequest}
  23919. * The request object.
  23920. *
  23921. * @see https://github.com/Raynos/xhr
  23922. */
  23923. videojs.xhr = XHR;
  23924. videojs.TextTrack = TextTrack;
  23925. videojs.AudioTrack = AudioTrack;
  23926. videojs.VideoTrack = VideoTrack;
  23927. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  23928. videojs[k] = function () {
  23929. log.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  23930. return Dom[k].apply(null, arguments);
  23931. };
  23932. });
  23933. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  23934. /**
  23935. * A reference to the {@link module:dom|DOM utility module} as an object.
  23936. *
  23937. * @type {Object}
  23938. * @see {@link module:dom|dom}
  23939. */
  23940. videojs.dom = Dom;
  23941. /**
  23942. * A reference to the {@link module:fn|fn utility module} as an object.
  23943. *
  23944. * @type {Object}
  23945. * @see {@link module:fn|fn}
  23946. */
  23947. videojs.fn = Fn;
  23948. /**
  23949. * A reference to the {@link module:num|num utility module} as an object.
  23950. *
  23951. * @type {Object}
  23952. * @see {@link module:num|num}
  23953. */
  23954. videojs.num = Num;
  23955. /**
  23956. * A reference to the {@link module:str|str utility module} as an object.
  23957. *
  23958. * @type {Object}
  23959. * @see {@link module:str|str}
  23960. */
  23961. videojs.str = Str;
  23962. /**
  23963. * A reference to the {@link module:url|URL utility module} as an object.
  23964. *
  23965. * @type {Object}
  23966. * @see {@link module:url|url}
  23967. */
  23968. videojs.url = Url;
  23969. export { videojs as default };