video.core.js 863 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996
  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. (function (global, factory) {
  13. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  14. typeof define === 'function' && define.amd ? define(factory) :
  15. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.videojs = factory());
  16. })(this, (function () { 'use strict';
  17. var version = "8.3.0";
  18. /**
  19. * An Object that contains lifecycle hooks as keys which point to an array
  20. * of functions that are run when a lifecycle is triggered
  21. *
  22. * @private
  23. */
  24. const hooks_ = {};
  25. /**
  26. * Get a list of hooks for a specific lifecycle
  27. *
  28. * @param {string} type
  29. * the lifecycle to get hooks from
  30. *
  31. * @param {Function|Function[]} [fn]
  32. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  33. *
  34. * @return {Array}
  35. * an array of hooks, or an empty array if there are none.
  36. */
  37. const hooks = function (type, fn) {
  38. hooks_[type] = hooks_[type] || [];
  39. if (fn) {
  40. hooks_[type] = hooks_[type].concat(fn);
  41. }
  42. return hooks_[type];
  43. };
  44. /**
  45. * Add a function hook to a specific videojs lifecycle.
  46. *
  47. * @param {string} type
  48. * the lifecycle to hook the function to.
  49. *
  50. * @param {Function|Function[]}
  51. * The function or array of functions to attach.
  52. */
  53. const hook = function (type, fn) {
  54. hooks(type, fn);
  55. };
  56. /**
  57. * Remove a hook from a specific videojs lifecycle.
  58. *
  59. * @param {string} type
  60. * the lifecycle that the function hooked to
  61. *
  62. * @param {Function} fn
  63. * The hooked function to remove
  64. *
  65. * @return {boolean}
  66. * The function that was removed or undef
  67. */
  68. const removeHook = function (type, fn) {
  69. const index = hooks(type).indexOf(fn);
  70. if (index <= -1) {
  71. return false;
  72. }
  73. hooks_[type] = hooks_[type].slice();
  74. hooks_[type].splice(index, 1);
  75. return true;
  76. };
  77. /**
  78. * Add a function hook that will only run once to a specific videojs lifecycle.
  79. *
  80. * @param {string} type
  81. * the lifecycle to hook the function to.
  82. *
  83. * @param {Function|Function[]}
  84. * The function or array of functions to attach.
  85. */
  86. const hookOnce = function (type, fn) {
  87. hooks(type, [].concat(fn).map(original => {
  88. const wrapper = (...args) => {
  89. removeHook(type, wrapper);
  90. return original(...args);
  91. };
  92. return wrapper;
  93. }));
  94. };
  95. /**
  96. * @file fullscreen-api.js
  97. * @module fullscreen-api
  98. */
  99. /**
  100. * Store the browser-specific methods for the fullscreen API.
  101. *
  102. * @type {Object}
  103. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  104. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  105. */
  106. const FullscreenApi = {
  107. prefixed: true
  108. };
  109. // browser API methods
  110. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  111. // WebKit
  112. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  113. // Mozilla
  114. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  115. // Microsoft
  116. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  117. const specApi = apiMap[0];
  118. let browserApi;
  119. // determine the supported set of functions
  120. for (let i = 0; i < apiMap.length; i++) {
  121. // check for exitFullscreen function
  122. if (apiMap[i][1] in document) {
  123. browserApi = apiMap[i];
  124. break;
  125. }
  126. }
  127. // map the browser API names to the spec API names
  128. if (browserApi) {
  129. for (let i = 0; i < browserApi.length; i++) {
  130. FullscreenApi[specApi[i]] = browserApi[i];
  131. }
  132. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  133. }
  134. /**
  135. * @file create-logger.js
  136. * @module create-logger
  137. */
  138. // This is the private tracking variable for the logging history.
  139. let history = [];
  140. /**
  141. * Log messages to the console and history based on the type of message
  142. *
  143. * @private
  144. * @param {string} type
  145. * The name of the console method to use.
  146. *
  147. * @param {Array} args
  148. * The arguments to be passed to the matching console method.
  149. */
  150. const LogByTypeFactory = (name, log) => (type, level, args) => {
  151. const lvl = log.levels[level];
  152. const lvlRegExp = new RegExp(`^(${lvl})$`);
  153. if (type !== 'log') {
  154. // Add the type to the front of the message when it's not "log".
  155. args.unshift(type.toUpperCase() + ':');
  156. }
  157. // Add console prefix after adding to history.
  158. args.unshift(name + ':');
  159. // Add a clone of the args at this point to history.
  160. if (history) {
  161. history.push([].concat(args));
  162. // only store 1000 history entries
  163. const splice = history.length - 1000;
  164. history.splice(0, splice > 0 ? splice : 0);
  165. }
  166. // If there's no console then don't try to output messages, but they will
  167. // still be stored in history.
  168. if (!window.console) {
  169. return;
  170. }
  171. // Was setting these once outside of this function, but containing them
  172. // in the function makes it easier to test cases where console doesn't exist
  173. // when the module is executed.
  174. let fn = window.console[type];
  175. if (!fn && type === 'debug') {
  176. // Certain browsers don't have support for console.debug. For those, we
  177. // should default to the closest comparable log.
  178. fn = window.console.info || window.console.log;
  179. }
  180. // Bail out if there's no console or if this type is not allowed by the
  181. // current logging level.
  182. if (!fn || !lvl || !lvlRegExp.test(type)) {
  183. return;
  184. }
  185. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  186. };
  187. function createLogger$1(name) {
  188. // This is the private tracking variable for logging level.
  189. let level = 'info';
  190. // the curried logByType bound to the specific log and history
  191. let logByType;
  192. /**
  193. * Logs plain debug messages. Similar to `console.log`.
  194. *
  195. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  196. * of our JSDoc template, we cannot properly document this as both a function
  197. * and a namespace, so its function signature is documented here.
  198. *
  199. * #### Arguments
  200. * ##### *args
  201. * *[]
  202. *
  203. * Any combination of values that could be passed to `console.log()`.
  204. *
  205. * #### Return Value
  206. *
  207. * `undefined`
  208. *
  209. * @namespace
  210. * @param {...*} args
  211. * One or more messages or objects that should be logged.
  212. */
  213. const log = function (...args) {
  214. logByType('log', level, args);
  215. };
  216. // This is the logByType helper that the logging methods below use
  217. logByType = LogByTypeFactory(name, log);
  218. /**
  219. * Create a new sublogger which chains the old name to the new name.
  220. *
  221. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  222. * ```js
  223. * mylogger('foo');
  224. * // > VIDEOJS: player: foo
  225. * ```
  226. *
  227. * @param {string} name
  228. * The name to add call the new logger
  229. * @return {Object}
  230. */
  231. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  232. /**
  233. * Enumeration of available logging levels, where the keys are the level names
  234. * and the values are `|`-separated strings containing logging methods allowed
  235. * in that logging level. These strings are used to create a regular expression
  236. * matching the function name being called.
  237. *
  238. * Levels provided by Video.js are:
  239. *
  240. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  241. * this effect. The most restrictive.
  242. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  243. * `log.warn`, and `log.error`).
  244. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  245. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  246. * - `warn`: Matches `log.warn` and `log.error` calls.
  247. * - `error`: Matches only `log.error` calls.
  248. *
  249. * @type {Object}
  250. */
  251. log.levels = {
  252. all: 'debug|log|warn|error',
  253. off: '',
  254. debug: 'debug|log|warn|error',
  255. info: 'log|warn|error',
  256. warn: 'warn|error',
  257. error: 'error',
  258. DEFAULT: level
  259. };
  260. /**
  261. * Get or set the current logging level.
  262. *
  263. * If a string matching a key from {@link module:log.levels} is provided, acts
  264. * as a setter.
  265. *
  266. * @param {string} [lvl]
  267. * Pass a valid level to set a new logging level.
  268. *
  269. * @return {string}
  270. * The current logging level.
  271. */
  272. log.level = lvl => {
  273. if (typeof lvl === 'string') {
  274. if (!log.levels.hasOwnProperty(lvl)) {
  275. throw new Error(`"${lvl}" in not a valid log level`);
  276. }
  277. level = lvl;
  278. }
  279. return level;
  280. };
  281. /**
  282. * Returns an array containing everything that has been logged to the history.
  283. *
  284. * This array is a shallow clone of the internal history record. However, its
  285. * contents are _not_ cloned; so, mutating objects inside this array will
  286. * mutate them in history.
  287. *
  288. * @return {Array}
  289. */
  290. log.history = () => history ? [].concat(history) : [];
  291. /**
  292. * Allows you to filter the history by the given logger name
  293. *
  294. * @param {string} fname
  295. * The name to filter by
  296. *
  297. * @return {Array}
  298. * The filtered list to return
  299. */
  300. log.history.filter = fname => {
  301. return (history || []).filter(historyItem => {
  302. // if the first item in each historyItem includes `fname`, then it's a match
  303. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  304. });
  305. };
  306. /**
  307. * Clears the internal history tracking, but does not prevent further history
  308. * tracking.
  309. */
  310. log.history.clear = () => {
  311. if (history) {
  312. history.length = 0;
  313. }
  314. };
  315. /**
  316. * Disable history tracking if it is currently enabled.
  317. */
  318. log.history.disable = () => {
  319. if (history !== null) {
  320. history.length = 0;
  321. history = null;
  322. }
  323. };
  324. /**
  325. * Enable history tracking if it is currently disabled.
  326. */
  327. log.history.enable = () => {
  328. if (history === null) {
  329. history = [];
  330. }
  331. };
  332. /**
  333. * Logs error messages. Similar to `console.error`.
  334. *
  335. * @param {...*} args
  336. * One or more messages or objects that should be logged as an error
  337. */
  338. log.error = (...args) => logByType('error', level, args);
  339. /**
  340. * Logs warning messages. Similar to `console.warn`.
  341. *
  342. * @param {...*} args
  343. * One or more messages or objects that should be logged as a warning.
  344. */
  345. log.warn = (...args) => logByType('warn', level, args);
  346. /**
  347. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  348. * log if `console.debug` is not available
  349. *
  350. * @param {...*} args
  351. * One or more messages or objects that should be logged as debug.
  352. */
  353. log.debug = (...args) => logByType('debug', level, args);
  354. return log;
  355. }
  356. /**
  357. * @file log.js
  358. * @module log
  359. */
  360. const log = createLogger$1('VIDEOJS');
  361. const createLogger = log.createLogger;
  362. /**
  363. * @file obj.js
  364. * @module obj
  365. */
  366. /**
  367. * @callback obj:EachCallback
  368. *
  369. * @param {*} value
  370. * The current key for the object that is being iterated over.
  371. *
  372. * @param {string} key
  373. * The current key-value for object that is being iterated over
  374. */
  375. /**
  376. * @callback obj:ReduceCallback
  377. *
  378. * @param {*} accum
  379. * The value that is accumulating over the reduce loop.
  380. *
  381. * @param {*} value
  382. * The current key for the object that is being iterated over.
  383. *
  384. * @param {string} key
  385. * The current key-value for object that is being iterated over
  386. *
  387. * @return {*}
  388. * The new accumulated value.
  389. */
  390. const toString$1 = Object.prototype.toString;
  391. /**
  392. * Get the keys of an Object
  393. *
  394. * @param {Object}
  395. * The Object to get the keys from
  396. *
  397. * @return {string[]}
  398. * An array of the keys from the object. Returns an empty array if the
  399. * object passed in was invalid or had no keys.
  400. *
  401. * @private
  402. */
  403. const keys = function (object) {
  404. return isObject(object) ? Object.keys(object) : [];
  405. };
  406. /**
  407. * Array-like iteration for objects.
  408. *
  409. * @param {Object} object
  410. * The object to iterate over
  411. *
  412. * @param {obj:EachCallback} fn
  413. * The callback function which is called for each key in the object.
  414. */
  415. function each(object, fn) {
  416. keys(object).forEach(key => fn(object[key], key));
  417. }
  418. /**
  419. * Array-like reduce for objects.
  420. *
  421. * @param {Object} object
  422. * The Object that you want to reduce.
  423. *
  424. * @param {Function} fn
  425. * A callback function which is called for each key in the object. It
  426. * receives the accumulated value and the per-iteration value and key
  427. * as arguments.
  428. *
  429. * @param {*} [initial = 0]
  430. * Starting value
  431. *
  432. * @return {*}
  433. * The final accumulated value.
  434. */
  435. function reduce(object, fn, initial = 0) {
  436. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  437. }
  438. /**
  439. * Returns whether a value is an object of any kind - including DOM nodes,
  440. * arrays, regular expressions, etc. Not functions, though.
  441. *
  442. * This avoids the gotcha where using `typeof` on a `null` value
  443. * results in `'object'`.
  444. *
  445. * @param {Object} value
  446. * @return {boolean}
  447. */
  448. function isObject(value) {
  449. return !!value && typeof value === 'object';
  450. }
  451. /**
  452. * Returns whether an object appears to be a "plain" object - that is, a
  453. * direct instance of `Object`.
  454. *
  455. * @param {Object} value
  456. * @return {boolean}
  457. */
  458. function isPlain(value) {
  459. return isObject(value) && toString$1.call(value) === '[object Object]' && value.constructor === Object;
  460. }
  461. /**
  462. * Merge two objects recursively.
  463. *
  464. * Performs a deep merge like
  465. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  466. * plain objects (not arrays, elements, or anything else).
  467. *
  468. * Non-plain object values will be copied directly from the right-most
  469. * argument.
  470. *
  471. * @param {Object[]} sources
  472. * One or more objects to merge into a new object.
  473. *
  474. * @return {Object}
  475. * A new object that is the merged result of all sources.
  476. */
  477. function merge(...sources) {
  478. const result = {};
  479. sources.forEach(source => {
  480. if (!source) {
  481. return;
  482. }
  483. each(source, (value, key) => {
  484. if (!isPlain(value)) {
  485. result[key] = value;
  486. return;
  487. }
  488. if (!isPlain(result[key])) {
  489. result[key] = {};
  490. }
  491. result[key] = merge(result[key], value);
  492. });
  493. });
  494. return result;
  495. }
  496. /**
  497. * Object.defineProperty but "lazy", which means that the value is only set after
  498. * it is retrieved the first time, rather than being set right away.
  499. *
  500. * @param {Object} obj the object to set the property on
  501. * @param {string} key the key for the property to set
  502. * @param {Function} getValue the function used to get the value when it is needed.
  503. * @param {boolean} setter whether a setter should be allowed or not
  504. */
  505. function defineLazyProperty(obj, key, getValue, setter = true) {
  506. const set = value => Object.defineProperty(obj, key, {
  507. value,
  508. enumerable: true,
  509. writable: true
  510. });
  511. const options = {
  512. configurable: true,
  513. enumerable: true,
  514. get() {
  515. const value = getValue();
  516. set(value);
  517. return value;
  518. }
  519. };
  520. if (setter) {
  521. options.set = set;
  522. }
  523. return Object.defineProperty(obj, key, options);
  524. }
  525. var Obj = /*#__PURE__*/Object.freeze({
  526. __proto__: null,
  527. each: each,
  528. reduce: reduce,
  529. isObject: isObject,
  530. isPlain: isPlain,
  531. merge: merge,
  532. defineLazyProperty: defineLazyProperty
  533. });
  534. /**
  535. * @file browser.js
  536. * @module browser
  537. */
  538. /**
  539. * Whether or not this device is an iPod.
  540. *
  541. * @static
  542. * @type {Boolean}
  543. */
  544. let IS_IPOD = false;
  545. /**
  546. * The detected iOS version - or `null`.
  547. *
  548. * @static
  549. * @type {string|null}
  550. */
  551. let IOS_VERSION = null;
  552. /**
  553. * Whether or not this is an Android device.
  554. *
  555. * @static
  556. * @type {Boolean}
  557. */
  558. let IS_ANDROID = false;
  559. /**
  560. * The detected Android version - or `null` if not Android or indeterminable.
  561. *
  562. * @static
  563. * @type {number|string|null}
  564. */
  565. let ANDROID_VERSION;
  566. /**
  567. * Whether or not this is Mozilla Firefox.
  568. *
  569. * @static
  570. * @type {Boolean}
  571. */
  572. let IS_FIREFOX = false;
  573. /**
  574. * Whether or not this is Microsoft Edge.
  575. *
  576. * @static
  577. * @type {Boolean}
  578. */
  579. let IS_EDGE = false;
  580. /**
  581. * Whether or not this is any Chromium Browser
  582. *
  583. * @static
  584. * @type {Boolean}
  585. */
  586. let IS_CHROMIUM = false;
  587. /**
  588. * Whether or not this is any Chromium browser that is not Edge.
  589. *
  590. * This will also be `true` for Chrome on iOS, which will have different support
  591. * as it is actually Safari under the hood.
  592. *
  593. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  594. * IS_CHROMIUM should be used instead.
  595. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  596. *
  597. * @static
  598. * @deprecated
  599. * @type {Boolean}
  600. */
  601. let IS_CHROME = false;
  602. /**
  603. * The detected Chromium version - or `null`.
  604. *
  605. * @static
  606. * @type {number|null}
  607. */
  608. let CHROMIUM_VERSION = null;
  609. /**
  610. * The detected Google Chrome version - or `null`.
  611. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  612. * Deprecated, use CHROMIUM_VERSION instead.
  613. *
  614. * @static
  615. * @deprecated
  616. * @type {number|null}
  617. */
  618. let CHROME_VERSION = null;
  619. /**
  620. * The detected Internet Explorer version - or `null`.
  621. *
  622. * @static
  623. * @deprecated
  624. * @type {number|null}
  625. */
  626. let IE_VERSION = null;
  627. /**
  628. * Whether or not this is desktop Safari.
  629. *
  630. * @static
  631. * @type {Boolean}
  632. */
  633. let IS_SAFARI = false;
  634. /**
  635. * Whether or not this is a Windows machine.
  636. *
  637. * @static
  638. * @type {Boolean}
  639. */
  640. let IS_WINDOWS = false;
  641. /**
  642. * Whether or not this device is an iPad.
  643. *
  644. * @static
  645. * @type {Boolean}
  646. */
  647. let IS_IPAD = false;
  648. /**
  649. * Whether or not this device is an iPhone.
  650. *
  651. * @static
  652. * @type {Boolean}
  653. */
  654. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  655. // to identify iPhones, we need to exclude iPads.
  656. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  657. let IS_IPHONE = false;
  658. /**
  659. * Whether or not this device is touch-enabled.
  660. *
  661. * @static
  662. * @const
  663. * @type {Boolean}
  664. */
  665. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  666. const UAD = window.navigator && window.navigator.userAgentData;
  667. if (UAD) {
  668. // If userAgentData is present, use it instead of userAgent to avoid warnings
  669. // Currently only implemented on Chromium
  670. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  671. IS_ANDROID = UAD.platform === 'Android';
  672. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  673. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  674. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  675. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  676. IS_WINDOWS = UAD.platform === 'Windows';
  677. }
  678. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  679. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  680. // the checks need to be made agiainst the regular userAgent string.
  681. if (!IS_CHROMIUM) {
  682. const USER_AGENT = window.navigator && window.navigator.userAgent || '';
  683. IS_IPOD = /iPod/i.test(USER_AGENT);
  684. IOS_VERSION = function () {
  685. const match = USER_AGENT.match(/OS (\d+)_/i);
  686. if (match && match[1]) {
  687. return match[1];
  688. }
  689. return null;
  690. }();
  691. IS_ANDROID = /Android/i.test(USER_AGENT);
  692. ANDROID_VERSION = function () {
  693. // This matches Android Major.Minor.Patch versions
  694. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  695. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  696. if (!match) {
  697. return null;
  698. }
  699. const major = match[1] && parseFloat(match[1]);
  700. const minor = match[2] && parseFloat(match[2]);
  701. if (major && minor) {
  702. return parseFloat(match[1] + '.' + match[2]);
  703. } else if (major) {
  704. return major;
  705. }
  706. return null;
  707. }();
  708. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  709. IS_EDGE = /Edg/i.test(USER_AGENT);
  710. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  711. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  712. CHROMIUM_VERSION = CHROME_VERSION = function () {
  713. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  714. if (match && match[2]) {
  715. return parseFloat(match[2]);
  716. }
  717. return null;
  718. }();
  719. IE_VERSION = function () {
  720. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  721. let version = result && parseFloat(result[1]);
  722. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  723. // IE 11 has a different user agent string than other IE versions
  724. version = 11.0;
  725. }
  726. return version;
  727. }();
  728. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  729. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  730. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  731. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  732. }
  733. /**
  734. * Whether or not this is an iOS device.
  735. *
  736. * @static
  737. * @const
  738. * @type {Boolean}
  739. */
  740. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  741. /**
  742. * Whether or not this is any flavor of Safari - including iOS.
  743. *
  744. * @static
  745. * @const
  746. * @type {Boolean}
  747. */
  748. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  749. var browser = /*#__PURE__*/Object.freeze({
  750. __proto__: null,
  751. get IS_IPOD () { return IS_IPOD; },
  752. get IOS_VERSION () { return IOS_VERSION; },
  753. get IS_ANDROID () { return IS_ANDROID; },
  754. get ANDROID_VERSION () { return ANDROID_VERSION; },
  755. get IS_FIREFOX () { return IS_FIREFOX; },
  756. get IS_EDGE () { return IS_EDGE; },
  757. get IS_CHROMIUM () { return IS_CHROMIUM; },
  758. get IS_CHROME () { return IS_CHROME; },
  759. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  760. get CHROME_VERSION () { return CHROME_VERSION; },
  761. get IE_VERSION () { return IE_VERSION; },
  762. get IS_SAFARI () { return IS_SAFARI; },
  763. get IS_WINDOWS () { return IS_WINDOWS; },
  764. get IS_IPAD () { return IS_IPAD; },
  765. get IS_IPHONE () { return IS_IPHONE; },
  766. TOUCH_ENABLED: TOUCH_ENABLED,
  767. IS_IOS: IS_IOS,
  768. IS_ANY_SAFARI: IS_ANY_SAFARI
  769. });
  770. /**
  771. * @file dom.js
  772. * @module dom
  773. */
  774. /**
  775. * Detect if a value is a string with any non-whitespace characters.
  776. *
  777. * @private
  778. * @param {string} str
  779. * The string to check
  780. *
  781. * @return {boolean}
  782. * Will be `true` if the string is non-blank, `false` otherwise.
  783. *
  784. */
  785. function isNonBlankString(str) {
  786. // we use str.trim as it will trim any whitespace characters
  787. // from the front or back of non-whitespace characters. aka
  788. // Any string that contains non-whitespace characters will
  789. // still contain them after `trim` but whitespace only strings
  790. // will have a length of 0, failing this check.
  791. return typeof str === 'string' && Boolean(str.trim());
  792. }
  793. /**
  794. * Throws an error if the passed string has whitespace. This is used by
  795. * class methods to be relatively consistent with the classList API.
  796. *
  797. * @private
  798. * @param {string} str
  799. * The string to check for whitespace.
  800. *
  801. * @throws {Error}
  802. * Throws an error if there is whitespace in the string.
  803. */
  804. function throwIfWhitespace(str) {
  805. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  806. if (str.indexOf(' ') >= 0) {
  807. throw new Error('class has illegal whitespace characters');
  808. }
  809. }
  810. /**
  811. * Whether the current DOM interface appears to be real (i.e. not simulated).
  812. *
  813. * @return {boolean}
  814. * Will be `true` if the DOM appears to be real, `false` otherwise.
  815. */
  816. function isReal() {
  817. // Both document and window will never be undefined thanks to `global`.
  818. return document === window.document;
  819. }
  820. /**
  821. * Determines, via duck typing, whether or not a value is a DOM element.
  822. *
  823. * @param {*} value
  824. * The value to check.
  825. *
  826. * @return {boolean}
  827. * Will be `true` if the value is a DOM element, `false` otherwise.
  828. */
  829. function isEl(value) {
  830. return isObject(value) && value.nodeType === 1;
  831. }
  832. /**
  833. * Determines if the current DOM is embedded in an iframe.
  834. *
  835. * @return {boolean}
  836. * Will be `true` if the DOM is embedded in an iframe, `false`
  837. * otherwise.
  838. */
  839. function isInFrame() {
  840. // We need a try/catch here because Safari will throw errors when attempting
  841. // to get either `parent` or `self`
  842. try {
  843. return window.parent !== window.self;
  844. } catch (x) {
  845. return true;
  846. }
  847. }
  848. /**
  849. * Creates functions to query the DOM using a given method.
  850. *
  851. * @private
  852. * @param {string} method
  853. * The method to create the query with.
  854. *
  855. * @return {Function}
  856. * The query method
  857. */
  858. function createQuerier(method) {
  859. return function (selector, context) {
  860. if (!isNonBlankString(selector)) {
  861. return document[method](null);
  862. }
  863. if (isNonBlankString(context)) {
  864. context = document.querySelector(context);
  865. }
  866. const ctx = isEl(context) ? context : document;
  867. return ctx[method] && ctx[method](selector);
  868. };
  869. }
  870. /**
  871. * Creates an element and applies properties, attributes, and inserts content.
  872. *
  873. * @param {string} [tagName='div']
  874. * Name of tag to be created.
  875. *
  876. * @param {Object} [properties={}]
  877. * Element properties to be applied.
  878. *
  879. * @param {Object} [attributes={}]
  880. * Element attributes to be applied.
  881. *
  882. * @param {ContentDescriptor} [content]
  883. * A content descriptor object.
  884. *
  885. * @return {Element}
  886. * The element that was created.
  887. */
  888. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  889. const el = document.createElement(tagName);
  890. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  891. const val = properties[propName];
  892. // Handle textContent since it's not supported everywhere and we have a
  893. // method for it.
  894. if (propName === 'textContent') {
  895. textContent(el, val);
  896. } else if (el[propName] !== val || propName === 'tabIndex') {
  897. el[propName] = val;
  898. }
  899. });
  900. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  901. el.setAttribute(attrName, attributes[attrName]);
  902. });
  903. if (content) {
  904. appendContent(el, content);
  905. }
  906. return el;
  907. }
  908. /**
  909. * Injects text into an element, replacing any existing contents entirely.
  910. *
  911. * @param {Element} el
  912. * The element to add text content into
  913. *
  914. * @param {string} text
  915. * The text content to add.
  916. *
  917. * @return {Element}
  918. * The element with added text content.
  919. */
  920. function textContent(el, text) {
  921. if (typeof el.textContent === 'undefined') {
  922. el.innerText = text;
  923. } else {
  924. el.textContent = text;
  925. }
  926. return el;
  927. }
  928. /**
  929. * Insert an element as the first child node of another
  930. *
  931. * @param {Element} child
  932. * Element to insert
  933. *
  934. * @param {Element} parent
  935. * Element to insert child into
  936. */
  937. function prependTo(child, parent) {
  938. if (parent.firstChild) {
  939. parent.insertBefore(child, parent.firstChild);
  940. } else {
  941. parent.appendChild(child);
  942. }
  943. }
  944. /**
  945. * Check if an element has a class name.
  946. *
  947. * @param {Element} element
  948. * Element to check
  949. *
  950. * @param {string} classToCheck
  951. * Class name to check for
  952. *
  953. * @return {boolean}
  954. * Will be `true` if the element has a class, `false` otherwise.
  955. *
  956. * @throws {Error}
  957. * Throws an error if `classToCheck` has white space.
  958. */
  959. function hasClass(element, classToCheck) {
  960. throwIfWhitespace(classToCheck);
  961. return element.classList.contains(classToCheck);
  962. }
  963. /**
  964. * Add a class name to an element.
  965. *
  966. * @param {Element} element
  967. * Element to add class name to.
  968. *
  969. * @param {...string} classesToAdd
  970. * One or more class name to add.
  971. *
  972. * @return {Element}
  973. * The DOM element with the added class name.
  974. */
  975. function addClass(element, ...classesToAdd) {
  976. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  977. return element;
  978. }
  979. /**
  980. * Remove a class name from an element.
  981. *
  982. * @param {Element} element
  983. * Element to remove a class name from.
  984. *
  985. * @param {...string} classesToRemove
  986. * One or more class name to remove.
  987. *
  988. * @return {Element}
  989. * The DOM element with class name removed.
  990. */
  991. function removeClass(element, ...classesToRemove) {
  992. // Protect in case the player gets disposed
  993. if (!element) {
  994. log.warn("removeClass was called with an element that doesn't exist");
  995. return null;
  996. }
  997. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  998. return element;
  999. }
  1000. /**
  1001. * The callback definition for toggleClass.
  1002. *
  1003. * @callback module:dom~PredicateCallback
  1004. * @param {Element} element
  1005. * The DOM element of the Component.
  1006. *
  1007. * @param {string} classToToggle
  1008. * The `className` that wants to be toggled
  1009. *
  1010. * @return {boolean|undefined}
  1011. * If `true` is returned, the `classToToggle` will be added to the
  1012. * `element`. If `false`, the `classToToggle` will be removed from
  1013. * the `element`. If `undefined`, the callback will be ignored.
  1014. */
  1015. /**
  1016. * Adds or removes a class name to/from an element depending on an optional
  1017. * condition or the presence/absence of the class name.
  1018. *
  1019. * @param {Element} element
  1020. * The element to toggle a class name on.
  1021. *
  1022. * @param {string} classToToggle
  1023. * The class that should be toggled.
  1024. *
  1025. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1026. * See the return value for {@link module:dom~PredicateCallback}
  1027. *
  1028. * @return {Element}
  1029. * The element with a class that has been toggled.
  1030. */
  1031. function toggleClass(element, classToToggle, predicate) {
  1032. if (typeof predicate === 'function') {
  1033. predicate = predicate(element, classToToggle);
  1034. }
  1035. if (typeof predicate !== 'boolean') {
  1036. predicate = undefined;
  1037. }
  1038. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1039. return element;
  1040. }
  1041. /**
  1042. * Apply attributes to an HTML element.
  1043. *
  1044. * @param {Element} el
  1045. * Element to add attributes to.
  1046. *
  1047. * @param {Object} [attributes]
  1048. * Attributes to be applied.
  1049. */
  1050. function setAttributes(el, attributes) {
  1051. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1052. const attrValue = attributes[attrName];
  1053. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1054. el.removeAttribute(attrName);
  1055. } else {
  1056. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1057. }
  1058. });
  1059. }
  1060. /**
  1061. * Get an element's attribute values, as defined on the HTML tag.
  1062. *
  1063. * Attributes are not the same as properties. They're defined on the tag
  1064. * or with setAttribute.
  1065. *
  1066. * @param {Element} tag
  1067. * Element from which to get tag attributes.
  1068. *
  1069. * @return {Object}
  1070. * All attributes of the element. Boolean attributes will be `true` or
  1071. * `false`, others will be strings.
  1072. */
  1073. function getAttributes(tag) {
  1074. const obj = {};
  1075. // known boolean attributes
  1076. // we can check for matching boolean properties, but not all browsers
  1077. // and not all tags know about these attributes, so, we still want to check them manually
  1078. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1079. if (tag && tag.attributes && tag.attributes.length > 0) {
  1080. const attrs = tag.attributes;
  1081. for (let i = attrs.length - 1; i >= 0; i--) {
  1082. const attrName = attrs[i].name;
  1083. let attrVal = attrs[i].value;
  1084. // check for known booleans
  1085. // the matching element property will return a value for typeof
  1086. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1087. // the value of an included boolean attribute is typically an empty
  1088. // string ('') which would equal false if we just check for a false value.
  1089. // we also don't want support bad code like autoplay='false'
  1090. attrVal = attrVal !== null ? true : false;
  1091. }
  1092. obj[attrName] = attrVal;
  1093. }
  1094. }
  1095. return obj;
  1096. }
  1097. /**
  1098. * Get the value of an element's attribute.
  1099. *
  1100. * @param {Element} el
  1101. * A DOM element.
  1102. *
  1103. * @param {string} attribute
  1104. * Attribute to get the value of.
  1105. *
  1106. * @return {string}
  1107. * The value of the attribute.
  1108. */
  1109. function getAttribute(el, attribute) {
  1110. return el.getAttribute(attribute);
  1111. }
  1112. /**
  1113. * Set the value of an element's attribute.
  1114. *
  1115. * @param {Element} el
  1116. * A DOM element.
  1117. *
  1118. * @param {string} attribute
  1119. * Attribute to set.
  1120. *
  1121. * @param {string} value
  1122. * Value to set the attribute to.
  1123. */
  1124. function setAttribute(el, attribute, value) {
  1125. el.setAttribute(attribute, value);
  1126. }
  1127. /**
  1128. * Remove an element's attribute.
  1129. *
  1130. * @param {Element} el
  1131. * A DOM element.
  1132. *
  1133. * @param {string} attribute
  1134. * Attribute to remove.
  1135. */
  1136. function removeAttribute(el, attribute) {
  1137. el.removeAttribute(attribute);
  1138. }
  1139. /**
  1140. * Attempt to block the ability to select text.
  1141. */
  1142. function blockTextSelection() {
  1143. document.body.focus();
  1144. document.onselectstart = function () {
  1145. return false;
  1146. };
  1147. }
  1148. /**
  1149. * Turn off text selection blocking.
  1150. */
  1151. function unblockTextSelection() {
  1152. document.onselectstart = function () {
  1153. return true;
  1154. };
  1155. }
  1156. /**
  1157. * Identical to the native `getBoundingClientRect` function, but ensures that
  1158. * the method is supported at all (it is in all browsers we claim to support)
  1159. * and that the element is in the DOM before continuing.
  1160. *
  1161. * This wrapper function also shims properties which are not provided by some
  1162. * older browsers (namely, IE8).
  1163. *
  1164. * Additionally, some browsers do not support adding properties to a
  1165. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1166. * properties (except `x` and `y` which are not widely supported). This helps
  1167. * avoid implementations where keys are non-enumerable.
  1168. *
  1169. * @param {Element} el
  1170. * Element whose `ClientRect` we want to calculate.
  1171. *
  1172. * @return {Object|undefined}
  1173. * Always returns a plain object - or `undefined` if it cannot.
  1174. */
  1175. function getBoundingClientRect(el) {
  1176. if (el && el.getBoundingClientRect && el.parentNode) {
  1177. const rect = el.getBoundingClientRect();
  1178. const result = {};
  1179. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1180. if (rect[k] !== undefined) {
  1181. result[k] = rect[k];
  1182. }
  1183. });
  1184. if (!result.height) {
  1185. result.height = parseFloat(computedStyle(el, 'height'));
  1186. }
  1187. if (!result.width) {
  1188. result.width = parseFloat(computedStyle(el, 'width'));
  1189. }
  1190. return result;
  1191. }
  1192. }
  1193. /**
  1194. * Represents the position of a DOM element on the page.
  1195. *
  1196. * @typedef {Object} module:dom~Position
  1197. *
  1198. * @property {number} left
  1199. * Pixels to the left.
  1200. *
  1201. * @property {number} top
  1202. * Pixels from the top.
  1203. */
  1204. /**
  1205. * Get the position of an element in the DOM.
  1206. *
  1207. * Uses `getBoundingClientRect` technique from John Resig.
  1208. *
  1209. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1210. *
  1211. * @param {Element} el
  1212. * Element from which to get offset.
  1213. *
  1214. * @return {module:dom~Position}
  1215. * The position of the element that was passed in.
  1216. */
  1217. function findPosition(el) {
  1218. if (!el || el && !el.offsetParent) {
  1219. return {
  1220. left: 0,
  1221. top: 0,
  1222. width: 0,
  1223. height: 0
  1224. };
  1225. }
  1226. const width = el.offsetWidth;
  1227. const height = el.offsetHeight;
  1228. let left = 0;
  1229. let top = 0;
  1230. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1231. left += el.offsetLeft;
  1232. top += el.offsetTop;
  1233. el = el.offsetParent;
  1234. }
  1235. return {
  1236. left,
  1237. top,
  1238. width,
  1239. height
  1240. };
  1241. }
  1242. /**
  1243. * Represents x and y coordinates for a DOM element or mouse pointer.
  1244. *
  1245. * @typedef {Object} module:dom~Coordinates
  1246. *
  1247. * @property {number} x
  1248. * x coordinate in pixels
  1249. *
  1250. * @property {number} y
  1251. * y coordinate in pixels
  1252. */
  1253. /**
  1254. * Get the pointer position within an element.
  1255. *
  1256. * The base on the coordinates are the bottom left of the element.
  1257. *
  1258. * @param {Element} el
  1259. * Element on which to get the pointer position on.
  1260. *
  1261. * @param {Event} event
  1262. * Event object.
  1263. *
  1264. * @return {module:dom~Coordinates}
  1265. * A coordinates object corresponding to the mouse position.
  1266. *
  1267. */
  1268. function getPointerPosition(el, event) {
  1269. const translated = {
  1270. x: 0,
  1271. y: 0
  1272. };
  1273. if (IS_IOS) {
  1274. let item = el;
  1275. while (item && item.nodeName.toLowerCase() !== 'html') {
  1276. const transform = computedStyle(item, 'transform');
  1277. if (/^matrix/.test(transform)) {
  1278. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1279. translated.x += values[4];
  1280. translated.y += values[5];
  1281. } else if (/^matrix3d/.test(transform)) {
  1282. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1283. translated.x += values[12];
  1284. translated.y += values[13];
  1285. }
  1286. item = item.parentNode;
  1287. }
  1288. }
  1289. const position = {};
  1290. const boxTarget = findPosition(event.target);
  1291. const box = findPosition(el);
  1292. const boxW = box.width;
  1293. const boxH = box.height;
  1294. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1295. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1296. if (event.changedTouches) {
  1297. offsetX = event.changedTouches[0].pageX - box.left;
  1298. offsetY = event.changedTouches[0].pageY + box.top;
  1299. if (IS_IOS) {
  1300. offsetX -= translated.x;
  1301. offsetY -= translated.y;
  1302. }
  1303. }
  1304. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1305. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1306. return position;
  1307. }
  1308. /**
  1309. * Determines, via duck typing, whether or not a value is a text node.
  1310. *
  1311. * @param {*} value
  1312. * Check if this value is a text node.
  1313. *
  1314. * @return {boolean}
  1315. * Will be `true` if the value is a text node, `false` otherwise.
  1316. */
  1317. function isTextNode(value) {
  1318. return isObject(value) && value.nodeType === 3;
  1319. }
  1320. /**
  1321. * Empties the contents of an element.
  1322. *
  1323. * @param {Element} el
  1324. * The element to empty children from
  1325. *
  1326. * @return {Element}
  1327. * The element with no children
  1328. */
  1329. function emptyEl(el) {
  1330. while (el.firstChild) {
  1331. el.removeChild(el.firstChild);
  1332. }
  1333. return el;
  1334. }
  1335. /**
  1336. * This is a mixed value that describes content to be injected into the DOM
  1337. * via some method. It can be of the following types:
  1338. *
  1339. * Type | Description
  1340. * -----------|-------------
  1341. * `string` | The value will be normalized into a text node.
  1342. * `Element` | The value will be accepted as-is.
  1343. * `Text` | A TextNode. The value will be accepted as-is.
  1344. * `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).
  1345. * `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.
  1346. *
  1347. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1348. */
  1349. /**
  1350. * Normalizes content for eventual insertion into the DOM.
  1351. *
  1352. * This allows a wide range of content definition methods, but helps protect
  1353. * from falling into the trap of simply writing to `innerHTML`, which could
  1354. * be an XSS concern.
  1355. *
  1356. * The content for an element can be passed in multiple types and
  1357. * combinations, whose behavior is as follows:
  1358. *
  1359. * @param {ContentDescriptor} content
  1360. * A content descriptor value.
  1361. *
  1362. * @return {Array}
  1363. * All of the content that was passed in, normalized to an array of
  1364. * elements or text nodes.
  1365. */
  1366. function normalizeContent(content) {
  1367. // First, invoke content if it is a function. If it produces an array,
  1368. // that needs to happen before normalization.
  1369. if (typeof content === 'function') {
  1370. content = content();
  1371. }
  1372. // Next up, normalize to an array, so one or many items can be normalized,
  1373. // filtered, and returned.
  1374. return (Array.isArray(content) ? content : [content]).map(value => {
  1375. // First, invoke value if it is a function to produce a new value,
  1376. // which will be subsequently normalized to a Node of some kind.
  1377. if (typeof value === 'function') {
  1378. value = value();
  1379. }
  1380. if (isEl(value) || isTextNode(value)) {
  1381. return value;
  1382. }
  1383. if (typeof value === 'string' && /\S/.test(value)) {
  1384. return document.createTextNode(value);
  1385. }
  1386. }).filter(value => value);
  1387. }
  1388. /**
  1389. * Normalizes and appends content to an element.
  1390. *
  1391. * @param {Element} el
  1392. * Element to append normalized content to.
  1393. *
  1394. * @param {ContentDescriptor} content
  1395. * A content descriptor value.
  1396. *
  1397. * @return {Element}
  1398. * The element with appended normalized content.
  1399. */
  1400. function appendContent(el, content) {
  1401. normalizeContent(content).forEach(node => el.appendChild(node));
  1402. return el;
  1403. }
  1404. /**
  1405. * Normalizes and inserts content into an element; this is identical to
  1406. * `appendContent()`, except it empties the element first.
  1407. *
  1408. * @param {Element} el
  1409. * Element to insert normalized content into.
  1410. *
  1411. * @param {ContentDescriptor} content
  1412. * A content descriptor value.
  1413. *
  1414. * @return {Element}
  1415. * The element with inserted normalized content.
  1416. */
  1417. function insertContent(el, content) {
  1418. return appendContent(emptyEl(el), content);
  1419. }
  1420. /**
  1421. * Check if an event was a single left click.
  1422. *
  1423. * @param {Event} event
  1424. * Event object.
  1425. *
  1426. * @return {boolean}
  1427. * Will be `true` if a single left click, `false` otherwise.
  1428. */
  1429. function isSingleLeftClick(event) {
  1430. // Note: if you create something draggable, be sure to
  1431. // call it on both `mousedown` and `mousemove` event,
  1432. // otherwise `mousedown` should be enough for a button
  1433. if (event.button === undefined && event.buttons === undefined) {
  1434. // Why do we need `buttons` ?
  1435. // Because, middle mouse sometimes have this:
  1436. // e.button === 0 and e.buttons === 4
  1437. // Furthermore, we want to prevent combination click, something like
  1438. // HOLD middlemouse then left click, that would be
  1439. // e.button === 0, e.buttons === 5
  1440. // just `button` is not gonna work
  1441. // Alright, then what this block does ?
  1442. // this is for chrome `simulate mobile devices`
  1443. // I want to support this as well
  1444. return true;
  1445. }
  1446. if (event.button === 0 && event.buttons === undefined) {
  1447. // Touch screen, sometimes on some specific device, `buttons`
  1448. // doesn't have anything (safari on ios, blackberry...)
  1449. return true;
  1450. }
  1451. // `mouseup` event on a single left click has
  1452. // `button` and `buttons` equal to 0
  1453. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1454. return true;
  1455. }
  1456. if (event.button !== 0 || event.buttons !== 1) {
  1457. // This is the reason we have those if else block above
  1458. // if any special case we can catch and let it slide
  1459. // we do it above, when get to here, this definitely
  1460. // is-not-left-click
  1461. return false;
  1462. }
  1463. return true;
  1464. }
  1465. /**
  1466. * Finds a single DOM element matching `selector` within the optional
  1467. * `context` of another DOM element (defaulting to `document`).
  1468. *
  1469. * @param {string} selector
  1470. * A valid CSS selector, which will be passed to `querySelector`.
  1471. *
  1472. * @param {Element|String} [context=document]
  1473. * A DOM element within which to query. Can also be a selector
  1474. * string in which case the first matching element will be used
  1475. * as context. If missing (or no element matches selector), falls
  1476. * back to `document`.
  1477. *
  1478. * @return {Element|null}
  1479. * The element that was found or null.
  1480. */
  1481. const $ = createQuerier('querySelector');
  1482. /**
  1483. * Finds a all DOM elements matching `selector` within the optional
  1484. * `context` of another DOM element (defaulting to `document`).
  1485. *
  1486. * @param {string} selector
  1487. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1488. *
  1489. * @param {Element|String} [context=document]
  1490. * A DOM element within which to query. Can also be a selector
  1491. * string in which case the first matching element will be used
  1492. * as context. If missing (or no element matches selector), falls
  1493. * back to `document`.
  1494. *
  1495. * @return {NodeList}
  1496. * A element list of elements that were found. Will be empty if none
  1497. * were found.
  1498. *
  1499. */
  1500. const $$ = createQuerier('querySelectorAll');
  1501. /**
  1502. * A safe getComputedStyle.
  1503. *
  1504. * This is needed because in Firefox, if the player is loaded in an iframe with
  1505. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1506. * null-check to make sure that the player doesn't break in these cases.
  1507. *
  1508. * @param {Element} el
  1509. * The element you want the computed style of
  1510. *
  1511. * @param {string} prop
  1512. * The property name you want
  1513. *
  1514. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1515. */
  1516. function computedStyle(el, prop) {
  1517. if (!el || !prop) {
  1518. return '';
  1519. }
  1520. if (typeof window.getComputedStyle === 'function') {
  1521. let computedStyleValue;
  1522. try {
  1523. computedStyleValue = window.getComputedStyle(el);
  1524. } catch (e) {
  1525. return '';
  1526. }
  1527. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1528. }
  1529. return '';
  1530. }
  1531. var Dom = /*#__PURE__*/Object.freeze({
  1532. __proto__: null,
  1533. isReal: isReal,
  1534. isEl: isEl,
  1535. isInFrame: isInFrame,
  1536. createEl: createEl,
  1537. textContent: textContent,
  1538. prependTo: prependTo,
  1539. hasClass: hasClass,
  1540. addClass: addClass,
  1541. removeClass: removeClass,
  1542. toggleClass: toggleClass,
  1543. setAttributes: setAttributes,
  1544. getAttributes: getAttributes,
  1545. getAttribute: getAttribute,
  1546. setAttribute: setAttribute,
  1547. removeAttribute: removeAttribute,
  1548. blockTextSelection: blockTextSelection,
  1549. unblockTextSelection: unblockTextSelection,
  1550. getBoundingClientRect: getBoundingClientRect,
  1551. findPosition: findPosition,
  1552. getPointerPosition: getPointerPosition,
  1553. isTextNode: isTextNode,
  1554. emptyEl: emptyEl,
  1555. normalizeContent: normalizeContent,
  1556. appendContent: appendContent,
  1557. insertContent: insertContent,
  1558. isSingleLeftClick: isSingleLeftClick,
  1559. $: $,
  1560. $$: $$,
  1561. computedStyle: computedStyle
  1562. });
  1563. /**
  1564. * @file setup.js - Functions for setting up a player without
  1565. * user interaction based on the data-setup `attribute` of the video tag.
  1566. *
  1567. * @module setup
  1568. */
  1569. let _windowLoaded = false;
  1570. let videojs$1;
  1571. /**
  1572. * Set up any tags that have a data-setup `attribute` when the player is started.
  1573. */
  1574. const autoSetup = function () {
  1575. if (videojs$1.options.autoSetup === false) {
  1576. return;
  1577. }
  1578. const vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1579. const audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1580. const divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1581. const mediaEls = vids.concat(audios, divs);
  1582. // Check if any media elements exist
  1583. if (mediaEls && mediaEls.length > 0) {
  1584. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1585. const mediaEl = mediaEls[i];
  1586. // Check if element exists, has getAttribute func.
  1587. if (mediaEl && mediaEl.getAttribute) {
  1588. // Make sure this player hasn't already been set up.
  1589. if (mediaEl.player === undefined) {
  1590. const options = mediaEl.getAttribute('data-setup');
  1591. // Check if data-setup attr exists.
  1592. // We only auto-setup if they've added the data-setup attr.
  1593. if (options !== null) {
  1594. // Create new video.js instance.
  1595. videojs$1(mediaEl);
  1596. }
  1597. }
  1598. // If getAttribute isn't defined, we need to wait for the DOM.
  1599. } else {
  1600. autoSetupTimeout(1);
  1601. break;
  1602. }
  1603. }
  1604. // No videos were found, so keep looping unless page is finished loading.
  1605. } else if (!_windowLoaded) {
  1606. autoSetupTimeout(1);
  1607. }
  1608. };
  1609. /**
  1610. * Wait until the page is loaded before running autoSetup. This will be called in
  1611. * autoSetup if `hasLoaded` returns false.
  1612. *
  1613. * @param {number} wait
  1614. * How long to wait in ms
  1615. *
  1616. * @param {module:videojs} [vjs]
  1617. * The videojs library function
  1618. */
  1619. function autoSetupTimeout(wait, vjs) {
  1620. // Protect against breakage in non-browser environments
  1621. if (!isReal()) {
  1622. return;
  1623. }
  1624. if (vjs) {
  1625. videojs$1 = vjs;
  1626. }
  1627. window.setTimeout(autoSetup, wait);
  1628. }
  1629. /**
  1630. * Used to set the internal tracking of window loaded state to true.
  1631. *
  1632. * @private
  1633. */
  1634. function setWindowLoaded() {
  1635. _windowLoaded = true;
  1636. window.removeEventListener('load', setWindowLoaded);
  1637. }
  1638. if (isReal()) {
  1639. if (document.readyState === 'complete') {
  1640. setWindowLoaded();
  1641. } else {
  1642. /**
  1643. * Listen for the load event on window, and set _windowLoaded to true.
  1644. *
  1645. * We use a standard event listener here to avoid incrementing the GUID
  1646. * before any players are created.
  1647. *
  1648. * @listens load
  1649. */
  1650. window.addEventListener('load', setWindowLoaded);
  1651. }
  1652. }
  1653. /**
  1654. * @file stylesheet.js
  1655. * @module stylesheet
  1656. */
  1657. /**
  1658. * Create a DOM style element given a className for it.
  1659. *
  1660. * @param {string} className
  1661. * The className to add to the created style element.
  1662. *
  1663. * @return {Element}
  1664. * The element that was created.
  1665. */
  1666. const createStyleElement = function (className) {
  1667. const style = document.createElement('style');
  1668. style.className = className;
  1669. return style;
  1670. };
  1671. /**
  1672. * Add text to a DOM element.
  1673. *
  1674. * @param {Element} el
  1675. * The Element to add text content to.
  1676. *
  1677. * @param {string} content
  1678. * The text to add to the element.
  1679. */
  1680. const setTextContent = function (el, content) {
  1681. if (el.styleSheet) {
  1682. el.styleSheet.cssText = content;
  1683. } else {
  1684. el.textContent = content;
  1685. }
  1686. };
  1687. /**
  1688. * @file dom-data.js
  1689. * @module dom-data
  1690. */
  1691. /**
  1692. * Element Data Store.
  1693. *
  1694. * Allows for binding data to an element without putting it directly on the
  1695. * element. Ex. Event listeners are stored here.
  1696. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1697. *
  1698. * @type {Object}
  1699. * @private
  1700. */
  1701. var DomData = new WeakMap();
  1702. /**
  1703. * @file guid.js
  1704. * @module guid
  1705. */
  1706. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1707. //
  1708. // The initial GUID is 3 because some users have come to rely on the first
  1709. // default player ID ending up as `vjs_video_3`.
  1710. //
  1711. // See: https://github.com/videojs/video.js/pull/6216
  1712. const _initialGuid = 3;
  1713. /**
  1714. * Unique ID for an element or function
  1715. *
  1716. * @type {Number}
  1717. */
  1718. let _guid = _initialGuid;
  1719. /**
  1720. * Get a unique auto-incrementing ID by number that has not been returned before.
  1721. *
  1722. * @return {number}
  1723. * A new unique ID.
  1724. */
  1725. function newGUID() {
  1726. return _guid++;
  1727. }
  1728. /**
  1729. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1730. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1731. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1732. * robust as jquery's, so there's probably some differences.
  1733. *
  1734. * @file events.js
  1735. * @module events
  1736. */
  1737. /**
  1738. * Clean up the listener cache and dispatchers
  1739. *
  1740. * @param {Element|Object} elem
  1741. * Element to clean up
  1742. *
  1743. * @param {string} type
  1744. * Type of event to clean up
  1745. */
  1746. function _cleanUpEvents(elem, type) {
  1747. if (!DomData.has(elem)) {
  1748. return;
  1749. }
  1750. const data = DomData.get(elem);
  1751. // Remove the events of a particular type if there are none left
  1752. if (data.handlers[type].length === 0) {
  1753. delete data.handlers[type];
  1754. // data.handlers[type] = null;
  1755. // Setting to null was causing an error with data.handlers
  1756. // Remove the meta-handler from the element
  1757. if (elem.removeEventListener) {
  1758. elem.removeEventListener(type, data.dispatcher, false);
  1759. } else if (elem.detachEvent) {
  1760. elem.detachEvent('on' + type, data.dispatcher);
  1761. }
  1762. }
  1763. // Remove the events object if there are no types left
  1764. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1765. delete data.handlers;
  1766. delete data.dispatcher;
  1767. delete data.disabled;
  1768. }
  1769. // Finally remove the element data if there is no data left
  1770. if (Object.getOwnPropertyNames(data).length === 0) {
  1771. DomData.delete(elem);
  1772. }
  1773. }
  1774. /**
  1775. * Loops through an array of event types and calls the requested method for each type.
  1776. *
  1777. * @param {Function} fn
  1778. * The event method we want to use.
  1779. *
  1780. * @param {Element|Object} elem
  1781. * Element or object to bind listeners to
  1782. *
  1783. * @param {string} type
  1784. * Type of event to bind to.
  1785. *
  1786. * @param {Function} callback
  1787. * Event listener.
  1788. */
  1789. function _handleMultipleEvents(fn, elem, types, callback) {
  1790. types.forEach(function (type) {
  1791. // Call the event method for each one of the types
  1792. fn(elem, type, callback);
  1793. });
  1794. }
  1795. /**
  1796. * Fix a native event to have standard property values
  1797. *
  1798. * @param {Object} event
  1799. * Event object to fix.
  1800. *
  1801. * @return {Object}
  1802. * Fixed event object.
  1803. */
  1804. function fixEvent(event) {
  1805. if (event.fixed_) {
  1806. return event;
  1807. }
  1808. function returnTrue() {
  1809. return true;
  1810. }
  1811. function returnFalse() {
  1812. return false;
  1813. }
  1814. // Test if fixing up is needed
  1815. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1816. // But native events return true for stopPropagation, but don't have
  1817. // other expected methods like isPropagationStopped. Seems to be a problem
  1818. // with the Javascript Ninja code. So we're just overriding all events now.
  1819. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1820. const old = event || window.event;
  1821. event = {};
  1822. // Clone the old object so that we can modify the values event = {};
  1823. // IE8 Doesn't like when you mess with native event properties
  1824. // Firefox returns false for event.hasOwnProperty('type') and other props
  1825. // which makes copying more difficult.
  1826. // TODO: Probably best to create a whitelist of event props
  1827. for (const key in old) {
  1828. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1829. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1830. // and webkitMovementX/Y
  1831. // Lighthouse complains if Event.path is copied
  1832. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1833. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1834. // we still want to if preventDefault isn't supported (IE8).
  1835. if (!(key === 'returnValue' && old.preventDefault)) {
  1836. event[key] = old[key];
  1837. }
  1838. }
  1839. }
  1840. // The event occurred on this element
  1841. if (!event.target) {
  1842. event.target = event.srcElement || document;
  1843. }
  1844. // Handle which other element the event is related to
  1845. if (!event.relatedTarget) {
  1846. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1847. }
  1848. // Stop the default browser action
  1849. event.preventDefault = function () {
  1850. if (old.preventDefault) {
  1851. old.preventDefault();
  1852. }
  1853. event.returnValue = false;
  1854. old.returnValue = false;
  1855. event.defaultPrevented = true;
  1856. };
  1857. event.defaultPrevented = false;
  1858. // Stop the event from bubbling
  1859. event.stopPropagation = function () {
  1860. if (old.stopPropagation) {
  1861. old.stopPropagation();
  1862. }
  1863. event.cancelBubble = true;
  1864. old.cancelBubble = true;
  1865. event.isPropagationStopped = returnTrue;
  1866. };
  1867. event.isPropagationStopped = returnFalse;
  1868. // Stop the event from bubbling and executing other handlers
  1869. event.stopImmediatePropagation = function () {
  1870. if (old.stopImmediatePropagation) {
  1871. old.stopImmediatePropagation();
  1872. }
  1873. event.isImmediatePropagationStopped = returnTrue;
  1874. event.stopPropagation();
  1875. };
  1876. event.isImmediatePropagationStopped = returnFalse;
  1877. // Handle mouse position
  1878. if (event.clientX !== null && event.clientX !== undefined) {
  1879. const doc = document.documentElement;
  1880. const body = document.body;
  1881. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1882. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1883. }
  1884. // Handle key presses
  1885. event.which = event.charCode || event.keyCode;
  1886. // Fix button for mouse clicks:
  1887. // 0 == left; 1 == middle; 2 == right
  1888. if (event.button !== null && event.button !== undefined) {
  1889. // The following is disabled because it does not pass videojs-standard
  1890. // and... yikes.
  1891. /* eslint-disable */
  1892. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1893. /* eslint-enable */
  1894. }
  1895. }
  1896. event.fixed_ = true;
  1897. // Returns fixed-up instance
  1898. return event;
  1899. }
  1900. /**
  1901. * Whether passive event listeners are supported
  1902. */
  1903. let _supportsPassive;
  1904. const supportsPassive = function () {
  1905. if (typeof _supportsPassive !== 'boolean') {
  1906. _supportsPassive = false;
  1907. try {
  1908. const opts = Object.defineProperty({}, 'passive', {
  1909. get() {
  1910. _supportsPassive = true;
  1911. }
  1912. });
  1913. window.addEventListener('test', null, opts);
  1914. window.removeEventListener('test', null, opts);
  1915. } catch (e) {
  1916. // disregard
  1917. }
  1918. }
  1919. return _supportsPassive;
  1920. };
  1921. /**
  1922. * Touch events Chrome expects to be passive
  1923. */
  1924. const passiveEvents = ['touchstart', 'touchmove'];
  1925. /**
  1926. * Add an event listener to element
  1927. * It stores the handler function in a separate cache object
  1928. * and adds a generic handler to the element's event,
  1929. * along with a unique id (guid) to the element.
  1930. *
  1931. * @param {Element|Object} elem
  1932. * Element or object to bind listeners to
  1933. *
  1934. * @param {string|string[]} type
  1935. * Type of event to bind to.
  1936. *
  1937. * @param {Function} fn
  1938. * Event listener.
  1939. */
  1940. function on(elem, type, fn) {
  1941. if (Array.isArray(type)) {
  1942. return _handleMultipleEvents(on, elem, type, fn);
  1943. }
  1944. if (!DomData.has(elem)) {
  1945. DomData.set(elem, {});
  1946. }
  1947. const data = DomData.get(elem);
  1948. // We need a place to store all our handler data
  1949. if (!data.handlers) {
  1950. data.handlers = {};
  1951. }
  1952. if (!data.handlers[type]) {
  1953. data.handlers[type] = [];
  1954. }
  1955. if (!fn.guid) {
  1956. fn.guid = newGUID();
  1957. }
  1958. data.handlers[type].push(fn);
  1959. if (!data.dispatcher) {
  1960. data.disabled = false;
  1961. data.dispatcher = function (event, hash) {
  1962. if (data.disabled) {
  1963. return;
  1964. }
  1965. event = fixEvent(event);
  1966. const handlers = data.handlers[event.type];
  1967. if (handlers) {
  1968. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1969. const handlersCopy = handlers.slice(0);
  1970. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1971. if (event.isImmediatePropagationStopped()) {
  1972. break;
  1973. } else {
  1974. try {
  1975. handlersCopy[m].call(elem, event, hash);
  1976. } catch (e) {
  1977. log.error(e);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. };
  1983. }
  1984. if (data.handlers[type].length === 1) {
  1985. if (elem.addEventListener) {
  1986. let options = false;
  1987. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  1988. options = {
  1989. passive: true
  1990. };
  1991. }
  1992. elem.addEventListener(type, data.dispatcher, options);
  1993. } else if (elem.attachEvent) {
  1994. elem.attachEvent('on' + type, data.dispatcher);
  1995. }
  1996. }
  1997. }
  1998. /**
  1999. * Removes event listeners from an element
  2000. *
  2001. * @param {Element|Object} elem
  2002. * Object to remove listeners from.
  2003. *
  2004. * @param {string|string[]} [type]
  2005. * Type of listener to remove. Don't include to remove all events from element.
  2006. *
  2007. * @param {Function} [fn]
  2008. * Specific listener to remove. Don't include to remove listeners for an event
  2009. * type.
  2010. */
  2011. function off(elem, type, fn) {
  2012. // Don't want to add a cache object through getElData if not needed
  2013. if (!DomData.has(elem)) {
  2014. return;
  2015. }
  2016. const data = DomData.get(elem);
  2017. // If no events exist, nothing to unbind
  2018. if (!data.handlers) {
  2019. return;
  2020. }
  2021. if (Array.isArray(type)) {
  2022. return _handleMultipleEvents(off, elem, type, fn);
  2023. }
  2024. // Utility function
  2025. const removeType = function (el, t) {
  2026. data.handlers[t] = [];
  2027. _cleanUpEvents(el, t);
  2028. };
  2029. // Are we removing all bound events?
  2030. if (type === undefined) {
  2031. for (const t in data.handlers) {
  2032. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2033. removeType(elem, t);
  2034. }
  2035. }
  2036. return;
  2037. }
  2038. const handlers = data.handlers[type];
  2039. // If no handlers exist, nothing to unbind
  2040. if (!handlers) {
  2041. return;
  2042. }
  2043. // If no listener was provided, remove all listeners for type
  2044. if (!fn) {
  2045. removeType(elem, type);
  2046. return;
  2047. }
  2048. // We're only removing a single handler
  2049. if (fn.guid) {
  2050. for (let n = 0; n < handlers.length; n++) {
  2051. if (handlers[n].guid === fn.guid) {
  2052. handlers.splice(n--, 1);
  2053. }
  2054. }
  2055. }
  2056. _cleanUpEvents(elem, type);
  2057. }
  2058. /**
  2059. * Trigger an event for an element
  2060. *
  2061. * @param {Element|Object} elem
  2062. * Element to trigger an event on
  2063. *
  2064. * @param {EventTarget~Event|string} event
  2065. * A string (the type) or an event object with a type attribute
  2066. *
  2067. * @param {Object} [hash]
  2068. * data hash to pass along with the event
  2069. *
  2070. * @return {boolean|undefined}
  2071. * Returns the opposite of `defaultPrevented` if default was
  2072. * prevented. Otherwise, returns `undefined`
  2073. */
  2074. function trigger(elem, event, hash) {
  2075. // Fetches element data and a reference to the parent (for bubbling).
  2076. // Don't want to add a data object to cache for every parent,
  2077. // so checking hasElData first.
  2078. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2079. const parent = elem.parentNode || elem.ownerDocument;
  2080. // type = event.type || event,
  2081. // handler;
  2082. // If an event name was passed as a string, creates an event out of it
  2083. if (typeof event === 'string') {
  2084. event = {
  2085. type: event,
  2086. target: elem
  2087. };
  2088. } else if (!event.target) {
  2089. event.target = elem;
  2090. }
  2091. // Normalizes the event properties.
  2092. event = fixEvent(event);
  2093. // If the passed element has a dispatcher, executes the established handlers.
  2094. if (elemData.dispatcher) {
  2095. elemData.dispatcher.call(elem, event, hash);
  2096. }
  2097. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2098. // recursively calls this function to bubble the event up the DOM.
  2099. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2100. trigger.call(null, parent, event, hash);
  2101. // If at the top of the DOM, triggers the default action unless disabled.
  2102. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2103. if (!DomData.has(event.target)) {
  2104. DomData.set(event.target, {});
  2105. }
  2106. const targetData = DomData.get(event.target);
  2107. // Checks if the target has a default action for this event.
  2108. if (event.target[event.type]) {
  2109. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2110. targetData.disabled = true;
  2111. // Executes the default action.
  2112. if (typeof event.target[event.type] === 'function') {
  2113. event.target[event.type]();
  2114. }
  2115. // Re-enables event dispatching.
  2116. targetData.disabled = false;
  2117. }
  2118. }
  2119. // Inform the triggerer if the default was prevented by returning false
  2120. return !event.defaultPrevented;
  2121. }
  2122. /**
  2123. * Trigger a listener only once for an event.
  2124. *
  2125. * @param {Element|Object} elem
  2126. * Element or object to bind to.
  2127. *
  2128. * @param {string|string[]} type
  2129. * Name/type of event
  2130. *
  2131. * @param {Event~EventListener} fn
  2132. * Event listener function
  2133. */
  2134. function one(elem, type, fn) {
  2135. if (Array.isArray(type)) {
  2136. return _handleMultipleEvents(one, elem, type, fn);
  2137. }
  2138. const func = function () {
  2139. off(elem, type, func);
  2140. fn.apply(this, arguments);
  2141. };
  2142. // copy the guid to the new function so it can removed using the original function's ID
  2143. func.guid = fn.guid = fn.guid || newGUID();
  2144. on(elem, type, func);
  2145. }
  2146. /**
  2147. * Trigger a listener only once and then turn if off for all
  2148. * configured events
  2149. *
  2150. * @param {Element|Object} elem
  2151. * Element or object to bind to.
  2152. *
  2153. * @param {string|string[]} type
  2154. * Name/type of event
  2155. *
  2156. * @param {Event~EventListener} fn
  2157. * Event listener function
  2158. */
  2159. function any(elem, type, fn) {
  2160. const func = function () {
  2161. off(elem, type, func);
  2162. fn.apply(this, arguments);
  2163. };
  2164. // copy the guid to the new function so it can removed using the original function's ID
  2165. func.guid = fn.guid = fn.guid || newGUID();
  2166. // multiple ons, but one off for everything
  2167. on(elem, type, func);
  2168. }
  2169. var Events = /*#__PURE__*/Object.freeze({
  2170. __proto__: null,
  2171. fixEvent: fixEvent,
  2172. on: on,
  2173. off: off,
  2174. trigger: trigger,
  2175. one: one,
  2176. any: any
  2177. });
  2178. /**
  2179. * @file fn.js
  2180. * @module fn
  2181. */
  2182. const UPDATE_REFRESH_INTERVAL = 30;
  2183. /**
  2184. * A private, internal-only function for changing the context of a function.
  2185. *
  2186. * It also stores a unique id on the function so it can be easily removed from
  2187. * events.
  2188. *
  2189. * @private
  2190. * @function
  2191. * @param {*} context
  2192. * The object to bind as scope.
  2193. *
  2194. * @param {Function} fn
  2195. * The function to be bound to a scope.
  2196. *
  2197. * @param {number} [uid]
  2198. * An optional unique ID for the function to be set
  2199. *
  2200. * @return {Function}
  2201. * The new function that will be bound into the context given
  2202. */
  2203. const bind_ = function (context, fn, uid) {
  2204. // Make sure the function has a unique ID
  2205. if (!fn.guid) {
  2206. fn.guid = newGUID();
  2207. }
  2208. // Create the new function that changes the context
  2209. const bound = fn.bind(context);
  2210. // Allow for the ability to individualize this function
  2211. // Needed in the case where multiple objects might share the same prototype
  2212. // IF both items add an event listener with the same function, then you try to remove just one
  2213. // it will remove both because they both have the same guid.
  2214. // when using this, you need to use the bind method when you remove the listener as well.
  2215. // currently used in text tracks
  2216. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2217. return bound;
  2218. };
  2219. /**
  2220. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2221. * at most once per every `wait` milliseconds.
  2222. *
  2223. * @function
  2224. * @param {Function} fn
  2225. * The function to be throttled.
  2226. *
  2227. * @param {number} wait
  2228. * The number of milliseconds by which to throttle.
  2229. *
  2230. * @return {Function}
  2231. */
  2232. const throttle = function (fn, wait) {
  2233. let last = window.performance.now();
  2234. const throttled = function (...args) {
  2235. const now = window.performance.now();
  2236. if (now - last >= wait) {
  2237. fn(...args);
  2238. last = now;
  2239. }
  2240. };
  2241. return throttled;
  2242. };
  2243. /**
  2244. * Creates a debounced function that delays invoking `func` until after `wait`
  2245. * milliseconds have elapsed since the last time the debounced function was
  2246. * invoked.
  2247. *
  2248. * Inspired by lodash and underscore implementations.
  2249. *
  2250. * @function
  2251. * @param {Function} func
  2252. * The function to wrap with debounce behavior.
  2253. *
  2254. * @param {number} wait
  2255. * The number of milliseconds to wait after the last invocation.
  2256. *
  2257. * @param {boolean} [immediate]
  2258. * Whether or not to invoke the function immediately upon creation.
  2259. *
  2260. * @param {Object} [context=window]
  2261. * The "context" in which the debounced function should debounce. For
  2262. * example, if this function should be tied to a Video.js player,
  2263. * the player can be passed here. Alternatively, defaults to the
  2264. * global `window` object.
  2265. *
  2266. * @return {Function}
  2267. * A debounced function.
  2268. */
  2269. const debounce = function (func, wait, immediate, context = window) {
  2270. let timeout;
  2271. const cancel = () => {
  2272. context.clearTimeout(timeout);
  2273. timeout = null;
  2274. };
  2275. /* eslint-disable consistent-this */
  2276. const debounced = function () {
  2277. const self = this;
  2278. const args = arguments;
  2279. let later = function () {
  2280. timeout = null;
  2281. later = null;
  2282. if (!immediate) {
  2283. func.apply(self, args);
  2284. }
  2285. };
  2286. if (!timeout && immediate) {
  2287. func.apply(self, args);
  2288. }
  2289. context.clearTimeout(timeout);
  2290. timeout = context.setTimeout(later, wait);
  2291. };
  2292. /* eslint-enable consistent-this */
  2293. debounced.cancel = cancel;
  2294. return debounced;
  2295. };
  2296. var Fn = /*#__PURE__*/Object.freeze({
  2297. __proto__: null,
  2298. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2299. bind_: bind_,
  2300. throttle: throttle,
  2301. debounce: debounce
  2302. });
  2303. /**
  2304. * @file src/js/event-target.js
  2305. */
  2306. let EVENT_MAP;
  2307. /**
  2308. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2309. * adds shorthand functions that wrap around lengthy functions. For example:
  2310. * the `on` function is a wrapper around `addEventListener`.
  2311. *
  2312. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2313. * @class EventTarget
  2314. */
  2315. class EventTarget {
  2316. /**
  2317. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2318. * function that will get called when an event with a certain name gets triggered.
  2319. *
  2320. * @param {string|string[]} type
  2321. * An event name or an array of event names.
  2322. *
  2323. * @param {Function} fn
  2324. * The function to call with `EventTarget`s
  2325. */
  2326. on(type, fn) {
  2327. // Remove the addEventListener alias before calling Events.on
  2328. // so we don't get into an infinite type loop
  2329. const ael = this.addEventListener;
  2330. this.addEventListener = () => {};
  2331. on(this, type, fn);
  2332. this.addEventListener = ael;
  2333. }
  2334. /**
  2335. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2336. * This makes it so that the `event listener` will no longer get called when the
  2337. * named event happens.
  2338. *
  2339. * @param {string|string[]} type
  2340. * An event name or an array of event names.
  2341. *
  2342. * @param {Function} fn
  2343. * The function to remove.
  2344. */
  2345. off(type, fn) {
  2346. off(this, type, fn);
  2347. }
  2348. /**
  2349. * This function will add an `event listener` that gets triggered only once. After the
  2350. * first trigger it will get removed. This is like adding an `event listener`
  2351. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2352. *
  2353. * @param {string|string[]} type
  2354. * An event name or an array of event names.
  2355. *
  2356. * @param {Function} fn
  2357. * The function to be called once for each event name.
  2358. */
  2359. one(type, fn) {
  2360. // Remove the addEventListener aliasing Events.on
  2361. // so we don't get into an infinite type loop
  2362. const ael = this.addEventListener;
  2363. this.addEventListener = () => {};
  2364. one(this, type, fn);
  2365. this.addEventListener = ael;
  2366. }
  2367. /**
  2368. * This function will add an `event listener` that gets triggered only once and is
  2369. * removed from all events. This is like adding an array of `event listener`s
  2370. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2371. * first time it is triggered.
  2372. *
  2373. * @param {string|string[]} type
  2374. * An event name or an array of event names.
  2375. *
  2376. * @param {Function} fn
  2377. * The function to be called once for each event name.
  2378. */
  2379. any(type, fn) {
  2380. // Remove the addEventListener aliasing Events.on
  2381. // so we don't get into an infinite type loop
  2382. const ael = this.addEventListener;
  2383. this.addEventListener = () => {};
  2384. any(this, type, fn);
  2385. this.addEventListener = ael;
  2386. }
  2387. /**
  2388. * This function causes an event to happen. This will then cause any `event listeners`
  2389. * that are waiting for that event, to get called. If there are no `event listeners`
  2390. * for an event then nothing will happen.
  2391. *
  2392. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2393. * Trigger will also call the `on` + `uppercaseEventName` function.
  2394. *
  2395. * Example:
  2396. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2397. * `onClick` if it exists.
  2398. *
  2399. * @param {string|EventTarget~Event|Object} event
  2400. * The name of the event, an `Event`, or an object with a key of type set to
  2401. * an event name.
  2402. */
  2403. trigger(event) {
  2404. const type = event.type || event;
  2405. // deprecation
  2406. // In a future version we should default target to `this`
  2407. // similar to how we default the target to `elem` in
  2408. // `Events.trigger`. Right now the default `target` will be
  2409. // `document` due to the `Event.fixEvent` call.
  2410. if (typeof event === 'string') {
  2411. event = {
  2412. type
  2413. };
  2414. }
  2415. event = fixEvent(event);
  2416. if (this.allowedEvents_[type] && this['on' + type]) {
  2417. this['on' + type](event);
  2418. }
  2419. trigger(this, event);
  2420. }
  2421. queueTrigger(event) {
  2422. // only set up EVENT_MAP if it'll be used
  2423. if (!EVENT_MAP) {
  2424. EVENT_MAP = new Map();
  2425. }
  2426. const type = event.type || event;
  2427. let map = EVENT_MAP.get(this);
  2428. if (!map) {
  2429. map = new Map();
  2430. EVENT_MAP.set(this, map);
  2431. }
  2432. const oldTimeout = map.get(type);
  2433. map.delete(type);
  2434. window.clearTimeout(oldTimeout);
  2435. const timeout = window.setTimeout(() => {
  2436. map.delete(type);
  2437. // if we cleared out all timeouts for the current target, delete its map
  2438. if (map.size === 0) {
  2439. map = null;
  2440. EVENT_MAP.delete(this);
  2441. }
  2442. this.trigger(event);
  2443. }, 0);
  2444. map.set(type, timeout);
  2445. }
  2446. }
  2447. /**
  2448. * A Custom DOM event.
  2449. *
  2450. * @typedef {CustomEvent} Event
  2451. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2452. */
  2453. /**
  2454. * All event listeners should follow the following format.
  2455. *
  2456. * @callback EventTarget~EventListener
  2457. * @this {EventTarget}
  2458. *
  2459. * @param {Event} event
  2460. * the event that triggered this function
  2461. *
  2462. * @param {Object} [hash]
  2463. * hash of data sent during the event
  2464. */
  2465. /**
  2466. * An object containing event names as keys and booleans as values.
  2467. *
  2468. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2469. * will have extra functionality. See that function for more information.
  2470. *
  2471. * @property EventTarget.prototype.allowedEvents_
  2472. * @private
  2473. */
  2474. EventTarget.prototype.allowedEvents_ = {};
  2475. /**
  2476. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2477. * the standard DOM API.
  2478. *
  2479. * @function
  2480. * @see {@link EventTarget#on}
  2481. */
  2482. EventTarget.prototype.addEventListener = EventTarget.prototype.on;
  2483. /**
  2484. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2485. * the standard DOM API.
  2486. *
  2487. * @function
  2488. * @see {@link EventTarget#off}
  2489. */
  2490. EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
  2491. /**
  2492. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2493. * the standard DOM API.
  2494. *
  2495. * @function
  2496. * @see {@link EventTarget#trigger}
  2497. */
  2498. EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
  2499. /**
  2500. * @file mixins/evented.js
  2501. * @module evented
  2502. */
  2503. const objName = obj => {
  2504. if (typeof obj.name === 'function') {
  2505. return obj.name();
  2506. }
  2507. if (typeof obj.name === 'string') {
  2508. return obj.name;
  2509. }
  2510. if (obj.name_) {
  2511. return obj.name_;
  2512. }
  2513. if (obj.constructor && obj.constructor.name) {
  2514. return obj.constructor.name;
  2515. }
  2516. return typeof obj;
  2517. };
  2518. /**
  2519. * Returns whether or not an object has had the evented mixin applied.
  2520. *
  2521. * @param {Object} object
  2522. * An object to test.
  2523. *
  2524. * @return {boolean}
  2525. * Whether or not the object appears to be evented.
  2526. */
  2527. const isEvented = object => object instanceof EventTarget || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2528. /**
  2529. * Adds a callback to run after the evented mixin applied.
  2530. *
  2531. * @param {Object} object
  2532. * An object to Add
  2533. * @param {Function} callback
  2534. * The callback to run.
  2535. */
  2536. const addEventedCallback = (target, callback) => {
  2537. if (isEvented(target)) {
  2538. callback();
  2539. } else {
  2540. if (!target.eventedCallbacks) {
  2541. target.eventedCallbacks = [];
  2542. }
  2543. target.eventedCallbacks.push(callback);
  2544. }
  2545. };
  2546. /**
  2547. * Whether a value is a valid event type - non-empty string or array.
  2548. *
  2549. * @private
  2550. * @param {string|Array} type
  2551. * The type value to test.
  2552. *
  2553. * @return {boolean}
  2554. * Whether or not the type is a valid event type.
  2555. */
  2556. const isValidEventType = type =>
  2557. // The regex here verifies that the `type` contains at least one non-
  2558. // whitespace character.
  2559. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2560. /**
  2561. * Validates a value to determine if it is a valid event target. Throws if not.
  2562. *
  2563. * @private
  2564. * @throws {Error}
  2565. * If the target does not appear to be a valid event target.
  2566. *
  2567. * @param {Object} target
  2568. * The object to test.
  2569. *
  2570. * @param {Object} obj
  2571. * The evented object we are validating for
  2572. *
  2573. * @param {string} fnName
  2574. * The name of the evented mixin function that called this.
  2575. */
  2576. const validateTarget = (target, obj, fnName) => {
  2577. if (!target || !target.nodeName && !isEvented(target)) {
  2578. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2579. }
  2580. };
  2581. /**
  2582. * Validates a value to determine if it is a valid event target. Throws if not.
  2583. *
  2584. * @private
  2585. * @throws {Error}
  2586. * If the type does not appear to be a valid event type.
  2587. *
  2588. * @param {string|Array} type
  2589. * The type to test.
  2590. *
  2591. * @param {Object} obj
  2592. * The evented object we are validating for
  2593. *
  2594. * @param {string} fnName
  2595. * The name of the evented mixin function that called this.
  2596. */
  2597. const validateEventType = (type, obj, fnName) => {
  2598. if (!isValidEventType(type)) {
  2599. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2600. }
  2601. };
  2602. /**
  2603. * Validates a value to determine if it is a valid listener. Throws if not.
  2604. *
  2605. * @private
  2606. * @throws {Error}
  2607. * If the listener is not a function.
  2608. *
  2609. * @param {Function} listener
  2610. * The listener to test.
  2611. *
  2612. * @param {Object} obj
  2613. * The evented object we are validating for
  2614. *
  2615. * @param {string} fnName
  2616. * The name of the evented mixin function that called this.
  2617. */
  2618. const validateListener = (listener, obj, fnName) => {
  2619. if (typeof listener !== 'function') {
  2620. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2621. }
  2622. };
  2623. /**
  2624. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2625. * normalizes them into an object.
  2626. *
  2627. * @private
  2628. * @param {Object} self
  2629. * The evented object on which `on()` or `one()` was called. This
  2630. * object will be bound as the `this` value for the listener.
  2631. *
  2632. * @param {Array} args
  2633. * An array of arguments passed to `on()` or `one()`.
  2634. *
  2635. * @param {string} fnName
  2636. * The name of the evented mixin function that called this.
  2637. *
  2638. * @return {Object}
  2639. * An object containing useful values for `on()` or `one()` calls.
  2640. */
  2641. const normalizeListenArgs = (self, args, fnName) => {
  2642. // If the number of arguments is less than 3, the target is always the
  2643. // evented object itself.
  2644. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2645. let target;
  2646. let type;
  2647. let listener;
  2648. if (isTargetingSelf) {
  2649. target = self.eventBusEl_;
  2650. // Deal with cases where we got 3 arguments, but we are still listening to
  2651. // the evented object itself.
  2652. if (args.length >= 3) {
  2653. args.shift();
  2654. }
  2655. [type, listener] = args;
  2656. } else {
  2657. [target, type, listener] = args;
  2658. }
  2659. validateTarget(target, self, fnName);
  2660. validateEventType(type, self, fnName);
  2661. validateListener(listener, self, fnName);
  2662. listener = bind_(self, listener);
  2663. return {
  2664. isTargetingSelf,
  2665. target,
  2666. type,
  2667. listener
  2668. };
  2669. };
  2670. /**
  2671. * Adds the listener to the event type(s) on the target, normalizing for
  2672. * the type of target.
  2673. *
  2674. * @private
  2675. * @param {Element|Object} target
  2676. * A DOM node or evented object.
  2677. *
  2678. * @param {string} method
  2679. * The event binding method to use ("on" or "one").
  2680. *
  2681. * @param {string|Array} type
  2682. * One or more event type(s).
  2683. *
  2684. * @param {Function} listener
  2685. * A listener function.
  2686. */
  2687. const listen = (target, method, type, listener) => {
  2688. validateTarget(target, target, method);
  2689. if (target.nodeName) {
  2690. Events[method](target, type, listener);
  2691. } else {
  2692. target[method](type, listener);
  2693. }
  2694. };
  2695. /**
  2696. * Contains methods that provide event capabilities to an object which is passed
  2697. * to {@link module:evented|evented}.
  2698. *
  2699. * @mixin EventedMixin
  2700. */
  2701. const EventedMixin = {
  2702. /**
  2703. * Add a listener to an event (or events) on this object or another evented
  2704. * object.
  2705. *
  2706. * @param {string|Array|Element|Object} targetOrType
  2707. * If this is a string or array, it represents the event type(s)
  2708. * that will trigger the listener.
  2709. *
  2710. * Another evented object can be passed here instead, which will
  2711. * cause the listener to listen for events on _that_ object.
  2712. *
  2713. * In either case, the listener's `this` value will be bound to
  2714. * this object.
  2715. *
  2716. * @param {string|Array|Function} typeOrListener
  2717. * If the first argument was a string or array, this should be the
  2718. * listener function. Otherwise, this is a string or array of event
  2719. * type(s).
  2720. *
  2721. * @param {Function} [listener]
  2722. * If the first argument was another evented object, this will be
  2723. * the listener function.
  2724. */
  2725. on(...args) {
  2726. const {
  2727. isTargetingSelf,
  2728. target,
  2729. type,
  2730. listener
  2731. } = normalizeListenArgs(this, args, 'on');
  2732. listen(target, 'on', type, listener);
  2733. // If this object is listening to another evented object.
  2734. if (!isTargetingSelf) {
  2735. // If this object is disposed, remove the listener.
  2736. const removeListenerOnDispose = () => this.off(target, type, listener);
  2737. // Use the same function ID as the listener so we can remove it later it
  2738. // using the ID of the original listener.
  2739. removeListenerOnDispose.guid = listener.guid;
  2740. // Add a listener to the target's dispose event as well. This ensures
  2741. // that if the target is disposed BEFORE this object, we remove the
  2742. // removal listener that was just added. Otherwise, we create a memory leak.
  2743. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2744. // Use the same function ID as the listener so we can remove it later
  2745. // it using the ID of the original listener.
  2746. removeRemoverOnTargetDispose.guid = listener.guid;
  2747. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2748. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2749. }
  2750. },
  2751. /**
  2752. * Add a listener to an event (or events) on this object or another evented
  2753. * object. The listener will be called once per event and then removed.
  2754. *
  2755. * @param {string|Array|Element|Object} targetOrType
  2756. * If this is a string or array, it represents the event type(s)
  2757. * that will trigger the listener.
  2758. *
  2759. * Another evented object can be passed here instead, which will
  2760. * cause the listener to listen for events on _that_ object.
  2761. *
  2762. * In either case, the listener's `this` value will be bound to
  2763. * this object.
  2764. *
  2765. * @param {string|Array|Function} typeOrListener
  2766. * If the first argument was a string or array, this should be the
  2767. * listener function. Otherwise, this is a string or array of event
  2768. * type(s).
  2769. *
  2770. * @param {Function} [listener]
  2771. * If the first argument was another evented object, this will be
  2772. * the listener function.
  2773. */
  2774. one(...args) {
  2775. const {
  2776. isTargetingSelf,
  2777. target,
  2778. type,
  2779. listener
  2780. } = normalizeListenArgs(this, args, 'one');
  2781. // Targeting this evented object.
  2782. if (isTargetingSelf) {
  2783. listen(target, 'one', type, listener);
  2784. // Targeting another evented object.
  2785. } else {
  2786. // TODO: This wrapper is incorrect! It should only
  2787. // remove the wrapper for the event type that called it.
  2788. // Instead all listeners are removed on the first trigger!
  2789. // see https://github.com/videojs/video.js/issues/5962
  2790. const wrapper = (...largs) => {
  2791. this.off(target, type, wrapper);
  2792. listener.apply(null, largs);
  2793. };
  2794. // Use the same function ID as the listener so we can remove it later
  2795. // it using the ID of the original listener.
  2796. wrapper.guid = listener.guid;
  2797. listen(target, 'one', type, wrapper);
  2798. }
  2799. },
  2800. /**
  2801. * Add a listener to an event (or events) on this object or another evented
  2802. * object. The listener will only be called once for the first event that is triggered
  2803. * then removed.
  2804. *
  2805. * @param {string|Array|Element|Object} targetOrType
  2806. * If this is a string or array, it represents the event type(s)
  2807. * that will trigger the listener.
  2808. *
  2809. * Another evented object can be passed here instead, which will
  2810. * cause the listener to listen for events on _that_ object.
  2811. *
  2812. * In either case, the listener's `this` value will be bound to
  2813. * this object.
  2814. *
  2815. * @param {string|Array|Function} typeOrListener
  2816. * If the first argument was a string or array, this should be the
  2817. * listener function. Otherwise, this is a string or array of event
  2818. * type(s).
  2819. *
  2820. * @param {Function} [listener]
  2821. * If the first argument was another evented object, this will be
  2822. * the listener function.
  2823. */
  2824. any(...args) {
  2825. const {
  2826. isTargetingSelf,
  2827. target,
  2828. type,
  2829. listener
  2830. } = normalizeListenArgs(this, args, 'any');
  2831. // Targeting this evented object.
  2832. if (isTargetingSelf) {
  2833. listen(target, 'any', type, listener);
  2834. // Targeting another evented object.
  2835. } else {
  2836. const wrapper = (...largs) => {
  2837. this.off(target, type, wrapper);
  2838. listener.apply(null, largs);
  2839. };
  2840. // Use the same function ID as the listener so we can remove it later
  2841. // it using the ID of the original listener.
  2842. wrapper.guid = listener.guid;
  2843. listen(target, 'any', type, wrapper);
  2844. }
  2845. },
  2846. /**
  2847. * Removes listener(s) from event(s) on an evented object.
  2848. *
  2849. * @param {string|Array|Element|Object} [targetOrType]
  2850. * If this is a string or array, it represents the event type(s).
  2851. *
  2852. * Another evented object can be passed here instead, in which case
  2853. * ALL 3 arguments are _required_.
  2854. *
  2855. * @param {string|Array|Function} [typeOrListener]
  2856. * If the first argument was a string or array, this may be the
  2857. * listener function. Otherwise, this is a string or array of event
  2858. * type(s).
  2859. *
  2860. * @param {Function} [listener]
  2861. * If the first argument was another evented object, this will be
  2862. * the listener function; otherwise, _all_ listeners bound to the
  2863. * event type(s) will be removed.
  2864. */
  2865. off(targetOrType, typeOrListener, listener) {
  2866. // Targeting this evented object.
  2867. if (!targetOrType || isValidEventType(targetOrType)) {
  2868. off(this.eventBusEl_, targetOrType, typeOrListener);
  2869. // Targeting another evented object.
  2870. } else {
  2871. const target = targetOrType;
  2872. const type = typeOrListener;
  2873. // Fail fast and in a meaningful way!
  2874. validateTarget(target, this, 'off');
  2875. validateEventType(type, this, 'off');
  2876. validateListener(listener, this, 'off');
  2877. // Ensure there's at least a guid, even if the function hasn't been used
  2878. listener = bind_(this, listener);
  2879. // Remove the dispose listener on this evented object, which was given
  2880. // the same guid as the event listener in on().
  2881. this.off('dispose', listener);
  2882. if (target.nodeName) {
  2883. off(target, type, listener);
  2884. off(target, 'dispose', listener);
  2885. } else if (isEvented(target)) {
  2886. target.off(type, listener);
  2887. target.off('dispose', listener);
  2888. }
  2889. }
  2890. },
  2891. /**
  2892. * Fire an event on this evented object, causing its listeners to be called.
  2893. *
  2894. * @param {string|Object} event
  2895. * An event type or an object with a type property.
  2896. *
  2897. * @param {Object} [hash]
  2898. * An additional object to pass along to listeners.
  2899. *
  2900. * @return {boolean}
  2901. * Whether or not the default behavior was prevented.
  2902. */
  2903. trigger(event, hash) {
  2904. validateTarget(this.eventBusEl_, this, 'trigger');
  2905. const type = event && typeof event !== 'string' ? event.type : event;
  2906. if (!isValidEventType(type)) {
  2907. 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.');
  2908. }
  2909. return trigger(this.eventBusEl_, event, hash);
  2910. }
  2911. };
  2912. /**
  2913. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2914. *
  2915. * @param {Object} target
  2916. * The object to which to add event methods.
  2917. *
  2918. * @param {Object} [options={}]
  2919. * Options for customizing the mixin behavior.
  2920. *
  2921. * @param {string} [options.eventBusKey]
  2922. * By default, adds a `eventBusEl_` DOM element to the target object,
  2923. * which is used as an event bus. If the target object already has a
  2924. * DOM element that should be used, pass its key here.
  2925. *
  2926. * @return {Object}
  2927. * The target object.
  2928. */
  2929. function evented(target, options = {}) {
  2930. const {
  2931. eventBusKey
  2932. } = options;
  2933. // Set or create the eventBusEl_.
  2934. if (eventBusKey) {
  2935. if (!target[eventBusKey].nodeName) {
  2936. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2937. }
  2938. target.eventBusEl_ = target[eventBusKey];
  2939. } else {
  2940. target.eventBusEl_ = createEl('span', {
  2941. className: 'vjs-event-bus'
  2942. });
  2943. }
  2944. Object.assign(target, EventedMixin);
  2945. if (target.eventedCallbacks) {
  2946. target.eventedCallbacks.forEach(callback => {
  2947. callback();
  2948. });
  2949. }
  2950. // When any evented object is disposed, it removes all its listeners.
  2951. target.on('dispose', () => {
  2952. target.off();
  2953. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2954. if (val && DomData.has(val)) {
  2955. DomData.delete(val);
  2956. }
  2957. });
  2958. window.setTimeout(() => {
  2959. target.eventBusEl_ = null;
  2960. }, 0);
  2961. });
  2962. return target;
  2963. }
  2964. /**
  2965. * @file mixins/stateful.js
  2966. * @module stateful
  2967. */
  2968. /**
  2969. * Contains methods that provide statefulness to an object which is passed
  2970. * to {@link module:stateful}.
  2971. *
  2972. * @mixin StatefulMixin
  2973. */
  2974. const StatefulMixin = {
  2975. /**
  2976. * A hash containing arbitrary keys and values representing the state of
  2977. * the object.
  2978. *
  2979. * @type {Object}
  2980. */
  2981. state: {},
  2982. /**
  2983. * Set the state of an object by mutating its
  2984. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2985. *
  2986. * @fires module:stateful~StatefulMixin#statechanged
  2987. * @param {Object|Function} stateUpdates
  2988. * A new set of properties to shallow-merge into the plugin state.
  2989. * Can be a plain object or a function returning a plain object.
  2990. *
  2991. * @return {Object|undefined}
  2992. * An object containing changes that occurred. If no changes
  2993. * occurred, returns `undefined`.
  2994. */
  2995. setState(stateUpdates) {
  2996. // Support providing the `stateUpdates` state as a function.
  2997. if (typeof stateUpdates === 'function') {
  2998. stateUpdates = stateUpdates();
  2999. }
  3000. let changes;
  3001. each(stateUpdates, (value, key) => {
  3002. // Record the change if the value is different from what's in the
  3003. // current state.
  3004. if (this.state[key] !== value) {
  3005. changes = changes || {};
  3006. changes[key] = {
  3007. from: this.state[key],
  3008. to: value
  3009. };
  3010. }
  3011. this.state[key] = value;
  3012. });
  3013. // Only trigger "statechange" if there were changes AND we have a trigger
  3014. // function. This allows us to not require that the target object be an
  3015. // evented object.
  3016. if (changes && isEvented(this)) {
  3017. /**
  3018. * An event triggered on an object that is both
  3019. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3020. * indicating that its state has changed.
  3021. *
  3022. * @event module:stateful~StatefulMixin#statechanged
  3023. * @type {Object}
  3024. * @property {Object} changes
  3025. * A hash containing the properties that were changed and
  3026. * the values they were changed `from` and `to`.
  3027. */
  3028. this.trigger({
  3029. changes,
  3030. type: 'statechanged'
  3031. });
  3032. }
  3033. return changes;
  3034. }
  3035. };
  3036. /**
  3037. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3038. * object.
  3039. *
  3040. * If the target object is {@link module:evented|evented} and has a
  3041. * `handleStateChanged` method, that method will be automatically bound to the
  3042. * `statechanged` event on itself.
  3043. *
  3044. * @param {Object} target
  3045. * The object to be made stateful.
  3046. *
  3047. * @param {Object} [defaultState]
  3048. * A default set of properties to populate the newly-stateful object's
  3049. * `state` property.
  3050. *
  3051. * @return {Object}
  3052. * Returns the `target`.
  3053. */
  3054. function stateful(target, defaultState) {
  3055. Object.assign(target, StatefulMixin);
  3056. // This happens after the mixing-in because we need to replace the `state`
  3057. // added in that step.
  3058. target.state = Object.assign({}, target.state, defaultState);
  3059. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3060. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3061. target.on('statechanged', target.handleStateChanged);
  3062. }
  3063. return target;
  3064. }
  3065. /**
  3066. * @file str.js
  3067. * @module to-lower-case
  3068. */
  3069. /**
  3070. * Lowercase the first letter of a string.
  3071. *
  3072. * @param {string} string
  3073. * String to be lowercased
  3074. *
  3075. * @return {string}
  3076. * The string with a lowercased first letter
  3077. */
  3078. const toLowerCase = function (string) {
  3079. if (typeof string !== 'string') {
  3080. return string;
  3081. }
  3082. return string.replace(/./, w => w.toLowerCase());
  3083. };
  3084. /**
  3085. * Uppercase the first letter of a string.
  3086. *
  3087. * @param {string} string
  3088. * String to be uppercased
  3089. *
  3090. * @return {string}
  3091. * The string with an uppercased first letter
  3092. */
  3093. const toTitleCase = function (string) {
  3094. if (typeof string !== 'string') {
  3095. return string;
  3096. }
  3097. return string.replace(/./, w => w.toUpperCase());
  3098. };
  3099. /**
  3100. * Compares the TitleCase versions of the two strings for equality.
  3101. *
  3102. * @param {string} str1
  3103. * The first string to compare
  3104. *
  3105. * @param {string} str2
  3106. * The second string to compare
  3107. *
  3108. * @return {boolean}
  3109. * Whether the TitleCase versions of the strings are equal
  3110. */
  3111. const titleCaseEquals = function (str1, str2) {
  3112. return toTitleCase(str1) === toTitleCase(str2);
  3113. };
  3114. var Str = /*#__PURE__*/Object.freeze({
  3115. __proto__: null,
  3116. toLowerCase: toLowerCase,
  3117. toTitleCase: toTitleCase,
  3118. titleCaseEquals: titleCaseEquals
  3119. });
  3120. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3121. function unwrapExports (x) {
  3122. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  3123. }
  3124. function createCommonjsModule(fn, module) {
  3125. return module = { exports: {} }, fn(module, module.exports), module.exports;
  3126. }
  3127. var keycode = createCommonjsModule(function (module, exports) {
  3128. // Source: http://jsfiddle.net/vWx8V/
  3129. // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes
  3130. /**
  3131. * Conenience method returns corresponding value for given keyName or keyCode.
  3132. *
  3133. * @param {Mixed} keyCode {Number} or keyName {String}
  3134. * @return {Mixed}
  3135. * @api public
  3136. */
  3137. function keyCode(searchInput) {
  3138. // Keyboard Events
  3139. if (searchInput && 'object' === typeof searchInput) {
  3140. var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode;
  3141. if (hasKeyCode) searchInput = hasKeyCode;
  3142. }
  3143. // Numbers
  3144. if ('number' === typeof searchInput) return names[searchInput];
  3145. // Everything else (cast to string)
  3146. var search = String(searchInput);
  3147. // check codes
  3148. var foundNamedKey = codes[search.toLowerCase()];
  3149. if (foundNamedKey) return foundNamedKey;
  3150. // check aliases
  3151. var foundNamedKey = aliases[search.toLowerCase()];
  3152. if (foundNamedKey) return foundNamedKey;
  3153. // weird character?
  3154. if (search.length === 1) return search.charCodeAt(0);
  3155. return undefined;
  3156. }
  3157. /**
  3158. * Compares a keyboard event with a given keyCode or keyName.
  3159. *
  3160. * @param {Event} event Keyboard event that should be tested
  3161. * @param {Mixed} keyCode {Number} or keyName {String}
  3162. * @return {Boolean}
  3163. * @api public
  3164. */
  3165. keyCode.isEventKey = function isEventKey(event, nameOrCode) {
  3166. if (event && 'object' === typeof event) {
  3167. var keyCode = event.which || event.keyCode || event.charCode;
  3168. if (keyCode === null || keyCode === undefined) {
  3169. return false;
  3170. }
  3171. if (typeof nameOrCode === 'string') {
  3172. // check codes
  3173. var foundNamedKey = codes[nameOrCode.toLowerCase()];
  3174. if (foundNamedKey) {
  3175. return foundNamedKey === keyCode;
  3176. }
  3177. // check aliases
  3178. var foundNamedKey = aliases[nameOrCode.toLowerCase()];
  3179. if (foundNamedKey) {
  3180. return foundNamedKey === keyCode;
  3181. }
  3182. } else if (typeof nameOrCode === 'number') {
  3183. return nameOrCode === keyCode;
  3184. }
  3185. return false;
  3186. }
  3187. };
  3188. exports = module.exports = keyCode;
  3189. /**
  3190. * Get by name
  3191. *
  3192. * exports.code['enter'] // => 13
  3193. */
  3194. var codes = exports.code = exports.codes = {
  3195. 'backspace': 8,
  3196. 'tab': 9,
  3197. 'enter': 13,
  3198. 'shift': 16,
  3199. 'ctrl': 17,
  3200. 'alt': 18,
  3201. 'pause/break': 19,
  3202. 'caps lock': 20,
  3203. 'esc': 27,
  3204. 'space': 32,
  3205. 'page up': 33,
  3206. 'page down': 34,
  3207. 'end': 35,
  3208. 'home': 36,
  3209. 'left': 37,
  3210. 'up': 38,
  3211. 'right': 39,
  3212. 'down': 40,
  3213. 'insert': 45,
  3214. 'delete': 46,
  3215. 'command': 91,
  3216. 'left command': 91,
  3217. 'right command': 93,
  3218. 'numpad *': 106,
  3219. 'numpad +': 107,
  3220. 'numpad -': 109,
  3221. 'numpad .': 110,
  3222. 'numpad /': 111,
  3223. 'num lock': 144,
  3224. 'scroll lock': 145,
  3225. 'my computer': 182,
  3226. 'my calculator': 183,
  3227. ';': 186,
  3228. '=': 187,
  3229. ',': 188,
  3230. '-': 189,
  3231. '.': 190,
  3232. '/': 191,
  3233. '`': 192,
  3234. '[': 219,
  3235. '\\': 220,
  3236. ']': 221,
  3237. "'": 222
  3238. };
  3239. // Helper aliases
  3240. var aliases = exports.aliases = {
  3241. 'windows': 91,
  3242. '⇧': 16,
  3243. '⌥': 18,
  3244. '⌃': 17,
  3245. '⌘': 91,
  3246. 'ctl': 17,
  3247. 'control': 17,
  3248. 'option': 18,
  3249. 'pause': 19,
  3250. 'break': 19,
  3251. 'caps': 20,
  3252. 'return': 13,
  3253. 'escape': 27,
  3254. 'spc': 32,
  3255. 'spacebar': 32,
  3256. 'pgup': 33,
  3257. 'pgdn': 34,
  3258. 'ins': 45,
  3259. 'del': 46,
  3260. 'cmd': 91
  3261. };
  3262. /*!
  3263. * Programatically add the following
  3264. */
  3265. // lower case chars
  3266. for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32;
  3267. // numbers
  3268. for (var i = 48; i < 58; i++) codes[i - 48] = i;
  3269. // function keys
  3270. for (i = 1; i < 13; i++) codes['f' + i] = i + 111;
  3271. // numpad keys
  3272. for (i = 0; i < 10; i++) codes['numpad ' + i] = i + 96;
  3273. /**
  3274. * Get by code
  3275. *
  3276. * exports.name[13] // => 'Enter'
  3277. */
  3278. var names = exports.names = exports.title = {}; // title for backward compat
  3279. // Create reverse mapping
  3280. for (i in codes) names[codes[i]] = i;
  3281. // Add aliases
  3282. for (var alias in aliases) {
  3283. codes[alias] = aliases[alias];
  3284. }
  3285. });
  3286. keycode.code;
  3287. keycode.codes;
  3288. keycode.aliases;
  3289. keycode.names;
  3290. keycode.title;
  3291. /**
  3292. * Player Component - Base class for all UI objects
  3293. *
  3294. * @file component.js
  3295. */
  3296. /**
  3297. * Base class for all UI Components.
  3298. * Components are UI objects which represent both a javascript object and an element
  3299. * in the DOM. They can be children of other components, and can have
  3300. * children themselves.
  3301. *
  3302. * Components can also use methods from {@link EventTarget}
  3303. */
  3304. class Component {
  3305. /**
  3306. * A callback that is called when a component is ready. Does not have any
  3307. * parameters and any callback value will be ignored.
  3308. *
  3309. * @callback ReadyCallback
  3310. * @this Component
  3311. */
  3312. /**
  3313. * Creates an instance of this class.
  3314. *
  3315. * @param { import('./player').default } player
  3316. * The `Player` that this class should be attached to.
  3317. *
  3318. * @param {Object} [options]
  3319. * The key/value store of component options.
  3320. *
  3321. * @param {Object[]} [options.children]
  3322. * An array of children objects to initialize this component with. Children objects have
  3323. * a name property that will be used if more than one component of the same type needs to be
  3324. * added.
  3325. *
  3326. * @param {string} [options.className]
  3327. * A class or space separated list of classes to add the component
  3328. *
  3329. * @param {ReadyCallback} [ready]
  3330. * Function that gets called when the `Component` is ready.
  3331. */
  3332. constructor(player, options, ready) {
  3333. // The component might be the player itself and we can't pass `this` to super
  3334. if (!player && this.play) {
  3335. this.player_ = player = this; // eslint-disable-line
  3336. } else {
  3337. this.player_ = player;
  3338. }
  3339. this.isDisposed_ = false;
  3340. // Hold the reference to the parent component via `addChild` method
  3341. this.parentComponent_ = null;
  3342. // Make a copy of prototype.options_ to protect against overriding defaults
  3343. this.options_ = merge({}, this.options_);
  3344. // Updated options with supplied options
  3345. options = this.options_ = merge(this.options_, options);
  3346. // Get ID from options or options element if one is supplied
  3347. this.id_ = options.id || options.el && options.el.id;
  3348. // If there was no ID from the options, generate one
  3349. if (!this.id_) {
  3350. // Don't require the player ID function in the case of mock players
  3351. const id = player && player.id && player.id() || 'no_player';
  3352. this.id_ = `${id}_component_${newGUID()}`;
  3353. }
  3354. this.name_ = options.name || null;
  3355. // Create element if one wasn't provided in options
  3356. if (options.el) {
  3357. this.el_ = options.el;
  3358. } else if (options.createEl !== false) {
  3359. this.el_ = this.createEl();
  3360. }
  3361. if (options.className && this.el_) {
  3362. options.className.split(' ').forEach(c => this.addClass(c));
  3363. }
  3364. // Remove the placeholder event methods. If the component is evented, the
  3365. // real methods are added next
  3366. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3367. this[fn] = undefined;
  3368. });
  3369. // if evented is anything except false, we want to mixin in evented
  3370. if (options.evented !== false) {
  3371. // Make this an evented object and use `el_`, if available, as its event bus
  3372. evented(this, {
  3373. eventBusKey: this.el_ ? 'el_' : null
  3374. });
  3375. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3376. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3377. }
  3378. stateful(this, this.constructor.defaultState);
  3379. this.children_ = [];
  3380. this.childIndex_ = {};
  3381. this.childNameIndex_ = {};
  3382. this.setTimeoutIds_ = new Set();
  3383. this.setIntervalIds_ = new Set();
  3384. this.rafIds_ = new Set();
  3385. this.namedRafs_ = new Map();
  3386. this.clearingTimersOnDispose_ = false;
  3387. // Add any child components in options
  3388. if (options.initChildren !== false) {
  3389. this.initChildren();
  3390. }
  3391. // Don't want to trigger ready here or it will go before init is actually
  3392. // finished for all children that run this constructor
  3393. this.ready(ready);
  3394. if (options.reportTouchActivity !== false) {
  3395. this.enableTouchActivity();
  3396. }
  3397. }
  3398. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3399. // They are replaced or removed in the constructor
  3400. /**
  3401. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3402. * function that will get called when an event with a certain name gets triggered.
  3403. *
  3404. * @param {string|string[]} type
  3405. * An event name or an array of event names.
  3406. *
  3407. * @param {Function} fn
  3408. * The function to call with `EventTarget`s
  3409. */
  3410. on(type, fn) {}
  3411. /**
  3412. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3413. * This makes it so that the `event listener` will no longer get called when the
  3414. * named event happens.
  3415. *
  3416. * @param {string|string[]} type
  3417. * An event name or an array of event names.
  3418. *
  3419. * @param {Function} fn
  3420. * The function to remove.
  3421. */
  3422. off(type, fn) {}
  3423. /**
  3424. * This function will add an `event listener` that gets triggered only once. After the
  3425. * first trigger it will get removed. This is like adding an `event listener`
  3426. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3427. *
  3428. * @param {string|string[]} type
  3429. * An event name or an array of event names.
  3430. *
  3431. * @param {Function} fn
  3432. * The function to be called once for each event name.
  3433. */
  3434. one(type, fn) {}
  3435. /**
  3436. * This function will add an `event listener` that gets triggered only once and is
  3437. * removed from all events. This is like adding an array of `event listener`s
  3438. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3439. * first time it is triggered.
  3440. *
  3441. * @param {string|string[]} type
  3442. * An event name or an array of event names.
  3443. *
  3444. * @param {Function} fn
  3445. * The function to be called once for each event name.
  3446. */
  3447. any(type, fn) {}
  3448. /**
  3449. * This function causes an event to happen. This will then cause any `event listeners`
  3450. * that are waiting for that event, to get called. If there are no `event listeners`
  3451. * for an event then nothing will happen.
  3452. *
  3453. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3454. * Trigger will also call the `on` + `uppercaseEventName` function.
  3455. *
  3456. * Example:
  3457. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3458. * `onClick` if it exists.
  3459. *
  3460. * @param {string|Event|Object} event
  3461. * The name of the event, an `Event`, or an object with a key of type set to
  3462. * an event name.
  3463. */
  3464. trigger(event) {}
  3465. /**
  3466. * Dispose of the `Component` and all child components.
  3467. *
  3468. * @fires Component#dispose
  3469. *
  3470. * @param {Object} options
  3471. * @param {Element} options.originalEl element with which to replace player element
  3472. */
  3473. dispose(options = {}) {
  3474. // Bail out if the component has already been disposed.
  3475. if (this.isDisposed_) {
  3476. return;
  3477. }
  3478. if (this.readyQueue_) {
  3479. this.readyQueue_.length = 0;
  3480. }
  3481. /**
  3482. * Triggered when a `Component` is disposed.
  3483. *
  3484. * @event Component#dispose
  3485. * @type {Event}
  3486. *
  3487. * @property {boolean} [bubbles=false]
  3488. * set to false so that the dispose event does not
  3489. * bubble up
  3490. */
  3491. this.trigger({
  3492. type: 'dispose',
  3493. bubbles: false
  3494. });
  3495. this.isDisposed_ = true;
  3496. // Dispose all children.
  3497. if (this.children_) {
  3498. for (let i = this.children_.length - 1; i >= 0; i--) {
  3499. if (this.children_[i].dispose) {
  3500. this.children_[i].dispose();
  3501. }
  3502. }
  3503. }
  3504. // Delete child references
  3505. this.children_ = null;
  3506. this.childIndex_ = null;
  3507. this.childNameIndex_ = null;
  3508. this.parentComponent_ = null;
  3509. if (this.el_) {
  3510. // Remove element from DOM
  3511. if (this.el_.parentNode) {
  3512. if (options.restoreEl) {
  3513. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3514. } else {
  3515. this.el_.parentNode.removeChild(this.el_);
  3516. }
  3517. }
  3518. this.el_ = null;
  3519. }
  3520. // remove reference to the player after disposing of the element
  3521. this.player_ = null;
  3522. }
  3523. /**
  3524. * Determine whether or not this component has been disposed.
  3525. *
  3526. * @return {boolean}
  3527. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3528. */
  3529. isDisposed() {
  3530. return Boolean(this.isDisposed_);
  3531. }
  3532. /**
  3533. * Return the {@link Player} that the `Component` has attached to.
  3534. *
  3535. * @return { import('./player').default }
  3536. * The player that this `Component` has attached to.
  3537. */
  3538. player() {
  3539. return this.player_;
  3540. }
  3541. /**
  3542. * Deep merge of options objects with new options.
  3543. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3544. * The two properties get merged using {@link module:obj.merge}
  3545. *
  3546. * @param {Object} obj
  3547. * The object that contains new options.
  3548. *
  3549. * @return {Object}
  3550. * A new object of `this.options_` and `obj` merged together.
  3551. */
  3552. options(obj) {
  3553. if (!obj) {
  3554. return this.options_;
  3555. }
  3556. this.options_ = merge(this.options_, obj);
  3557. return this.options_;
  3558. }
  3559. /**
  3560. * Get the `Component`s DOM element
  3561. *
  3562. * @return {Element}
  3563. * The DOM element for this `Component`.
  3564. */
  3565. el() {
  3566. return this.el_;
  3567. }
  3568. /**
  3569. * Create the `Component`s DOM element.
  3570. *
  3571. * @param {string} [tagName]
  3572. * Element's DOM node type. e.g. 'div'
  3573. *
  3574. * @param {Object} [properties]
  3575. * An object of properties that should be set.
  3576. *
  3577. * @param {Object} [attributes]
  3578. * An object of attributes that should be set.
  3579. *
  3580. * @return {Element}
  3581. * The element that gets created.
  3582. */
  3583. createEl(tagName, properties, attributes) {
  3584. return createEl(tagName, properties, attributes);
  3585. }
  3586. /**
  3587. * Localize a string given the string in english.
  3588. *
  3589. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3590. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3591. *
  3592. * If a `defaultValue` is provided, it'll use that over `string`,
  3593. * if a value isn't found in provided language files.
  3594. * This is useful if you want to have a descriptive key for token replacement
  3595. * but have a succinct localized string and not require `en.json` to be included.
  3596. *
  3597. * Currently, it is used for the progress bar timing.
  3598. * ```js
  3599. * {
  3600. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3601. * }
  3602. * ```
  3603. * It is then used like so:
  3604. * ```js
  3605. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3606. * [this.player_.currentTime(), this.player_.duration()],
  3607. * '{1} of {2}');
  3608. * ```
  3609. *
  3610. * Which outputs something like: `01:23 of 24:56`.
  3611. *
  3612. *
  3613. * @param {string} string
  3614. * The string to localize and the key to lookup in the language files.
  3615. * @param {string[]} [tokens]
  3616. * If the current item has token replacements, provide the tokens here.
  3617. * @param {string} [defaultValue]
  3618. * Defaults to `string`. Can be a default value to use for token replacement
  3619. * if the lookup key is needed to be separate.
  3620. *
  3621. * @return {string}
  3622. * The localized string or if no localization exists the english string.
  3623. */
  3624. localize(string, tokens, defaultValue = string) {
  3625. const code = this.player_.language && this.player_.language();
  3626. const languages = this.player_.languages && this.player_.languages();
  3627. const language = languages && languages[code];
  3628. const primaryCode = code && code.split('-')[0];
  3629. const primaryLang = languages && languages[primaryCode];
  3630. let localizedString = defaultValue;
  3631. if (language && language[string]) {
  3632. localizedString = language[string];
  3633. } else if (primaryLang && primaryLang[string]) {
  3634. localizedString = primaryLang[string];
  3635. }
  3636. if (tokens) {
  3637. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3638. const value = tokens[index - 1];
  3639. let ret = value;
  3640. if (typeof value === 'undefined') {
  3641. ret = match;
  3642. }
  3643. return ret;
  3644. });
  3645. }
  3646. return localizedString;
  3647. }
  3648. /**
  3649. * Handles language change for the player in components. Should be overridden by sub-components.
  3650. *
  3651. * @abstract
  3652. */
  3653. handleLanguagechange() {}
  3654. /**
  3655. * Return the `Component`s DOM element. This is where children get inserted.
  3656. * This will usually be the the same as the element returned in {@link Component#el}.
  3657. *
  3658. * @return {Element}
  3659. * The content element for this `Component`.
  3660. */
  3661. contentEl() {
  3662. return this.contentEl_ || this.el_;
  3663. }
  3664. /**
  3665. * Get this `Component`s ID
  3666. *
  3667. * @return {string}
  3668. * The id of this `Component`
  3669. */
  3670. id() {
  3671. return this.id_;
  3672. }
  3673. /**
  3674. * Get the `Component`s name. The name gets used to reference the `Component`
  3675. * and is set during registration.
  3676. *
  3677. * @return {string}
  3678. * The name of this `Component`.
  3679. */
  3680. name() {
  3681. return this.name_;
  3682. }
  3683. /**
  3684. * Get an array of all child components
  3685. *
  3686. * @return {Array}
  3687. * The children
  3688. */
  3689. children() {
  3690. return this.children_;
  3691. }
  3692. /**
  3693. * Returns the child `Component` with the given `id`.
  3694. *
  3695. * @param {string} id
  3696. * The id of the child `Component` to get.
  3697. *
  3698. * @return {Component|undefined}
  3699. * The child `Component` with the given `id` or undefined.
  3700. */
  3701. getChildById(id) {
  3702. return this.childIndex_[id];
  3703. }
  3704. /**
  3705. * Returns the child `Component` with the given `name`.
  3706. *
  3707. * @param {string} name
  3708. * The name of the child `Component` to get.
  3709. *
  3710. * @return {Component|undefined}
  3711. * The child `Component` with the given `name` or undefined.
  3712. */
  3713. getChild(name) {
  3714. if (!name) {
  3715. return;
  3716. }
  3717. return this.childNameIndex_[name];
  3718. }
  3719. /**
  3720. * Returns the descendant `Component` following the givent
  3721. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3722. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3723. * component and 'baz' on the 'bar' component and return undefined
  3724. * if any of those don't exist.
  3725. *
  3726. * @param {...string[]|...string} names
  3727. * The name of the child `Component` to get.
  3728. *
  3729. * @return {Component|undefined}
  3730. * The descendant `Component` following the given descendant
  3731. * `names` or undefined.
  3732. */
  3733. getDescendant(...names) {
  3734. // flatten array argument into the main array
  3735. names = names.reduce((acc, n) => acc.concat(n), []);
  3736. let currentChild = this;
  3737. for (let i = 0; i < names.length; i++) {
  3738. currentChild = currentChild.getChild(names[i]);
  3739. if (!currentChild || !currentChild.getChild) {
  3740. return;
  3741. }
  3742. }
  3743. return currentChild;
  3744. }
  3745. /**
  3746. * Add a child `Component` inside the current `Component`.
  3747. *
  3748. *
  3749. * @param {string|Component} child
  3750. * The name or instance of a child to add.
  3751. *
  3752. * @param {Object} [options={}]
  3753. * The key/value store of options that will get passed to children of
  3754. * the child.
  3755. *
  3756. * @param {number} [index=this.children_.length]
  3757. * The index to attempt to add a child into.
  3758. *
  3759. * @return {Component}
  3760. * The `Component` that gets added as a child. When using a string the
  3761. * `Component` will get created by this process.
  3762. */
  3763. addChild(child, options = {}, index = this.children_.length) {
  3764. let component;
  3765. let componentName;
  3766. // If child is a string, create component with options
  3767. if (typeof child === 'string') {
  3768. componentName = toTitleCase(child);
  3769. const componentClassName = options.componentClass || componentName;
  3770. // Set name through options
  3771. options.name = componentName;
  3772. // Create a new object & element for this controls set
  3773. // If there's no .player_, this is a player
  3774. const ComponentClass = Component.getComponent(componentClassName);
  3775. if (!ComponentClass) {
  3776. throw new Error(`Component ${componentClassName} does not exist`);
  3777. }
  3778. // data stored directly on the videojs object may be
  3779. // misidentified as a component to retain
  3780. // backwards-compatibility with 4.x. check to make sure the
  3781. // component class can be instantiated.
  3782. if (typeof ComponentClass !== 'function') {
  3783. return null;
  3784. }
  3785. component = new ComponentClass(this.player_ || this, options);
  3786. // child is a component instance
  3787. } else {
  3788. component = child;
  3789. }
  3790. if (component.parentComponent_) {
  3791. component.parentComponent_.removeChild(component);
  3792. }
  3793. this.children_.splice(index, 0, component);
  3794. component.parentComponent_ = this;
  3795. if (typeof component.id === 'function') {
  3796. this.childIndex_[component.id()] = component;
  3797. }
  3798. // If a name wasn't used to create the component, check if we can use the
  3799. // name function of the component
  3800. componentName = componentName || component.name && toTitleCase(component.name());
  3801. if (componentName) {
  3802. this.childNameIndex_[componentName] = component;
  3803. this.childNameIndex_[toLowerCase(componentName)] = component;
  3804. }
  3805. // Add the UI object's element to the container div (box)
  3806. // Having an element is not required
  3807. if (typeof component.el === 'function' && component.el()) {
  3808. // If inserting before a component, insert before that component's element
  3809. let refNode = null;
  3810. if (this.children_[index + 1]) {
  3811. // Most children are components, but the video tech is an HTML element
  3812. if (this.children_[index + 1].el_) {
  3813. refNode = this.children_[index + 1].el_;
  3814. } else if (isEl(this.children_[index + 1])) {
  3815. refNode = this.children_[index + 1];
  3816. }
  3817. }
  3818. this.contentEl().insertBefore(component.el(), refNode);
  3819. }
  3820. // Return so it can stored on parent object if desired.
  3821. return component;
  3822. }
  3823. /**
  3824. * Remove a child `Component` from this `Component`s list of children. Also removes
  3825. * the child `Component`s element from this `Component`s element.
  3826. *
  3827. * @param {Component} component
  3828. * The child `Component` to remove.
  3829. */
  3830. removeChild(component) {
  3831. if (typeof component === 'string') {
  3832. component = this.getChild(component);
  3833. }
  3834. if (!component || !this.children_) {
  3835. return;
  3836. }
  3837. let childFound = false;
  3838. for (let i = this.children_.length - 1; i >= 0; i--) {
  3839. if (this.children_[i] === component) {
  3840. childFound = true;
  3841. this.children_.splice(i, 1);
  3842. break;
  3843. }
  3844. }
  3845. if (!childFound) {
  3846. return;
  3847. }
  3848. component.parentComponent_ = null;
  3849. this.childIndex_[component.id()] = null;
  3850. this.childNameIndex_[toTitleCase(component.name())] = null;
  3851. this.childNameIndex_[toLowerCase(component.name())] = null;
  3852. const compEl = component.el();
  3853. if (compEl && compEl.parentNode === this.contentEl()) {
  3854. this.contentEl().removeChild(component.el());
  3855. }
  3856. }
  3857. /**
  3858. * Add and initialize default child `Component`s based upon options.
  3859. */
  3860. initChildren() {
  3861. const children = this.options_.children;
  3862. if (children) {
  3863. // `this` is `parent`
  3864. const parentOptions = this.options_;
  3865. const handleAdd = child => {
  3866. const name = child.name;
  3867. let opts = child.opts;
  3868. // Allow options for children to be set at the parent options
  3869. // e.g. videojs(id, { controlBar: false });
  3870. // instead of videojs(id, { children: { controlBar: false });
  3871. if (parentOptions[name] !== undefined) {
  3872. opts = parentOptions[name];
  3873. }
  3874. // Allow for disabling default components
  3875. // e.g. options['children']['posterImage'] = false
  3876. if (opts === false) {
  3877. return;
  3878. }
  3879. // Allow options to be passed as a simple boolean if no configuration
  3880. // is necessary.
  3881. if (opts === true) {
  3882. opts = {};
  3883. }
  3884. // We also want to pass the original player options
  3885. // to each component as well so they don't need to
  3886. // reach back into the player for options later.
  3887. opts.playerOptions = this.options_.playerOptions;
  3888. // Create and add the child component.
  3889. // Add a direct reference to the child by name on the parent instance.
  3890. // If two of the same component are used, different names should be supplied
  3891. // for each
  3892. const newChild = this.addChild(name, opts);
  3893. if (newChild) {
  3894. this[name] = newChild;
  3895. }
  3896. };
  3897. // Allow for an array of children details to passed in the options
  3898. let workingChildren;
  3899. const Tech = Component.getComponent('Tech');
  3900. if (Array.isArray(children)) {
  3901. workingChildren = children;
  3902. } else {
  3903. workingChildren = Object.keys(children);
  3904. }
  3905. workingChildren
  3906. // children that are in this.options_ but also in workingChildren would
  3907. // give us extra children we do not want. So, we want to filter them out.
  3908. .concat(Object.keys(this.options_).filter(function (child) {
  3909. return !workingChildren.some(function (wchild) {
  3910. if (typeof wchild === 'string') {
  3911. return child === wchild;
  3912. }
  3913. return child === wchild.name;
  3914. });
  3915. })).map(child => {
  3916. let name;
  3917. let opts;
  3918. if (typeof child === 'string') {
  3919. name = child;
  3920. opts = children[name] || this.options_[name] || {};
  3921. } else {
  3922. name = child.name;
  3923. opts = child;
  3924. }
  3925. return {
  3926. name,
  3927. opts
  3928. };
  3929. }).filter(child => {
  3930. // we have to make sure that child.name isn't in the techOrder since
  3931. // techs are registered as Components but can't aren't compatible
  3932. // See https://github.com/videojs/video.js/issues/2772
  3933. const c = Component.getComponent(child.opts.componentClass || toTitleCase(child.name));
  3934. return c && !Tech.isTech(c);
  3935. }).forEach(handleAdd);
  3936. }
  3937. }
  3938. /**
  3939. * Builds the default DOM class name. Should be overridden by sub-components.
  3940. *
  3941. * @return {string}
  3942. * The DOM class name for this object.
  3943. *
  3944. * @abstract
  3945. */
  3946. buildCSSClass() {
  3947. // Child classes can include a function that does:
  3948. // return 'CLASS NAME' + this._super();
  3949. return '';
  3950. }
  3951. /**
  3952. * Bind a listener to the component's ready state.
  3953. * Different from event listeners in that if the ready event has already happened
  3954. * it will trigger the function immediately.
  3955. *
  3956. * @param {ReadyCallback} fn
  3957. * Function that gets called when the `Component` is ready.
  3958. *
  3959. * @return {Component}
  3960. * Returns itself; method can be chained.
  3961. */
  3962. ready(fn, sync = false) {
  3963. if (!fn) {
  3964. return;
  3965. }
  3966. if (!this.isReady_) {
  3967. this.readyQueue_ = this.readyQueue_ || [];
  3968. this.readyQueue_.push(fn);
  3969. return;
  3970. }
  3971. if (sync) {
  3972. fn.call(this);
  3973. } else {
  3974. // Call the function asynchronously by default for consistency
  3975. this.setTimeout(fn, 1);
  3976. }
  3977. }
  3978. /**
  3979. * Trigger all the ready listeners for this `Component`.
  3980. *
  3981. * @fires Component#ready
  3982. */
  3983. triggerReady() {
  3984. this.isReady_ = true;
  3985. // Ensure ready is triggered asynchronously
  3986. this.setTimeout(function () {
  3987. const readyQueue = this.readyQueue_;
  3988. // Reset Ready Queue
  3989. this.readyQueue_ = [];
  3990. if (readyQueue && readyQueue.length > 0) {
  3991. readyQueue.forEach(function (fn) {
  3992. fn.call(this);
  3993. }, this);
  3994. }
  3995. // Allow for using event listeners also
  3996. /**
  3997. * Triggered when a `Component` is ready.
  3998. *
  3999. * @event Component#ready
  4000. * @type {Event}
  4001. */
  4002. this.trigger('ready');
  4003. }, 1);
  4004. }
  4005. /**
  4006. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  4007. * `contentEl()` or another custom context.
  4008. *
  4009. * @param {string} selector
  4010. * A valid CSS selector, which will be passed to `querySelector`.
  4011. *
  4012. * @param {Element|string} [context=this.contentEl()]
  4013. * A DOM element within which to query. Can also be a selector string in
  4014. * which case the first matching element will get used as context. If
  4015. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4016. * nothing it falls back to `document`.
  4017. *
  4018. * @return {Element|null}
  4019. * the dom element that was found, or null
  4020. *
  4021. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4022. */
  4023. $(selector, context) {
  4024. return $(selector, context || this.contentEl());
  4025. }
  4026. /**
  4027. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  4028. * `contentEl()` or another custom context.
  4029. *
  4030. * @param {string} selector
  4031. * A valid CSS selector, which will be passed to `querySelectorAll`.
  4032. *
  4033. * @param {Element|string} [context=this.contentEl()]
  4034. * A DOM element within which to query. Can also be a selector string in
  4035. * which case the first matching element will get used as context. If
  4036. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4037. * nothing it falls back to `document`.
  4038. *
  4039. * @return {NodeList}
  4040. * a list of dom elements that were found
  4041. *
  4042. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4043. */
  4044. $$(selector, context) {
  4045. return $$(selector, context || this.contentEl());
  4046. }
  4047. /**
  4048. * Check if a component's element has a CSS class name.
  4049. *
  4050. * @param {string} classToCheck
  4051. * CSS class name to check.
  4052. *
  4053. * @return {boolean}
  4054. * - True if the `Component` has the class.
  4055. * - False if the `Component` does not have the class`
  4056. */
  4057. hasClass(classToCheck) {
  4058. return hasClass(this.el_, classToCheck);
  4059. }
  4060. /**
  4061. * Add a CSS class name to the `Component`s element.
  4062. *
  4063. * @param {...string} classesToAdd
  4064. * One or more CSS class name to add.
  4065. */
  4066. addClass(...classesToAdd) {
  4067. addClass(this.el_, ...classesToAdd);
  4068. }
  4069. /**
  4070. * Remove a CSS class name from the `Component`s element.
  4071. *
  4072. * @param {...string} classesToRemove
  4073. * One or more CSS class name to remove.
  4074. */
  4075. removeClass(...classesToRemove) {
  4076. removeClass(this.el_, ...classesToRemove);
  4077. }
  4078. /**
  4079. * Add or remove a CSS class name from the component's element.
  4080. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  4081. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  4082. *
  4083. * @param {string} classToToggle
  4084. * The class to add or remove based on (@link Component#hasClass}
  4085. *
  4086. * @param {boolean|Dom~predicate} [predicate]
  4087. * An {@link Dom~predicate} function or a boolean
  4088. */
  4089. toggleClass(classToToggle, predicate) {
  4090. toggleClass(this.el_, classToToggle, predicate);
  4091. }
  4092. /**
  4093. * Show the `Component`s element if it is hidden by removing the
  4094. * 'vjs-hidden' class name from it.
  4095. */
  4096. show() {
  4097. this.removeClass('vjs-hidden');
  4098. }
  4099. /**
  4100. * Hide the `Component`s element if it is currently showing by adding the
  4101. * 'vjs-hidden` class name to it.
  4102. */
  4103. hide() {
  4104. this.addClass('vjs-hidden');
  4105. }
  4106. /**
  4107. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  4108. * class name to it. Used during fadeIn/fadeOut.
  4109. *
  4110. * @private
  4111. */
  4112. lockShowing() {
  4113. this.addClass('vjs-lock-showing');
  4114. }
  4115. /**
  4116. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4117. * class name from it. Used during fadeIn/fadeOut.
  4118. *
  4119. * @private
  4120. */
  4121. unlockShowing() {
  4122. this.removeClass('vjs-lock-showing');
  4123. }
  4124. /**
  4125. * Get the value of an attribute on the `Component`s element.
  4126. *
  4127. * @param {string} attribute
  4128. * Name of the attribute to get the value from.
  4129. *
  4130. * @return {string|null}
  4131. * - The value of the attribute that was asked for.
  4132. * - Can be an empty string on some browsers if the attribute does not exist
  4133. * or has no value
  4134. * - Most browsers will return null if the attribute does not exist or has
  4135. * no value.
  4136. *
  4137. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4138. */
  4139. getAttribute(attribute) {
  4140. return getAttribute(this.el_, attribute);
  4141. }
  4142. /**
  4143. * Set the value of an attribute on the `Component`'s element
  4144. *
  4145. * @param {string} attribute
  4146. * Name of the attribute to set.
  4147. *
  4148. * @param {string} value
  4149. * Value to set the attribute to.
  4150. *
  4151. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4152. */
  4153. setAttribute(attribute, value) {
  4154. setAttribute(this.el_, attribute, value);
  4155. }
  4156. /**
  4157. * Remove an attribute from the `Component`s element.
  4158. *
  4159. * @param {string} attribute
  4160. * Name of the attribute to remove.
  4161. *
  4162. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4163. */
  4164. removeAttribute(attribute) {
  4165. removeAttribute(this.el_, attribute);
  4166. }
  4167. /**
  4168. * Get or set the width of the component based upon the CSS styles.
  4169. * See {@link Component#dimension} for more detailed information.
  4170. *
  4171. * @param {number|string} [num]
  4172. * The width that you want to set postfixed with '%', 'px' or nothing.
  4173. *
  4174. * @param {boolean} [skipListeners]
  4175. * Skip the componentresize event trigger
  4176. *
  4177. * @return {number|string}
  4178. * The width when getting, zero if there is no width. Can be a string
  4179. * postpixed with '%' or 'px'.
  4180. */
  4181. width(num, skipListeners) {
  4182. return this.dimension('width', num, skipListeners);
  4183. }
  4184. /**
  4185. * Get or set the height of the component based upon the CSS styles.
  4186. * See {@link Component#dimension} for more detailed information.
  4187. *
  4188. * @param {number|string} [num]
  4189. * The height that you want to set postfixed with '%', 'px' or nothing.
  4190. *
  4191. * @param {boolean} [skipListeners]
  4192. * Skip the componentresize event trigger
  4193. *
  4194. * @return {number|string}
  4195. * The width when getting, zero if there is no width. Can be a string
  4196. * postpixed with '%' or 'px'.
  4197. */
  4198. height(num, skipListeners) {
  4199. return this.dimension('height', num, skipListeners);
  4200. }
  4201. /**
  4202. * Set both the width and height of the `Component` element at the same time.
  4203. *
  4204. * @param {number|string} width
  4205. * Width to set the `Component`s element to.
  4206. *
  4207. * @param {number|string} height
  4208. * Height to set the `Component`s element to.
  4209. */
  4210. dimensions(width, height) {
  4211. // Skip componentresize listeners on width for optimization
  4212. this.width(width, true);
  4213. this.height(height);
  4214. }
  4215. /**
  4216. * Get or set width or height of the `Component` element. This is the shared code
  4217. * for the {@link Component#width} and {@link Component#height}.
  4218. *
  4219. * Things to know:
  4220. * - If the width or height in an number this will return the number postfixed with 'px'.
  4221. * - If the width/height is a percent this will return the percent postfixed with '%'
  4222. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4223. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4224. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4225. * for more information
  4226. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4227. * and {@link {Component#currentHeight}
  4228. *
  4229. * @fires Component#componentresize
  4230. *
  4231. * @param {string} widthOrHeight
  4232. 8 'width' or 'height'
  4233. *
  4234. * @param {number|string} [num]
  4235. 8 New dimension
  4236. *
  4237. * @param {boolean} [skipListeners]
  4238. * Skip componentresize event trigger
  4239. *
  4240. * @return {number}
  4241. * The dimension when getting or 0 if unset
  4242. */
  4243. dimension(widthOrHeight, num, skipListeners) {
  4244. if (num !== undefined) {
  4245. // Set to zero if null or literally NaN (NaN !== NaN)
  4246. if (num === null || num !== num) {
  4247. num = 0;
  4248. }
  4249. // Check if using css width/height (% or px) and adjust
  4250. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4251. this.el_.style[widthOrHeight] = num;
  4252. } else if (num === 'auto') {
  4253. this.el_.style[widthOrHeight] = '';
  4254. } else {
  4255. this.el_.style[widthOrHeight] = num + 'px';
  4256. }
  4257. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4258. if (!skipListeners) {
  4259. /**
  4260. * Triggered when a component is resized.
  4261. *
  4262. * @event Component#componentresize
  4263. * @type {Event}
  4264. */
  4265. this.trigger('componentresize');
  4266. }
  4267. return;
  4268. }
  4269. // Not setting a value, so getting it
  4270. // Make sure element exists
  4271. if (!this.el_) {
  4272. return 0;
  4273. }
  4274. // Get dimension value from style
  4275. const val = this.el_.style[widthOrHeight];
  4276. const pxIndex = val.indexOf('px');
  4277. if (pxIndex !== -1) {
  4278. // Return the pixel value with no 'px'
  4279. return parseInt(val.slice(0, pxIndex), 10);
  4280. }
  4281. // No px so using % or no style was set, so falling back to offsetWidth/height
  4282. // If component has display:none, offset will return 0
  4283. // TODO: handle display:none and no dimension style using px
  4284. return parseInt(this.el_['offset' + toTitleCase(widthOrHeight)], 10);
  4285. }
  4286. /**
  4287. * Get the computed width or the height of the component's element.
  4288. *
  4289. * Uses `window.getComputedStyle`.
  4290. *
  4291. * @param {string} widthOrHeight
  4292. * A string containing 'width' or 'height'. Whichever one you want to get.
  4293. *
  4294. * @return {number}
  4295. * The dimension that gets asked for or 0 if nothing was set
  4296. * for that dimension.
  4297. */
  4298. currentDimension(widthOrHeight) {
  4299. let computedWidthOrHeight = 0;
  4300. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4301. throw new Error('currentDimension only accepts width or height value');
  4302. }
  4303. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4304. // remove 'px' from variable and parse as integer
  4305. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4306. // if the computed value is still 0, it's possible that the browser is lying
  4307. // and we want to check the offset values.
  4308. // This code also runs wherever getComputedStyle doesn't exist.
  4309. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4310. const rule = `offset${toTitleCase(widthOrHeight)}`;
  4311. computedWidthOrHeight = this.el_[rule];
  4312. }
  4313. return computedWidthOrHeight;
  4314. }
  4315. /**
  4316. * An object that contains width and height values of the `Component`s
  4317. * computed style. Uses `window.getComputedStyle`.
  4318. *
  4319. * @typedef {Object} Component~DimensionObject
  4320. *
  4321. * @property {number} width
  4322. * The width of the `Component`s computed style.
  4323. *
  4324. * @property {number} height
  4325. * The height of the `Component`s computed style.
  4326. */
  4327. /**
  4328. * Get an object that contains computed width and height values of the
  4329. * component's element.
  4330. *
  4331. * Uses `window.getComputedStyle`.
  4332. *
  4333. * @return {Component~DimensionObject}
  4334. * The computed dimensions of the component's element.
  4335. */
  4336. currentDimensions() {
  4337. return {
  4338. width: this.currentDimension('width'),
  4339. height: this.currentDimension('height')
  4340. };
  4341. }
  4342. /**
  4343. * Get the computed width of the component's element.
  4344. *
  4345. * Uses `window.getComputedStyle`.
  4346. *
  4347. * @return {number}
  4348. * The computed width of the component's element.
  4349. */
  4350. currentWidth() {
  4351. return this.currentDimension('width');
  4352. }
  4353. /**
  4354. * Get the computed height of the component's element.
  4355. *
  4356. * Uses `window.getComputedStyle`.
  4357. *
  4358. * @return {number}
  4359. * The computed height of the component's element.
  4360. */
  4361. currentHeight() {
  4362. return this.currentDimension('height');
  4363. }
  4364. /**
  4365. * Set the focus to this component
  4366. */
  4367. focus() {
  4368. this.el_.focus();
  4369. }
  4370. /**
  4371. * Remove the focus from this component
  4372. */
  4373. blur() {
  4374. this.el_.blur();
  4375. }
  4376. /**
  4377. * When this Component receives a `keydown` event which it does not process,
  4378. * it passes the event to the Player for handling.
  4379. *
  4380. * @param {KeyboardEvent} event
  4381. * The `keydown` event that caused this function to be called.
  4382. */
  4383. handleKeyDown(event) {
  4384. if (this.player_) {
  4385. // We only stop propagation here because we want unhandled events to fall
  4386. // back to the browser. Exclude Tab for focus trapping.
  4387. if (!keycode.isEventKey(event, 'Tab')) {
  4388. event.stopPropagation();
  4389. }
  4390. this.player_.handleKeyDown(event);
  4391. }
  4392. }
  4393. /**
  4394. * Many components used to have a `handleKeyPress` method, which was poorly
  4395. * named because it listened to a `keydown` event. This method name now
  4396. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4397. * will not see their method calls stop working.
  4398. *
  4399. * @param {Event} event
  4400. * The event that caused this function to be called.
  4401. */
  4402. handleKeyPress(event) {
  4403. this.handleKeyDown(event);
  4404. }
  4405. /**
  4406. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4407. * support toggling the controls through a tap on the video. They get enabled
  4408. * because every sub-component would have extra overhead otherwise.
  4409. *
  4410. * @private
  4411. * @fires Component#tap
  4412. * @listens Component#touchstart
  4413. * @listens Component#touchmove
  4414. * @listens Component#touchleave
  4415. * @listens Component#touchcancel
  4416. * @listens Component#touchend
  4417. */
  4418. emitTapEvents() {
  4419. // Track the start time so we can determine how long the touch lasted
  4420. let touchStart = 0;
  4421. let firstTouch = null;
  4422. // Maximum movement allowed during a touch event to still be considered a tap
  4423. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4424. // so 10 seems like a nice, round number.
  4425. const tapMovementThreshold = 10;
  4426. // The maximum length a touch can be while still being considered a tap
  4427. const touchTimeThreshold = 200;
  4428. let couldBeTap;
  4429. this.on('touchstart', function (event) {
  4430. // If more than one finger, don't consider treating this as a click
  4431. if (event.touches.length === 1) {
  4432. // Copy pageX/pageY from the object
  4433. firstTouch = {
  4434. pageX: event.touches[0].pageX,
  4435. pageY: event.touches[0].pageY
  4436. };
  4437. // Record start time so we can detect a tap vs. "touch and hold"
  4438. touchStart = window.performance.now();
  4439. // Reset couldBeTap tracking
  4440. couldBeTap = true;
  4441. }
  4442. });
  4443. this.on('touchmove', function (event) {
  4444. // If more than one finger, don't consider treating this as a click
  4445. if (event.touches.length > 1) {
  4446. couldBeTap = false;
  4447. } else if (firstTouch) {
  4448. // Some devices will throw touchmoves for all but the slightest of taps.
  4449. // So, if we moved only a small distance, this could still be a tap
  4450. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4451. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4452. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4453. if (touchDistance > tapMovementThreshold) {
  4454. couldBeTap = false;
  4455. }
  4456. }
  4457. });
  4458. const noTap = function () {
  4459. couldBeTap = false;
  4460. };
  4461. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4462. this.on('touchleave', noTap);
  4463. this.on('touchcancel', noTap);
  4464. // When the touch ends, measure how long it took and trigger the appropriate
  4465. // event
  4466. this.on('touchend', function (event) {
  4467. firstTouch = null;
  4468. // Proceed only if the touchmove/leave/cancel event didn't happen
  4469. if (couldBeTap === true) {
  4470. // Measure how long the touch lasted
  4471. const touchTime = window.performance.now() - touchStart;
  4472. // Make sure the touch was less than the threshold to be considered a tap
  4473. if (touchTime < touchTimeThreshold) {
  4474. // Don't let browser turn this into a click
  4475. event.preventDefault();
  4476. /**
  4477. * Triggered when a `Component` is tapped.
  4478. *
  4479. * @event Component#tap
  4480. * @type {MouseEvent}
  4481. */
  4482. this.trigger('tap');
  4483. // It may be good to copy the touchend event object and change the
  4484. // type to tap, if the other event properties aren't exact after
  4485. // Events.fixEvent runs (e.g. event.target)
  4486. }
  4487. }
  4488. });
  4489. }
  4490. /**
  4491. * This function reports user activity whenever touch events happen. This can get
  4492. * turned off by any sub-components that wants touch events to act another way.
  4493. *
  4494. * Report user touch activity when touch events occur. User activity gets used to
  4495. * determine when controls should show/hide. It is simple when it comes to mouse
  4496. * events, because any mouse event should show the controls. So we capture mouse
  4497. * events that bubble up to the player and report activity when that happens.
  4498. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4499. * controls. So touch events can't help us at the player level either.
  4500. *
  4501. * User activity gets checked asynchronously. So what could happen is a tap event
  4502. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4503. * the player. Which, if it reported user activity, would turn the controls right
  4504. * back on. We also don't want to completely block touch events from bubbling up.
  4505. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4506. * controls back on.
  4507. *
  4508. * @listens Component#touchstart
  4509. * @listens Component#touchmove
  4510. * @listens Component#touchend
  4511. * @listens Component#touchcancel
  4512. */
  4513. enableTouchActivity() {
  4514. // Don't continue if the root player doesn't support reporting user activity
  4515. if (!this.player() || !this.player().reportUserActivity) {
  4516. return;
  4517. }
  4518. // listener for reporting that the user is active
  4519. const report = bind_(this.player(), this.player().reportUserActivity);
  4520. let touchHolding;
  4521. this.on('touchstart', function () {
  4522. report();
  4523. // For as long as the they are touching the device or have their mouse down,
  4524. // we consider them active even if they're not moving their finger or mouse.
  4525. // So we want to continue to update that they are active
  4526. this.clearInterval(touchHolding);
  4527. // report at the same interval as activityCheck
  4528. touchHolding = this.setInterval(report, 250);
  4529. });
  4530. const touchEnd = function (event) {
  4531. report();
  4532. // stop the interval that maintains activity if the touch is holding
  4533. this.clearInterval(touchHolding);
  4534. };
  4535. this.on('touchmove', report);
  4536. this.on('touchend', touchEnd);
  4537. this.on('touchcancel', touchEnd);
  4538. }
  4539. /**
  4540. * A callback that has no parameters and is bound into `Component`s context.
  4541. *
  4542. * @callback Component~GenericCallback
  4543. * @this Component
  4544. */
  4545. /**
  4546. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4547. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4548. * instead though:
  4549. * 1. It gets cleared via {@link Component#clearTimeout} when
  4550. * {@link Component#dispose} gets called.
  4551. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4552. *
  4553. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4554. * will cause its dispose listener not to get cleaned up! Please use
  4555. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4556. *
  4557. * @param {Component~GenericCallback} fn
  4558. * The function that will be run after `timeout`.
  4559. *
  4560. * @param {number} timeout
  4561. * Timeout in milliseconds to delay before executing the specified function.
  4562. *
  4563. * @return {number}
  4564. * Returns a timeout ID that gets used to identify the timeout. It can also
  4565. * get used in {@link Component#clearTimeout} to clear the timeout that
  4566. * was set.
  4567. *
  4568. * @listens Component#dispose
  4569. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4570. */
  4571. setTimeout(fn, timeout) {
  4572. // declare as variables so they are properly available in timeout function
  4573. // eslint-disable-next-line
  4574. var timeoutId;
  4575. fn = bind_(this, fn);
  4576. this.clearTimersOnDispose_();
  4577. timeoutId = window.setTimeout(() => {
  4578. if (this.setTimeoutIds_.has(timeoutId)) {
  4579. this.setTimeoutIds_.delete(timeoutId);
  4580. }
  4581. fn();
  4582. }, timeout);
  4583. this.setTimeoutIds_.add(timeoutId);
  4584. return timeoutId;
  4585. }
  4586. /**
  4587. * Clears a timeout that gets created via `window.setTimeout` or
  4588. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4589. * use this function instead of `window.clearTimout`. If you don't your dispose
  4590. * listener will not get cleaned up until {@link Component#dispose}!
  4591. *
  4592. * @param {number} timeoutId
  4593. * The id of the timeout to clear. The return value of
  4594. * {@link Component#setTimeout} or `window.setTimeout`.
  4595. *
  4596. * @return {number}
  4597. * Returns the timeout id that was cleared.
  4598. *
  4599. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4600. */
  4601. clearTimeout(timeoutId) {
  4602. if (this.setTimeoutIds_.has(timeoutId)) {
  4603. this.setTimeoutIds_.delete(timeoutId);
  4604. window.clearTimeout(timeoutId);
  4605. }
  4606. return timeoutId;
  4607. }
  4608. /**
  4609. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4610. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4611. * 1. It gets cleared via {@link Component#clearInterval} when
  4612. * {@link Component#dispose} gets called.
  4613. * 2. The function callback will be a {@link Component~GenericCallback}
  4614. *
  4615. * @param {Component~GenericCallback} fn
  4616. * The function to run every `x` seconds.
  4617. *
  4618. * @param {number} interval
  4619. * Execute the specified function every `x` milliseconds.
  4620. *
  4621. * @return {number}
  4622. * Returns an id that can be used to identify the interval. It can also be be used in
  4623. * {@link Component#clearInterval} to clear the interval.
  4624. *
  4625. * @listens Component#dispose
  4626. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4627. */
  4628. setInterval(fn, interval) {
  4629. fn = bind_(this, fn);
  4630. this.clearTimersOnDispose_();
  4631. const intervalId = window.setInterval(fn, interval);
  4632. this.setIntervalIds_.add(intervalId);
  4633. return intervalId;
  4634. }
  4635. /**
  4636. * Clears an interval that gets created via `window.setInterval` or
  4637. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4638. * use this function instead of `window.clearInterval`. If you don't your dispose
  4639. * listener will not get cleaned up until {@link Component#dispose}!
  4640. *
  4641. * @param {number} intervalId
  4642. * The id of the interval to clear. The return value of
  4643. * {@link Component#setInterval} or `window.setInterval`.
  4644. *
  4645. * @return {number}
  4646. * Returns the interval id that was cleared.
  4647. *
  4648. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4649. */
  4650. clearInterval(intervalId) {
  4651. if (this.setIntervalIds_.has(intervalId)) {
  4652. this.setIntervalIds_.delete(intervalId);
  4653. window.clearInterval(intervalId);
  4654. }
  4655. return intervalId;
  4656. }
  4657. /**
  4658. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4659. * with a few extra bonuses:
  4660. *
  4661. * - Supports browsers that do not support rAF by falling back to
  4662. * {@link Component#setTimeout}.
  4663. *
  4664. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4665. * bound to the component).
  4666. *
  4667. * - Automatic cancellation of the rAF callback is handled if the component
  4668. * is disposed before it is called.
  4669. *
  4670. * @param {Component~GenericCallback} fn
  4671. * A function that will be bound to this component and executed just
  4672. * before the browser's next repaint.
  4673. *
  4674. * @return {number}
  4675. * Returns an rAF ID that gets used to identify the timeout. It can
  4676. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4677. * the animation frame callback.
  4678. *
  4679. * @listens Component#dispose
  4680. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4681. */
  4682. requestAnimationFrame(fn) {
  4683. this.clearTimersOnDispose_();
  4684. // declare as variables so they are properly available in rAF function
  4685. // eslint-disable-next-line
  4686. var id;
  4687. fn = bind_(this, fn);
  4688. id = window.requestAnimationFrame(() => {
  4689. if (this.rafIds_.has(id)) {
  4690. this.rafIds_.delete(id);
  4691. }
  4692. fn();
  4693. });
  4694. this.rafIds_.add(id);
  4695. return id;
  4696. }
  4697. /**
  4698. * Request an animation frame, but only one named animation
  4699. * frame will be queued. Another will never be added until
  4700. * the previous one finishes.
  4701. *
  4702. * @param {string} name
  4703. * The name to give this requestAnimationFrame
  4704. *
  4705. * @param {Component~GenericCallback} fn
  4706. * A function that will be bound to this component and executed just
  4707. * before the browser's next repaint.
  4708. */
  4709. requestNamedAnimationFrame(name, fn) {
  4710. if (this.namedRafs_.has(name)) {
  4711. return;
  4712. }
  4713. this.clearTimersOnDispose_();
  4714. fn = bind_(this, fn);
  4715. const id = this.requestAnimationFrame(() => {
  4716. fn();
  4717. if (this.namedRafs_.has(name)) {
  4718. this.namedRafs_.delete(name);
  4719. }
  4720. });
  4721. this.namedRafs_.set(name, id);
  4722. return name;
  4723. }
  4724. /**
  4725. * Cancels a current named animation frame if it exists.
  4726. *
  4727. * @param {string} name
  4728. * The name of the requestAnimationFrame to cancel.
  4729. */
  4730. cancelNamedAnimationFrame(name) {
  4731. if (!this.namedRafs_.has(name)) {
  4732. return;
  4733. }
  4734. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4735. this.namedRafs_.delete(name);
  4736. }
  4737. /**
  4738. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4739. * (rAF).
  4740. *
  4741. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4742. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4743. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4744. *
  4745. * @param {number} id
  4746. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4747. *
  4748. * @return {number}
  4749. * Returns the rAF ID that was cleared.
  4750. *
  4751. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4752. */
  4753. cancelAnimationFrame(id) {
  4754. if (this.rafIds_.has(id)) {
  4755. this.rafIds_.delete(id);
  4756. window.cancelAnimationFrame(id);
  4757. }
  4758. return id;
  4759. }
  4760. /**
  4761. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4762. * and `setInterval`, clearing on dispose.
  4763. *
  4764. * > Previously each timer added and removed dispose listeners on it's own.
  4765. * For better performance it was decided to batch them all, and use `Set`s
  4766. * to track outstanding timer ids.
  4767. *
  4768. * @private
  4769. */
  4770. clearTimersOnDispose_() {
  4771. if (this.clearingTimersOnDispose_) {
  4772. return;
  4773. }
  4774. this.clearingTimersOnDispose_ = true;
  4775. this.one('dispose', () => {
  4776. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4777. // for a `Set` key will actually be the value again
  4778. // so forEach((val, val) =>` but for maps we want to use
  4779. // the key.
  4780. this[idName].forEach((val, key) => this[cancelName](key));
  4781. });
  4782. this.clearingTimersOnDispose_ = false;
  4783. });
  4784. }
  4785. /**
  4786. * Register a `Component` with `videojs` given the name and the component.
  4787. *
  4788. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4789. * should be registered using {@link Tech.registerTech} or
  4790. * {@link videojs:videojs.registerTech}.
  4791. *
  4792. * > NOTE: This function can also be seen on videojs as
  4793. * {@link videojs:videojs.registerComponent}.
  4794. *
  4795. * @param {string} name
  4796. * The name of the `Component` to register.
  4797. *
  4798. * @param {Component} ComponentToRegister
  4799. * The `Component` class to register.
  4800. *
  4801. * @return {Component}
  4802. * The `Component` that was registered.
  4803. */
  4804. static registerComponent(name, ComponentToRegister) {
  4805. if (typeof name !== 'string' || !name) {
  4806. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4807. }
  4808. const Tech = Component.getComponent('Tech');
  4809. // We need to make sure this check is only done if Tech has been registered.
  4810. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4811. const isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4812. if (isTech || !isComp) {
  4813. let reason;
  4814. if (isTech) {
  4815. reason = 'techs must be registered using Tech.registerTech()';
  4816. } else {
  4817. reason = 'must be a Component subclass';
  4818. }
  4819. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4820. }
  4821. name = toTitleCase(name);
  4822. if (!Component.components_) {
  4823. Component.components_ = {};
  4824. }
  4825. const Player = Component.getComponent('Player');
  4826. if (name === 'Player' && Player && Player.players) {
  4827. const players = Player.players;
  4828. const playerNames = Object.keys(players);
  4829. // If we have players that were disposed, then their name will still be
  4830. // in Players.players. So, we must loop through and verify that the value
  4831. // for each item is not null. This allows registration of the Player component
  4832. // after all players have been disposed or before any were created.
  4833. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4834. throw new Error('Can not register Player component after player has been created.');
  4835. }
  4836. }
  4837. Component.components_[name] = ComponentToRegister;
  4838. Component.components_[toLowerCase(name)] = ComponentToRegister;
  4839. return ComponentToRegister;
  4840. }
  4841. /**
  4842. * Get a `Component` based on the name it was registered with.
  4843. *
  4844. * @param {string} name
  4845. * The Name of the component to get.
  4846. *
  4847. * @return {Component}
  4848. * The `Component` that got registered under the given name.
  4849. */
  4850. static getComponent(name) {
  4851. if (!name || !Component.components_) {
  4852. return;
  4853. }
  4854. return Component.components_[name];
  4855. }
  4856. }
  4857. Component.registerComponent('Component', Component);
  4858. /**
  4859. * @file time.js
  4860. * @module time
  4861. */
  4862. /**
  4863. * Returns the time for the specified index at the start or end
  4864. * of a TimeRange object.
  4865. *
  4866. * @typedef {Function} TimeRangeIndex
  4867. *
  4868. * @param {number} [index=0]
  4869. * The range number to return the time for.
  4870. *
  4871. * @return {number}
  4872. * The time offset at the specified index.
  4873. *
  4874. * @deprecated The index argument must be provided.
  4875. * In the future, leaving it out will throw an error.
  4876. */
  4877. /**
  4878. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4879. *
  4880. * @typedef {Object} TimeRange
  4881. *
  4882. * @property {number} length
  4883. * The number of time ranges represented by this object.
  4884. *
  4885. * @property {module:time~TimeRangeIndex} start
  4886. * Returns the time offset at which a specified time range begins.
  4887. *
  4888. * @property {module:time~TimeRangeIndex} end
  4889. * Returns the time offset at which a specified time range ends.
  4890. *
  4891. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4892. */
  4893. /**
  4894. * Check if any of the time ranges are over the maximum index.
  4895. *
  4896. * @private
  4897. * @param {string} fnName
  4898. * The function name to use for logging
  4899. *
  4900. * @param {number} index
  4901. * The index to check
  4902. *
  4903. * @param {number} maxIndex
  4904. * The maximum possible index
  4905. *
  4906. * @throws {Error} if the timeRanges provided are over the maxIndex
  4907. */
  4908. function rangeCheck(fnName, index, maxIndex) {
  4909. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4910. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4911. }
  4912. }
  4913. /**
  4914. * Get the time for the specified index at the start or end
  4915. * of a TimeRange object.
  4916. *
  4917. * @private
  4918. * @param {string} fnName
  4919. * The function name to use for logging
  4920. *
  4921. * @param {string} valueIndex
  4922. * The property that should be used to get the time. should be
  4923. * 'start' or 'end'
  4924. *
  4925. * @param {Array} ranges
  4926. * An array of time ranges
  4927. *
  4928. * @param {Array} [rangeIndex=0]
  4929. * The index to start the search at
  4930. *
  4931. * @return {number}
  4932. * The time that offset at the specified index.
  4933. *
  4934. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4935. * @throws {Error} if rangeIndex is more than the length of ranges
  4936. */
  4937. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4938. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4939. return ranges[rangeIndex][valueIndex];
  4940. }
  4941. /**
  4942. * Create a time range object given ranges of time.
  4943. *
  4944. * @private
  4945. * @param {Array} [ranges]
  4946. * An array of time ranges.
  4947. *
  4948. * @return {TimeRange}
  4949. */
  4950. function createTimeRangesObj(ranges) {
  4951. let timeRangesObj;
  4952. if (ranges === undefined || ranges.length === 0) {
  4953. timeRangesObj = {
  4954. length: 0,
  4955. start() {
  4956. throw new Error('This TimeRanges object is empty');
  4957. },
  4958. end() {
  4959. throw new Error('This TimeRanges object is empty');
  4960. }
  4961. };
  4962. } else {
  4963. timeRangesObj = {
  4964. length: ranges.length,
  4965. start: getRange.bind(null, 'start', 0, ranges),
  4966. end: getRange.bind(null, 'end', 1, ranges)
  4967. };
  4968. }
  4969. if (window.Symbol && window.Symbol.iterator) {
  4970. timeRangesObj[window.Symbol.iterator] = () => (ranges || []).values();
  4971. }
  4972. return timeRangesObj;
  4973. }
  4974. /**
  4975. * Create a `TimeRange` object which mimics an
  4976. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4977. *
  4978. * @param {number|Array[]} start
  4979. * The start of a single range (a number) or an array of ranges (an
  4980. * array of arrays of two numbers each).
  4981. *
  4982. * @param {number} end
  4983. * The end of a single range. Cannot be used with the array form of
  4984. * the `start` argument.
  4985. *
  4986. * @return {TimeRange}
  4987. */
  4988. function createTimeRanges(start, end) {
  4989. if (Array.isArray(start)) {
  4990. return createTimeRangesObj(start);
  4991. } else if (start === undefined || end === undefined) {
  4992. return createTimeRangesObj();
  4993. }
  4994. return createTimeRangesObj([[start, end]]);
  4995. }
  4996. /**
  4997. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4998. * seconds) will force a number of leading zeros to cover the length of the
  4999. * guide.
  5000. *
  5001. * @private
  5002. * @param {number} seconds
  5003. * Number of seconds to be turned into a string
  5004. *
  5005. * @param {number} guide
  5006. * Number (in seconds) to model the string after
  5007. *
  5008. * @return {string}
  5009. * Time formatted as H:MM:SS or M:SS
  5010. */
  5011. const defaultImplementation = function (seconds, guide) {
  5012. seconds = seconds < 0 ? 0 : seconds;
  5013. let s = Math.floor(seconds % 60);
  5014. let m = Math.floor(seconds / 60 % 60);
  5015. let h = Math.floor(seconds / 3600);
  5016. const gm = Math.floor(guide / 60 % 60);
  5017. const gh = Math.floor(guide / 3600);
  5018. // handle invalid times
  5019. if (isNaN(seconds) || seconds === Infinity) {
  5020. // '-' is false for all relational operators (e.g. <, >=) so this setting
  5021. // will add the minimum number of fields specified by the guide
  5022. h = m = s = '-';
  5023. }
  5024. // Check if we need to show hours
  5025. h = h > 0 || gh > 0 ? h + ':' : '';
  5026. // If hours are showing, we may need to add a leading zero.
  5027. // Always show at least one digit of minutes.
  5028. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  5029. // Check if leading zero is need for seconds
  5030. s = s < 10 ? '0' + s : s;
  5031. return h + m + s;
  5032. };
  5033. // Internal pointer to the current implementation.
  5034. let implementation = defaultImplementation;
  5035. /**
  5036. * Replaces the default formatTime implementation with a custom implementation.
  5037. *
  5038. * @param {Function} customImplementation
  5039. * A function which will be used in place of the default formatTime
  5040. * implementation. Will receive the current time in seconds and the
  5041. * guide (in seconds) as arguments.
  5042. */
  5043. function setFormatTime(customImplementation) {
  5044. implementation = customImplementation;
  5045. }
  5046. /**
  5047. * Resets formatTime to the default implementation.
  5048. */
  5049. function resetFormatTime() {
  5050. implementation = defaultImplementation;
  5051. }
  5052. /**
  5053. * Delegates to either the default time formatting function or a custom
  5054. * function supplied via `setFormatTime`.
  5055. *
  5056. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  5057. * guide (in seconds) will force a number of leading zeros to cover the
  5058. * length of the guide.
  5059. *
  5060. * @example formatTime(125, 600) === "02:05"
  5061. * @param {number} seconds
  5062. * Number of seconds to be turned into a string
  5063. *
  5064. * @param {number} guide
  5065. * Number (in seconds) to model the string after
  5066. *
  5067. * @return {string}
  5068. * Time formatted as H:MM:SS or M:SS
  5069. */
  5070. function formatTime(seconds, guide = seconds) {
  5071. return implementation(seconds, guide);
  5072. }
  5073. var Time = /*#__PURE__*/Object.freeze({
  5074. __proto__: null,
  5075. createTimeRanges: createTimeRanges,
  5076. createTimeRange: createTimeRanges,
  5077. setFormatTime: setFormatTime,
  5078. resetFormatTime: resetFormatTime,
  5079. formatTime: formatTime
  5080. });
  5081. /**
  5082. * @file buffer.js
  5083. * @module buffer
  5084. */
  5085. /**
  5086. * Compute the percentage of the media that has been buffered.
  5087. *
  5088. * @param { import('./time').TimeRange } buffered
  5089. * The current `TimeRanges` object representing buffered time ranges
  5090. *
  5091. * @param {number} duration
  5092. * Total duration of the media
  5093. *
  5094. * @return {number}
  5095. * Percent buffered of the total duration in decimal form.
  5096. */
  5097. function bufferedPercent(buffered, duration) {
  5098. let bufferedDuration = 0;
  5099. let start;
  5100. let end;
  5101. if (!duration) {
  5102. return 0;
  5103. }
  5104. if (!buffered || !buffered.length) {
  5105. buffered = createTimeRanges(0, 0);
  5106. }
  5107. for (let i = 0; i < buffered.length; i++) {
  5108. start = buffered.start(i);
  5109. end = buffered.end(i);
  5110. // buffered end can be bigger than duration by a very small fraction
  5111. if (end > duration) {
  5112. end = duration;
  5113. }
  5114. bufferedDuration += end - start;
  5115. }
  5116. return bufferedDuration / duration;
  5117. }
  5118. /**
  5119. * @file media-error.js
  5120. */
  5121. /**
  5122. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  5123. *
  5124. * @param {number|string|Object|MediaError} value
  5125. * This can be of multiple types:
  5126. * - number: should be a standard error code
  5127. * - string: an error message (the code will be 0)
  5128. * - Object: arbitrary properties
  5129. * - `MediaError` (native): used to populate a video.js `MediaError` object
  5130. * - `MediaError` (video.js): will return itself if it's already a
  5131. * video.js `MediaError` object.
  5132. *
  5133. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  5134. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  5135. *
  5136. * @class MediaError
  5137. */
  5138. function MediaError(value) {
  5139. // Allow redundant calls to this constructor to avoid having `instanceof`
  5140. // checks peppered around the code.
  5141. if (value instanceof MediaError) {
  5142. return value;
  5143. }
  5144. if (typeof value === 'number') {
  5145. this.code = value;
  5146. } else if (typeof value === 'string') {
  5147. // default code is zero, so this is a custom error
  5148. this.message = value;
  5149. } else if (isObject(value)) {
  5150. // We assign the `code` property manually because native `MediaError` objects
  5151. // do not expose it as an own/enumerable property of the object.
  5152. if (typeof value.code === 'number') {
  5153. this.code = value.code;
  5154. }
  5155. Object.assign(this, value);
  5156. }
  5157. if (!this.message) {
  5158. this.message = MediaError.defaultMessages[this.code] || '';
  5159. }
  5160. }
  5161. /**
  5162. * The error code that refers two one of the defined `MediaError` types
  5163. *
  5164. * @type {Number}
  5165. */
  5166. MediaError.prototype.code = 0;
  5167. /**
  5168. * An optional message that to show with the error. Message is not part of the HTML5
  5169. * video spec but allows for more informative custom errors.
  5170. *
  5171. * @type {String}
  5172. */
  5173. MediaError.prototype.message = '';
  5174. /**
  5175. * An optional status code that can be set by plugins to allow even more detail about
  5176. * the error. For example a plugin might provide a specific HTTP status code and an
  5177. * error message for that code. Then when the plugin gets that error this class will
  5178. * know how to display an error message for it. This allows a custom message to show
  5179. * up on the `Player` error overlay.
  5180. *
  5181. * @type {Array}
  5182. */
  5183. MediaError.prototype.status = null;
  5184. /**
  5185. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5186. * specification listed under {@link MediaError} for more information.
  5187. *
  5188. * @enum {array}
  5189. * @readonly
  5190. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5191. * @property {string} 1 - MEDIA_ERR_ABORTED
  5192. * @property {string} 2 - MEDIA_ERR_NETWORK
  5193. * @property {string} 3 - MEDIA_ERR_DECODE
  5194. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5195. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5196. */
  5197. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5198. /**
  5199. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5200. *
  5201. * @type {Array}
  5202. * @constant
  5203. */
  5204. MediaError.defaultMessages = {
  5205. 1: 'You aborted the media playback',
  5206. 2: 'A network error caused the media download to fail part-way.',
  5207. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5208. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5209. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5210. };
  5211. // Add types as properties on MediaError
  5212. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5213. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5214. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5215. // values should be accessible on both the class and instance
  5216. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5217. }
  5218. var tuple = SafeParseTuple;
  5219. function SafeParseTuple(obj, reviver) {
  5220. var json;
  5221. var error = null;
  5222. try {
  5223. json = JSON.parse(obj, reviver);
  5224. } catch (err) {
  5225. error = err;
  5226. }
  5227. return [error, json];
  5228. }
  5229. /**
  5230. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5231. *
  5232. * @param {Object} value
  5233. * An object that may or may not be `Promise`-like.
  5234. *
  5235. * @return {boolean}
  5236. * Whether or not the object is `Promise`-like.
  5237. */
  5238. function isPromise(value) {
  5239. return value !== undefined && value !== null && typeof value.then === 'function';
  5240. }
  5241. /**
  5242. * Silence a Promise-like object.
  5243. *
  5244. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5245. * play promise" rejection error messages.
  5246. *
  5247. * @param {Object} value
  5248. * An object that may or may not be `Promise`-like.
  5249. */
  5250. function silencePromise(value) {
  5251. if (isPromise(value)) {
  5252. value.then(null, e => {});
  5253. }
  5254. }
  5255. /**
  5256. * @file text-track-list-converter.js Utilities for capturing text track state and
  5257. * re-creating tracks based on a capture.
  5258. *
  5259. * @module text-track-list-converter
  5260. */
  5261. /**
  5262. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5263. * represents the {@link TextTrack}'s state.
  5264. *
  5265. * @param {TextTrack} track
  5266. * The text track to query.
  5267. *
  5268. * @return {Object}
  5269. * A serializable javascript representation of the TextTrack.
  5270. * @private
  5271. */
  5272. const trackToJson_ = function (track) {
  5273. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5274. if (track[prop]) {
  5275. acc[prop] = track[prop];
  5276. }
  5277. return acc;
  5278. }, {
  5279. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5280. return {
  5281. startTime: cue.startTime,
  5282. endTime: cue.endTime,
  5283. text: cue.text,
  5284. id: cue.id
  5285. };
  5286. })
  5287. });
  5288. return ret;
  5289. };
  5290. /**
  5291. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5292. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5293. * {@link text-track-list-converter:jsonToTextTracks}.
  5294. *
  5295. * @param { import('../tech/tech').default } tech
  5296. * The tech object to query
  5297. *
  5298. * @return {Array}
  5299. * A serializable javascript representation of the {@link Tech}s
  5300. * {@link TextTrackList}.
  5301. */
  5302. const textTracksToJson = function (tech) {
  5303. const trackEls = tech.$$('track');
  5304. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5305. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5306. const json = trackToJson_(trackEl.track);
  5307. if (trackEl.src) {
  5308. json.src = trackEl.src;
  5309. }
  5310. return json;
  5311. });
  5312. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5313. return trackObjs.indexOf(track) === -1;
  5314. }).map(trackToJson_));
  5315. };
  5316. /**
  5317. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5318. * object {@link TextTrack} representations.
  5319. *
  5320. * @param {Array} json
  5321. * An array of `TextTrack` representation objects, like those that would be
  5322. * produced by `textTracksToJson`.
  5323. *
  5324. * @param {Tech} tech
  5325. * The `Tech` to create the `TextTrack`s on.
  5326. */
  5327. const jsonToTextTracks = function (json, tech) {
  5328. json.forEach(function (track) {
  5329. const addedTrack = tech.addRemoteTextTrack(track).track;
  5330. if (!track.src && track.cues) {
  5331. track.cues.forEach(cue => addedTrack.addCue(cue));
  5332. }
  5333. });
  5334. return tech.textTracks();
  5335. };
  5336. var textTrackConverter = {
  5337. textTracksToJson,
  5338. jsonToTextTracks,
  5339. trackToJson_
  5340. };
  5341. /**
  5342. * @file modal-dialog.js
  5343. */
  5344. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5345. /**
  5346. * The `ModalDialog` displays over the video and its controls, which blocks
  5347. * interaction with the player until it is closed.
  5348. *
  5349. * Modal dialogs include a "Close" button and will close when that button
  5350. * is activated - or when ESC is pressed anywhere.
  5351. *
  5352. * @extends Component
  5353. */
  5354. class ModalDialog extends Component {
  5355. /**
  5356. * Create an instance of this class.
  5357. *
  5358. * @param { import('./player').default } player
  5359. * The `Player` that this class should be attached to.
  5360. *
  5361. * @param {Object} [options]
  5362. * The key/value store of player options.
  5363. *
  5364. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5365. * Provide customized content for this modal.
  5366. *
  5367. * @param {string} [options.description]
  5368. * A text description for the modal, primarily for accessibility.
  5369. *
  5370. * @param {boolean} [options.fillAlways=false]
  5371. * Normally, modals are automatically filled only the first time
  5372. * they open. This tells the modal to refresh its content
  5373. * every time it opens.
  5374. *
  5375. * @param {string} [options.label]
  5376. * A text label for the modal, primarily for accessibility.
  5377. *
  5378. * @param {boolean} [options.pauseOnOpen=true]
  5379. * If `true`, playback will will be paused if playing when
  5380. * the modal opens, and resumed when it closes.
  5381. *
  5382. * @param {boolean} [options.temporary=true]
  5383. * If `true`, the modal can only be opened once; it will be
  5384. * disposed as soon as it's closed.
  5385. *
  5386. * @param {boolean} [options.uncloseable=false]
  5387. * If `true`, the user will not be able to close the modal
  5388. * through the UI in the normal ways. Programmatic closing is
  5389. * still possible.
  5390. */
  5391. constructor(player, options) {
  5392. super(player, options);
  5393. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5394. this.close_ = e => this.close(e);
  5395. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5396. this.closeable(!this.options_.uncloseable);
  5397. this.content(this.options_.content);
  5398. // Make sure the contentEl is defined AFTER any children are initialized
  5399. // because we only want the contents of the modal in the contentEl
  5400. // (not the UI elements like the close button).
  5401. this.contentEl_ = createEl('div', {
  5402. className: `${MODAL_CLASS_NAME}-content`
  5403. }, {
  5404. role: 'document'
  5405. });
  5406. this.descEl_ = createEl('p', {
  5407. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5408. id: this.el().getAttribute('aria-describedby')
  5409. });
  5410. textContent(this.descEl_, this.description());
  5411. this.el_.appendChild(this.descEl_);
  5412. this.el_.appendChild(this.contentEl_);
  5413. }
  5414. /**
  5415. * Create the `ModalDialog`'s DOM element
  5416. *
  5417. * @return {Element}
  5418. * The DOM element that gets created.
  5419. */
  5420. createEl() {
  5421. return super.createEl('div', {
  5422. className: this.buildCSSClass(),
  5423. tabIndex: -1
  5424. }, {
  5425. 'aria-describedby': `${this.id()}_description`,
  5426. 'aria-hidden': 'true',
  5427. 'aria-label': this.label(),
  5428. 'role': 'dialog'
  5429. });
  5430. }
  5431. dispose() {
  5432. this.contentEl_ = null;
  5433. this.descEl_ = null;
  5434. this.previouslyActiveEl_ = null;
  5435. super.dispose();
  5436. }
  5437. /**
  5438. * Builds the default DOM `className`.
  5439. *
  5440. * @return {string}
  5441. * The DOM `className` for this object.
  5442. */
  5443. buildCSSClass() {
  5444. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5445. }
  5446. /**
  5447. * Returns the label string for this modal. Primarily used for accessibility.
  5448. *
  5449. * @return {string}
  5450. * the localized or raw label of this modal.
  5451. */
  5452. label() {
  5453. return this.localize(this.options_.label || 'Modal Window');
  5454. }
  5455. /**
  5456. * Returns the description string for this modal. Primarily used for
  5457. * accessibility.
  5458. *
  5459. * @return {string}
  5460. * The localized or raw description of this modal.
  5461. */
  5462. description() {
  5463. let desc = this.options_.description || this.localize('This is a modal window.');
  5464. // Append a universal closeability message if the modal is closeable.
  5465. if (this.closeable()) {
  5466. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5467. }
  5468. return desc;
  5469. }
  5470. /**
  5471. * Opens the modal.
  5472. *
  5473. * @fires ModalDialog#beforemodalopen
  5474. * @fires ModalDialog#modalopen
  5475. */
  5476. open() {
  5477. if (!this.opened_) {
  5478. const player = this.player();
  5479. /**
  5480. * Fired just before a `ModalDialog` is opened.
  5481. *
  5482. * @event ModalDialog#beforemodalopen
  5483. * @type {Event}
  5484. */
  5485. this.trigger('beforemodalopen');
  5486. this.opened_ = true;
  5487. // Fill content if the modal has never opened before and
  5488. // never been filled.
  5489. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5490. this.fill();
  5491. }
  5492. // If the player was playing, pause it and take note of its previously
  5493. // playing state.
  5494. this.wasPlaying_ = !player.paused();
  5495. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5496. player.pause();
  5497. }
  5498. this.on('keydown', this.handleKeyDown_);
  5499. // Hide controls and note if they were enabled.
  5500. this.hadControls_ = player.controls();
  5501. player.controls(false);
  5502. this.show();
  5503. this.conditionalFocus_();
  5504. this.el().setAttribute('aria-hidden', 'false');
  5505. /**
  5506. * Fired just after a `ModalDialog` is opened.
  5507. *
  5508. * @event ModalDialog#modalopen
  5509. * @type {Event}
  5510. */
  5511. this.trigger('modalopen');
  5512. this.hasBeenOpened_ = true;
  5513. }
  5514. }
  5515. /**
  5516. * If the `ModalDialog` is currently open or closed.
  5517. *
  5518. * @param {boolean} [value]
  5519. * If given, it will open (`true`) or close (`false`) the modal.
  5520. *
  5521. * @return {boolean}
  5522. * the current open state of the modaldialog
  5523. */
  5524. opened(value) {
  5525. if (typeof value === 'boolean') {
  5526. this[value ? 'open' : 'close']();
  5527. }
  5528. return this.opened_;
  5529. }
  5530. /**
  5531. * Closes the modal, does nothing if the `ModalDialog` is
  5532. * not open.
  5533. *
  5534. * @fires ModalDialog#beforemodalclose
  5535. * @fires ModalDialog#modalclose
  5536. */
  5537. close() {
  5538. if (!this.opened_) {
  5539. return;
  5540. }
  5541. const player = this.player();
  5542. /**
  5543. * Fired just before a `ModalDialog` is closed.
  5544. *
  5545. * @event ModalDialog#beforemodalclose
  5546. * @type {Event}
  5547. */
  5548. this.trigger('beforemodalclose');
  5549. this.opened_ = false;
  5550. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5551. player.play();
  5552. }
  5553. this.off('keydown', this.handleKeyDown_);
  5554. if (this.hadControls_) {
  5555. player.controls(true);
  5556. }
  5557. this.hide();
  5558. this.el().setAttribute('aria-hidden', 'true');
  5559. /**
  5560. * Fired just after a `ModalDialog` is closed.
  5561. *
  5562. * @event ModalDialog#modalclose
  5563. * @type {Event}
  5564. */
  5565. this.trigger('modalclose');
  5566. this.conditionalBlur_();
  5567. if (this.options_.temporary) {
  5568. this.dispose();
  5569. }
  5570. }
  5571. /**
  5572. * Check to see if the `ModalDialog` is closeable via the UI.
  5573. *
  5574. * @param {boolean} [value]
  5575. * If given as a boolean, it will set the `closeable` option.
  5576. *
  5577. * @return {boolean}
  5578. * Returns the final value of the closable option.
  5579. */
  5580. closeable(value) {
  5581. if (typeof value === 'boolean') {
  5582. const closeable = this.closeable_ = !!value;
  5583. let close = this.getChild('closeButton');
  5584. // If this is being made closeable and has no close button, add one.
  5585. if (closeable && !close) {
  5586. // The close button should be a child of the modal - not its
  5587. // content element, so temporarily change the content element.
  5588. const temp = this.contentEl_;
  5589. this.contentEl_ = this.el_;
  5590. close = this.addChild('closeButton', {
  5591. controlText: 'Close Modal Dialog'
  5592. });
  5593. this.contentEl_ = temp;
  5594. this.on(close, 'close', this.close_);
  5595. }
  5596. // If this is being made uncloseable and has a close button, remove it.
  5597. if (!closeable && close) {
  5598. this.off(close, 'close', this.close_);
  5599. this.removeChild(close);
  5600. close.dispose();
  5601. }
  5602. }
  5603. return this.closeable_;
  5604. }
  5605. /**
  5606. * Fill the modal's content element with the modal's "content" option.
  5607. * The content element will be emptied before this change takes place.
  5608. */
  5609. fill() {
  5610. this.fillWith(this.content());
  5611. }
  5612. /**
  5613. * Fill the modal's content element with arbitrary content.
  5614. * The content element will be emptied before this change takes place.
  5615. *
  5616. * @fires ModalDialog#beforemodalfill
  5617. * @fires ModalDialog#modalfill
  5618. *
  5619. * @param { import('./utils/dom').ContentDescriptor} [content]
  5620. * The same rules apply to this as apply to the `content` option.
  5621. */
  5622. fillWith(content) {
  5623. const contentEl = this.contentEl();
  5624. const parentEl = contentEl.parentNode;
  5625. const nextSiblingEl = contentEl.nextSibling;
  5626. /**
  5627. * Fired just before a `ModalDialog` is filled with content.
  5628. *
  5629. * @event ModalDialog#beforemodalfill
  5630. * @type {Event}
  5631. */
  5632. this.trigger('beforemodalfill');
  5633. this.hasBeenFilled_ = true;
  5634. // Detach the content element from the DOM before performing
  5635. // manipulation to avoid modifying the live DOM multiple times.
  5636. parentEl.removeChild(contentEl);
  5637. this.empty();
  5638. insertContent(contentEl, content);
  5639. /**
  5640. * Fired just after a `ModalDialog` is filled with content.
  5641. *
  5642. * @event ModalDialog#modalfill
  5643. * @type {Event}
  5644. */
  5645. this.trigger('modalfill');
  5646. // Re-inject the re-filled content element.
  5647. if (nextSiblingEl) {
  5648. parentEl.insertBefore(contentEl, nextSiblingEl);
  5649. } else {
  5650. parentEl.appendChild(contentEl);
  5651. }
  5652. // make sure that the close button is last in the dialog DOM
  5653. const closeButton = this.getChild('closeButton');
  5654. if (closeButton) {
  5655. parentEl.appendChild(closeButton.el_);
  5656. }
  5657. }
  5658. /**
  5659. * Empties the content element. This happens anytime the modal is filled.
  5660. *
  5661. * @fires ModalDialog#beforemodalempty
  5662. * @fires ModalDialog#modalempty
  5663. */
  5664. empty() {
  5665. /**
  5666. * Fired just before a `ModalDialog` is emptied.
  5667. *
  5668. * @event ModalDialog#beforemodalempty
  5669. * @type {Event}
  5670. */
  5671. this.trigger('beforemodalempty');
  5672. emptyEl(this.contentEl());
  5673. /**
  5674. * Fired just after a `ModalDialog` is emptied.
  5675. *
  5676. * @event ModalDialog#modalempty
  5677. * @type {Event}
  5678. */
  5679. this.trigger('modalempty');
  5680. }
  5681. /**
  5682. * Gets or sets the modal content, which gets normalized before being
  5683. * rendered into the DOM.
  5684. *
  5685. * This does not update the DOM or fill the modal, but it is called during
  5686. * that process.
  5687. *
  5688. * @param { import('./utils/dom').ContentDescriptor} [value]
  5689. * If defined, sets the internal content value to be used on the
  5690. * next call(s) to `fill`. This value is normalized before being
  5691. * inserted. To "clear" the internal content value, pass `null`.
  5692. *
  5693. * @return { import('./utils/dom').ContentDescriptor}
  5694. * The current content of the modal dialog
  5695. */
  5696. content(value) {
  5697. if (typeof value !== 'undefined') {
  5698. this.content_ = value;
  5699. }
  5700. return this.content_;
  5701. }
  5702. /**
  5703. * conditionally focus the modal dialog if focus was previously on the player.
  5704. *
  5705. * @private
  5706. */
  5707. conditionalFocus_() {
  5708. const activeEl = document.activeElement;
  5709. const playerEl = this.player_.el_;
  5710. this.previouslyActiveEl_ = null;
  5711. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5712. this.previouslyActiveEl_ = activeEl;
  5713. this.focus();
  5714. }
  5715. }
  5716. /**
  5717. * conditionally blur the element and refocus the last focused element
  5718. *
  5719. * @private
  5720. */
  5721. conditionalBlur_() {
  5722. if (this.previouslyActiveEl_) {
  5723. this.previouslyActiveEl_.focus();
  5724. this.previouslyActiveEl_ = null;
  5725. }
  5726. }
  5727. /**
  5728. * Keydown handler. Attached when modal is focused.
  5729. *
  5730. * @listens keydown
  5731. */
  5732. handleKeyDown(event) {
  5733. // Do not allow keydowns to reach out of the modal dialog.
  5734. event.stopPropagation();
  5735. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5736. event.preventDefault();
  5737. this.close();
  5738. return;
  5739. }
  5740. // exit early if it isn't a tab key
  5741. if (!keycode.isEventKey(event, 'Tab')) {
  5742. return;
  5743. }
  5744. const focusableEls = this.focusableEls_();
  5745. const activeEl = this.el_.querySelector(':focus');
  5746. let focusIndex;
  5747. for (let i = 0; i < focusableEls.length; i++) {
  5748. if (activeEl === focusableEls[i]) {
  5749. focusIndex = i;
  5750. break;
  5751. }
  5752. }
  5753. if (document.activeElement === this.el_) {
  5754. focusIndex = 0;
  5755. }
  5756. if (event.shiftKey && focusIndex === 0) {
  5757. focusableEls[focusableEls.length - 1].focus();
  5758. event.preventDefault();
  5759. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5760. focusableEls[0].focus();
  5761. event.preventDefault();
  5762. }
  5763. }
  5764. /**
  5765. * get all focusable elements
  5766. *
  5767. * @private
  5768. */
  5769. focusableEls_() {
  5770. const allChildren = this.el_.querySelectorAll('*');
  5771. return Array.prototype.filter.call(allChildren, child => {
  5772. 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');
  5773. });
  5774. }
  5775. }
  5776. /**
  5777. * Default options for `ModalDialog` default options.
  5778. *
  5779. * @type {Object}
  5780. * @private
  5781. */
  5782. ModalDialog.prototype.options_ = {
  5783. pauseOnOpen: true,
  5784. temporary: true
  5785. };
  5786. Component.registerComponent('ModalDialog', ModalDialog);
  5787. /**
  5788. * @file track-list.js
  5789. */
  5790. /**
  5791. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5792. * {@link VideoTrackList}
  5793. *
  5794. * @extends EventTarget
  5795. */
  5796. class TrackList extends EventTarget {
  5797. /**
  5798. * Create an instance of this class
  5799. *
  5800. * @param { import('./track').default[] } tracks
  5801. * A list of tracks to initialize the list with.
  5802. *
  5803. * @abstract
  5804. */
  5805. constructor(tracks = []) {
  5806. super();
  5807. this.tracks_ = [];
  5808. /**
  5809. * @memberof TrackList
  5810. * @member {number} length
  5811. * The current number of `Track`s in the this Trackist.
  5812. * @instance
  5813. */
  5814. Object.defineProperty(this, 'length', {
  5815. get() {
  5816. return this.tracks_.length;
  5817. }
  5818. });
  5819. for (let i = 0; i < tracks.length; i++) {
  5820. this.addTrack(tracks[i]);
  5821. }
  5822. }
  5823. /**
  5824. * Add a {@link Track} to the `TrackList`
  5825. *
  5826. * @param { import('./track').default } track
  5827. * The audio, video, or text track to add to the list.
  5828. *
  5829. * @fires TrackList#addtrack
  5830. */
  5831. addTrack(track) {
  5832. const index = this.tracks_.length;
  5833. if (!('' + index in this)) {
  5834. Object.defineProperty(this, index, {
  5835. get() {
  5836. return this.tracks_[index];
  5837. }
  5838. });
  5839. }
  5840. // Do not add duplicate tracks
  5841. if (this.tracks_.indexOf(track) === -1) {
  5842. this.tracks_.push(track);
  5843. /**
  5844. * Triggered when a track is added to a track list.
  5845. *
  5846. * @event TrackList#addtrack
  5847. * @type {Event}
  5848. * @property {Track} track
  5849. * A reference to track that was added.
  5850. */
  5851. this.trigger({
  5852. track,
  5853. type: 'addtrack',
  5854. target: this
  5855. });
  5856. }
  5857. /**
  5858. * Triggered when a track label is changed.
  5859. *
  5860. * @event TrackList#addtrack
  5861. * @type {Event}
  5862. * @property {Track} track
  5863. * A reference to track that was added.
  5864. */
  5865. track.labelchange_ = () => {
  5866. this.trigger({
  5867. track,
  5868. type: 'labelchange',
  5869. target: this
  5870. });
  5871. };
  5872. if (isEvented(track)) {
  5873. track.addEventListener('labelchange', track.labelchange_);
  5874. }
  5875. }
  5876. /**
  5877. * Remove a {@link Track} from the `TrackList`
  5878. *
  5879. * @param { import('./track').default } rtrack
  5880. * The audio, video, or text track to remove from the list.
  5881. *
  5882. * @fires TrackList#removetrack
  5883. */
  5884. removeTrack(rtrack) {
  5885. let track;
  5886. for (let i = 0, l = this.length; i < l; i++) {
  5887. if (this[i] === rtrack) {
  5888. track = this[i];
  5889. if (track.off) {
  5890. track.off();
  5891. }
  5892. this.tracks_.splice(i, 1);
  5893. break;
  5894. }
  5895. }
  5896. if (!track) {
  5897. return;
  5898. }
  5899. /**
  5900. * Triggered when a track is removed from track list.
  5901. *
  5902. * @event TrackList#removetrack
  5903. * @type {Event}
  5904. * @property {Track} track
  5905. * A reference to track that was removed.
  5906. */
  5907. this.trigger({
  5908. track,
  5909. type: 'removetrack',
  5910. target: this
  5911. });
  5912. }
  5913. /**
  5914. * Get a Track from the TrackList by a tracks id
  5915. *
  5916. * @param {string} id - the id of the track to get
  5917. * @method getTrackById
  5918. * @return { import('./track').default }
  5919. * @private
  5920. */
  5921. getTrackById(id) {
  5922. let result = null;
  5923. for (let i = 0, l = this.length; i < l; i++) {
  5924. const track = this[i];
  5925. if (track.id === id) {
  5926. result = track;
  5927. break;
  5928. }
  5929. }
  5930. return result;
  5931. }
  5932. }
  5933. /**
  5934. * Triggered when a different track is selected/enabled.
  5935. *
  5936. * @event TrackList#change
  5937. * @type {Event}
  5938. */
  5939. /**
  5940. * Events that can be called with on + eventName. See {@link EventHandler}.
  5941. *
  5942. * @property {Object} TrackList#allowedEvents_
  5943. * @private
  5944. */
  5945. TrackList.prototype.allowedEvents_ = {
  5946. change: 'change',
  5947. addtrack: 'addtrack',
  5948. removetrack: 'removetrack',
  5949. labelchange: 'labelchange'
  5950. };
  5951. // emulate attribute EventHandler support to allow for feature detection
  5952. for (const event in TrackList.prototype.allowedEvents_) {
  5953. TrackList.prototype['on' + event] = null;
  5954. }
  5955. /**
  5956. * @file audio-track-list.js
  5957. */
  5958. /**
  5959. * Anywhere we call this function we diverge from the spec
  5960. * as we only support one enabled audiotrack at a time
  5961. *
  5962. * @param {AudioTrackList} list
  5963. * list to work on
  5964. *
  5965. * @param { import('./audio-track').default } track
  5966. * The track to skip
  5967. *
  5968. * @private
  5969. */
  5970. const disableOthers$1 = function (list, track) {
  5971. for (let i = 0; i < list.length; i++) {
  5972. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5973. continue;
  5974. }
  5975. // another audio track is enabled, disable it
  5976. list[i].enabled = false;
  5977. }
  5978. };
  5979. /**
  5980. * The current list of {@link AudioTrack} for a media file.
  5981. *
  5982. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5983. * @extends TrackList
  5984. */
  5985. class AudioTrackList extends TrackList {
  5986. /**
  5987. * Create an instance of this class.
  5988. *
  5989. * @param {AudioTrack[]} [tracks=[]]
  5990. * A list of `AudioTrack` to instantiate the list with.
  5991. */
  5992. constructor(tracks = []) {
  5993. // make sure only 1 track is enabled
  5994. // sorted from last index to first index
  5995. for (let i = tracks.length - 1; i >= 0; i--) {
  5996. if (tracks[i].enabled) {
  5997. disableOthers$1(tracks, tracks[i]);
  5998. break;
  5999. }
  6000. }
  6001. super(tracks);
  6002. this.changing_ = false;
  6003. }
  6004. /**
  6005. * Add an {@link AudioTrack} to the `AudioTrackList`.
  6006. *
  6007. * @param { import('./audio-track').default } track
  6008. * The AudioTrack to add to the list
  6009. *
  6010. * @fires TrackList#addtrack
  6011. */
  6012. addTrack(track) {
  6013. if (track.enabled) {
  6014. disableOthers$1(this, track);
  6015. }
  6016. super.addTrack(track);
  6017. // native tracks don't have this
  6018. if (!track.addEventListener) {
  6019. return;
  6020. }
  6021. track.enabledChange_ = () => {
  6022. // when we are disabling other tracks (since we don't support
  6023. // more than one track at a time) we will set changing_
  6024. // to true so that we don't trigger additional change events
  6025. if (this.changing_) {
  6026. return;
  6027. }
  6028. this.changing_ = true;
  6029. disableOthers$1(this, track);
  6030. this.changing_ = false;
  6031. this.trigger('change');
  6032. };
  6033. /**
  6034. * @listens AudioTrack#enabledchange
  6035. * @fires TrackList#change
  6036. */
  6037. track.addEventListener('enabledchange', track.enabledChange_);
  6038. }
  6039. removeTrack(rtrack) {
  6040. super.removeTrack(rtrack);
  6041. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  6042. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  6043. rtrack.enabledChange_ = null;
  6044. }
  6045. }
  6046. }
  6047. /**
  6048. * @file video-track-list.js
  6049. */
  6050. /**
  6051. * Un-select all other {@link VideoTrack}s that are selected.
  6052. *
  6053. * @param {VideoTrackList} list
  6054. * list to work on
  6055. *
  6056. * @param { import('./video-track').default } track
  6057. * The track to skip
  6058. *
  6059. * @private
  6060. */
  6061. const disableOthers = function (list, track) {
  6062. for (let i = 0; i < list.length; i++) {
  6063. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6064. continue;
  6065. }
  6066. // another video track is enabled, disable it
  6067. list[i].selected = false;
  6068. }
  6069. };
  6070. /**
  6071. * The current list of {@link VideoTrack} for a video.
  6072. *
  6073. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  6074. * @extends TrackList
  6075. */
  6076. class VideoTrackList extends TrackList {
  6077. /**
  6078. * Create an instance of this class.
  6079. *
  6080. * @param {VideoTrack[]} [tracks=[]]
  6081. * A list of `VideoTrack` to instantiate the list with.
  6082. */
  6083. constructor(tracks = []) {
  6084. // make sure only 1 track is enabled
  6085. // sorted from last index to first index
  6086. for (let i = tracks.length - 1; i >= 0; i--) {
  6087. if (tracks[i].selected) {
  6088. disableOthers(tracks, tracks[i]);
  6089. break;
  6090. }
  6091. }
  6092. super(tracks);
  6093. this.changing_ = false;
  6094. /**
  6095. * @member {number} VideoTrackList#selectedIndex
  6096. * The current index of the selected {@link VideoTrack`}.
  6097. */
  6098. Object.defineProperty(this, 'selectedIndex', {
  6099. get() {
  6100. for (let i = 0; i < this.length; i++) {
  6101. if (this[i].selected) {
  6102. return i;
  6103. }
  6104. }
  6105. return -1;
  6106. },
  6107. set() {}
  6108. });
  6109. }
  6110. /**
  6111. * Add a {@link VideoTrack} to the `VideoTrackList`.
  6112. *
  6113. * @param { import('./video-track').default } track
  6114. * The VideoTrack to add to the list
  6115. *
  6116. * @fires TrackList#addtrack
  6117. */
  6118. addTrack(track) {
  6119. if (track.selected) {
  6120. disableOthers(this, track);
  6121. }
  6122. super.addTrack(track);
  6123. // native tracks don't have this
  6124. if (!track.addEventListener) {
  6125. return;
  6126. }
  6127. track.selectedChange_ = () => {
  6128. if (this.changing_) {
  6129. return;
  6130. }
  6131. this.changing_ = true;
  6132. disableOthers(this, track);
  6133. this.changing_ = false;
  6134. this.trigger('change');
  6135. };
  6136. /**
  6137. * @listens VideoTrack#selectedchange
  6138. * @fires TrackList#change
  6139. */
  6140. track.addEventListener('selectedchange', track.selectedChange_);
  6141. }
  6142. removeTrack(rtrack) {
  6143. super.removeTrack(rtrack);
  6144. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  6145. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  6146. rtrack.selectedChange_ = null;
  6147. }
  6148. }
  6149. }
  6150. /**
  6151. * @file text-track-list.js
  6152. */
  6153. /**
  6154. * The current list of {@link TextTrack} for a media file.
  6155. *
  6156. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6157. * @extends TrackList
  6158. */
  6159. class TextTrackList extends TrackList {
  6160. /**
  6161. * Add a {@link TextTrack} to the `TextTrackList`
  6162. *
  6163. * @param { import('./text-track').default } track
  6164. * The text track to add to the list.
  6165. *
  6166. * @fires TrackList#addtrack
  6167. */
  6168. addTrack(track) {
  6169. super.addTrack(track);
  6170. if (!this.queueChange_) {
  6171. this.queueChange_ = () => this.queueTrigger('change');
  6172. }
  6173. if (!this.triggerSelectedlanguagechange) {
  6174. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6175. }
  6176. /**
  6177. * @listens TextTrack#modechange
  6178. * @fires TrackList#change
  6179. */
  6180. track.addEventListener('modechange', this.queueChange_);
  6181. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6182. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6183. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6184. }
  6185. }
  6186. removeTrack(rtrack) {
  6187. super.removeTrack(rtrack);
  6188. // manually remove the event handlers we added
  6189. if (rtrack.removeEventListener) {
  6190. if (this.queueChange_) {
  6191. rtrack.removeEventListener('modechange', this.queueChange_);
  6192. }
  6193. if (this.selectedlanguagechange_) {
  6194. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6195. }
  6196. }
  6197. }
  6198. }
  6199. /**
  6200. * @file html-track-element-list.js
  6201. */
  6202. /**
  6203. * The current list of {@link HtmlTrackElement}s.
  6204. */
  6205. class HtmlTrackElementList {
  6206. /**
  6207. * Create an instance of this class.
  6208. *
  6209. * @param {HtmlTrackElement[]} [tracks=[]]
  6210. * A list of `HtmlTrackElement` to instantiate the list with.
  6211. */
  6212. constructor(trackElements = []) {
  6213. this.trackElements_ = [];
  6214. /**
  6215. * @memberof HtmlTrackElementList
  6216. * @member {number} length
  6217. * The current number of `Track`s in the this Trackist.
  6218. * @instance
  6219. */
  6220. Object.defineProperty(this, 'length', {
  6221. get() {
  6222. return this.trackElements_.length;
  6223. }
  6224. });
  6225. for (let i = 0, length = trackElements.length; i < length; i++) {
  6226. this.addTrackElement_(trackElements[i]);
  6227. }
  6228. }
  6229. /**
  6230. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6231. *
  6232. * @param {HtmlTrackElement} trackElement
  6233. * The track element to add to the list.
  6234. *
  6235. * @private
  6236. */
  6237. addTrackElement_(trackElement) {
  6238. const index = this.trackElements_.length;
  6239. if (!('' + index in this)) {
  6240. Object.defineProperty(this, index, {
  6241. get() {
  6242. return this.trackElements_[index];
  6243. }
  6244. });
  6245. }
  6246. // Do not add duplicate elements
  6247. if (this.trackElements_.indexOf(trackElement) === -1) {
  6248. this.trackElements_.push(trackElement);
  6249. }
  6250. }
  6251. /**
  6252. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6253. * {@link TextTrack}.
  6254. *
  6255. * @param {TextTrack} track
  6256. * The track associated with a track element.
  6257. *
  6258. * @return {HtmlTrackElement|undefined}
  6259. * The track element that was found or undefined.
  6260. *
  6261. * @private
  6262. */
  6263. getTrackElementByTrack_(track) {
  6264. let trackElement_;
  6265. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6266. if (track === this.trackElements_[i].track) {
  6267. trackElement_ = this.trackElements_[i];
  6268. break;
  6269. }
  6270. }
  6271. return trackElement_;
  6272. }
  6273. /**
  6274. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6275. *
  6276. * @param {HtmlTrackElement} trackElement
  6277. * The track element to remove from the list.
  6278. *
  6279. * @private
  6280. */
  6281. removeTrackElement_(trackElement) {
  6282. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6283. if (trackElement === this.trackElements_[i]) {
  6284. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6285. this.trackElements_[i].track.off();
  6286. }
  6287. if (typeof this.trackElements_[i].off === 'function') {
  6288. this.trackElements_[i].off();
  6289. }
  6290. this.trackElements_.splice(i, 1);
  6291. break;
  6292. }
  6293. }
  6294. }
  6295. }
  6296. /**
  6297. * @file text-track-cue-list.js
  6298. */
  6299. /**
  6300. * @typedef {Object} TextTrackCueList~TextTrackCue
  6301. *
  6302. * @property {string} id
  6303. * The unique id for this text track cue
  6304. *
  6305. * @property {number} startTime
  6306. * The start time for this text track cue
  6307. *
  6308. * @property {number} endTime
  6309. * The end time for this text track cue
  6310. *
  6311. * @property {boolean} pauseOnExit
  6312. * Pause when the end time is reached if true.
  6313. *
  6314. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6315. */
  6316. /**
  6317. * A List of TextTrackCues.
  6318. *
  6319. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6320. */
  6321. class TextTrackCueList {
  6322. /**
  6323. * Create an instance of this class..
  6324. *
  6325. * @param {Array} cues
  6326. * A list of cues to be initialized with
  6327. */
  6328. constructor(cues) {
  6329. TextTrackCueList.prototype.setCues_.call(this, cues);
  6330. /**
  6331. * @memberof TextTrackCueList
  6332. * @member {number} length
  6333. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6334. * @instance
  6335. */
  6336. Object.defineProperty(this, 'length', {
  6337. get() {
  6338. return this.length_;
  6339. }
  6340. });
  6341. }
  6342. /**
  6343. * A setter for cues in this list. Creates getters
  6344. * an an index for the cues.
  6345. *
  6346. * @param {Array} cues
  6347. * An array of cues to set
  6348. *
  6349. * @private
  6350. */
  6351. setCues_(cues) {
  6352. const oldLength = this.length || 0;
  6353. let i = 0;
  6354. const l = cues.length;
  6355. this.cues_ = cues;
  6356. this.length_ = cues.length;
  6357. const defineProp = function (index) {
  6358. if (!('' + index in this)) {
  6359. Object.defineProperty(this, '' + index, {
  6360. get() {
  6361. return this.cues_[index];
  6362. }
  6363. });
  6364. }
  6365. };
  6366. if (oldLength < l) {
  6367. i = oldLength;
  6368. for (; i < l; i++) {
  6369. defineProp.call(this, i);
  6370. }
  6371. }
  6372. }
  6373. /**
  6374. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6375. *
  6376. * @param {string} id
  6377. * The id of the cue that should be searched for.
  6378. *
  6379. * @return {TextTrackCueList~TextTrackCue|null}
  6380. * A single cue or null if none was found.
  6381. */
  6382. getCueById(id) {
  6383. let result = null;
  6384. for (let i = 0, l = this.length; i < l; i++) {
  6385. const cue = this[i];
  6386. if (cue.id === id) {
  6387. result = cue;
  6388. break;
  6389. }
  6390. }
  6391. return result;
  6392. }
  6393. }
  6394. /**
  6395. * @file track-kinds.js
  6396. */
  6397. /**
  6398. * All possible `VideoTrackKind`s
  6399. *
  6400. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6401. * @typedef VideoTrack~Kind
  6402. * @enum
  6403. */
  6404. const VideoTrackKind = {
  6405. alternative: 'alternative',
  6406. captions: 'captions',
  6407. main: 'main',
  6408. sign: 'sign',
  6409. subtitles: 'subtitles',
  6410. commentary: 'commentary'
  6411. };
  6412. /**
  6413. * All possible `AudioTrackKind`s
  6414. *
  6415. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6416. * @typedef AudioTrack~Kind
  6417. * @enum
  6418. */
  6419. const AudioTrackKind = {
  6420. 'alternative': 'alternative',
  6421. 'descriptions': 'descriptions',
  6422. 'main': 'main',
  6423. 'main-desc': 'main-desc',
  6424. 'translation': 'translation',
  6425. 'commentary': 'commentary'
  6426. };
  6427. /**
  6428. * All possible `TextTrackKind`s
  6429. *
  6430. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6431. * @typedef TextTrack~Kind
  6432. * @enum
  6433. */
  6434. const TextTrackKind = {
  6435. subtitles: 'subtitles',
  6436. captions: 'captions',
  6437. descriptions: 'descriptions',
  6438. chapters: 'chapters',
  6439. metadata: 'metadata'
  6440. };
  6441. /**
  6442. * All possible `TextTrackMode`s
  6443. *
  6444. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6445. * @typedef TextTrack~Mode
  6446. * @enum
  6447. */
  6448. const TextTrackMode = {
  6449. disabled: 'disabled',
  6450. hidden: 'hidden',
  6451. showing: 'showing'
  6452. };
  6453. /**
  6454. * @file track.js
  6455. */
  6456. /**
  6457. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6458. * {@link VideoTrack}, and {@link TextTrack}.
  6459. *
  6460. * > Note: This class should not be used directly
  6461. *
  6462. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6463. * @extends EventTarget
  6464. * @abstract
  6465. */
  6466. class Track extends EventTarget {
  6467. /**
  6468. * Create an instance of this class.
  6469. *
  6470. * @param {Object} [options={}]
  6471. * Object of option names and values
  6472. *
  6473. * @param {string} [options.kind='']
  6474. * A valid kind for the track type you are creating.
  6475. *
  6476. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6477. * A unique id for this AudioTrack.
  6478. *
  6479. * @param {string} [options.label='']
  6480. * The menu label for this track.
  6481. *
  6482. * @param {string} [options.language='']
  6483. * A valid two character language code.
  6484. *
  6485. * @abstract
  6486. */
  6487. constructor(options = {}) {
  6488. super();
  6489. const trackProps = {
  6490. id: options.id || 'vjs_track_' + newGUID(),
  6491. kind: options.kind || '',
  6492. language: options.language || ''
  6493. };
  6494. let label = options.label || '';
  6495. /**
  6496. * @memberof Track
  6497. * @member {string} id
  6498. * The id of this track. Cannot be changed after creation.
  6499. * @instance
  6500. *
  6501. * @readonly
  6502. */
  6503. /**
  6504. * @memberof Track
  6505. * @member {string} kind
  6506. * The kind of track that this is. Cannot be changed after creation.
  6507. * @instance
  6508. *
  6509. * @readonly
  6510. */
  6511. /**
  6512. * @memberof Track
  6513. * @member {string} language
  6514. * The two letter language code for this track. Cannot be changed after
  6515. * creation.
  6516. * @instance
  6517. *
  6518. * @readonly
  6519. */
  6520. for (const key in trackProps) {
  6521. Object.defineProperty(this, key, {
  6522. get() {
  6523. return trackProps[key];
  6524. },
  6525. set() {}
  6526. });
  6527. }
  6528. /**
  6529. * @memberof Track
  6530. * @member {string} label
  6531. * The label of this track. Cannot be changed after creation.
  6532. * @instance
  6533. *
  6534. * @fires Track#labelchange
  6535. */
  6536. Object.defineProperty(this, 'label', {
  6537. get() {
  6538. return label;
  6539. },
  6540. set(newLabel) {
  6541. if (newLabel !== label) {
  6542. label = newLabel;
  6543. /**
  6544. * An event that fires when label changes on this track.
  6545. *
  6546. * > Note: This is not part of the spec!
  6547. *
  6548. * @event Track#labelchange
  6549. * @type {Event}
  6550. */
  6551. this.trigger('labelchange');
  6552. }
  6553. }
  6554. });
  6555. }
  6556. }
  6557. /**
  6558. * @file url.js
  6559. * @module url
  6560. */
  6561. /**
  6562. * @typedef {Object} url:URLObject
  6563. *
  6564. * @property {string} protocol
  6565. * The protocol of the url that was parsed.
  6566. *
  6567. * @property {string} hostname
  6568. * The hostname of the url that was parsed.
  6569. *
  6570. * @property {string} port
  6571. * The port of the url that was parsed.
  6572. *
  6573. * @property {string} pathname
  6574. * The pathname of the url that was parsed.
  6575. *
  6576. * @property {string} search
  6577. * The search query of the url that was parsed.
  6578. *
  6579. * @property {string} hash
  6580. * The hash of the url that was parsed.
  6581. *
  6582. * @property {string} host
  6583. * The host of the url that was parsed.
  6584. */
  6585. /**
  6586. * Resolve and parse the elements of a URL.
  6587. *
  6588. * @function
  6589. * @param {String} url
  6590. * The url to parse
  6591. *
  6592. * @return {url:URLObject}
  6593. * An object of url details
  6594. */
  6595. const parseUrl = function (url) {
  6596. // This entire method can be replace with URL once we are able to drop IE11
  6597. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6598. // add the url to an anchor and let the browser parse the URL
  6599. const a = document.createElement('a');
  6600. a.href = url;
  6601. // Copy the specific URL properties to a new object
  6602. // This is also needed for IE because the anchor loses its
  6603. // properties when it's removed from the dom
  6604. const details = {};
  6605. for (let i = 0; i < props.length; i++) {
  6606. details[props[i]] = a[props[i]];
  6607. }
  6608. // IE adds the port to the host property unlike everyone else. If
  6609. // a port identifier is added for standard ports, strip it.
  6610. if (details.protocol === 'http:') {
  6611. details.host = details.host.replace(/:80$/, '');
  6612. }
  6613. if (details.protocol === 'https:') {
  6614. details.host = details.host.replace(/:443$/, '');
  6615. }
  6616. if (!details.protocol) {
  6617. details.protocol = window.location.protocol;
  6618. }
  6619. /* istanbul ignore if */
  6620. if (!details.host) {
  6621. details.host = window.location.host;
  6622. }
  6623. return details;
  6624. };
  6625. /**
  6626. * Get absolute version of relative URL.
  6627. *
  6628. * @function
  6629. * @param {string} url
  6630. * URL to make absolute
  6631. *
  6632. * @return {string}
  6633. * Absolute URL
  6634. *
  6635. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6636. */
  6637. const getAbsoluteURL = function (url) {
  6638. // Check if absolute URL
  6639. if (!url.match(/^https?:\/\//)) {
  6640. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6641. const a = document.createElement('a');
  6642. a.href = url;
  6643. url = a.href;
  6644. }
  6645. return url;
  6646. };
  6647. /**
  6648. * Returns the extension of the passed file name. It will return an empty string
  6649. * if passed an invalid path.
  6650. *
  6651. * @function
  6652. * @param {string} path
  6653. * The fileName path like '/path/to/file.mp4'
  6654. *
  6655. * @return {string}
  6656. * The extension in lower case or an empty string if no
  6657. * extension could be found.
  6658. */
  6659. const getFileExtension = function (path) {
  6660. if (typeof path === 'string') {
  6661. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6662. const pathParts = splitPathRe.exec(path);
  6663. if (pathParts) {
  6664. return pathParts.pop().toLowerCase();
  6665. }
  6666. }
  6667. return '';
  6668. };
  6669. /**
  6670. * Returns whether the url passed is a cross domain request or not.
  6671. *
  6672. * @function
  6673. * @param {string} url
  6674. * The url to check.
  6675. *
  6676. * @param {Object} [winLoc]
  6677. * the domain to check the url against, defaults to window.location
  6678. *
  6679. * @param {string} [winLoc.protocol]
  6680. * The window location protocol defaults to window.location.protocol
  6681. *
  6682. * @param {string} [winLoc.host]
  6683. * The window location host defaults to window.location.host
  6684. *
  6685. * @return {boolean}
  6686. * Whether it is a cross domain request or not.
  6687. */
  6688. const isCrossOrigin = function (url, winLoc = window.location) {
  6689. const urlInfo = parseUrl(url);
  6690. // IE8 protocol relative urls will return ':' for protocol
  6691. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6692. // Check if url is for another domain/origin
  6693. // IE8 doesn't know location.origin, so we won't rely on it here
  6694. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6695. return crossOrigin;
  6696. };
  6697. var Url = /*#__PURE__*/Object.freeze({
  6698. __proto__: null,
  6699. parseUrl: parseUrl,
  6700. getAbsoluteURL: getAbsoluteURL,
  6701. getFileExtension: getFileExtension,
  6702. isCrossOrigin: isCrossOrigin
  6703. });
  6704. var win;
  6705. if (typeof window !== "undefined") {
  6706. win = window;
  6707. } else if (typeof commonjsGlobal !== "undefined") {
  6708. win = commonjsGlobal;
  6709. } else if (typeof self !== "undefined") {
  6710. win = self;
  6711. } else {
  6712. win = {};
  6713. }
  6714. var window_1 = win;
  6715. var _extends_1 = createCommonjsModule(function (module) {
  6716. function _extends() {
  6717. module.exports = _extends = Object.assign ? Object.assign.bind() : function (target) {
  6718. for (var i = 1; i < arguments.length; i++) {
  6719. var source = arguments[i];
  6720. for (var key in source) {
  6721. if (Object.prototype.hasOwnProperty.call(source, key)) {
  6722. target[key] = source[key];
  6723. }
  6724. }
  6725. }
  6726. return target;
  6727. }, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6728. return _extends.apply(this, arguments);
  6729. }
  6730. module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
  6731. });
  6732. unwrapExports(_extends_1);
  6733. var isFunction_1 = isFunction;
  6734. var toString = Object.prototype.toString;
  6735. function isFunction(fn) {
  6736. if (!fn) {
  6737. return false;
  6738. }
  6739. var string = toString.call(fn);
  6740. return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && (
  6741. // IE8 and below
  6742. fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
  6743. }
  6744. var httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {
  6745. if (decodeResponseBody === void 0) {
  6746. decodeResponseBody = false;
  6747. }
  6748. return function (err, response, responseBody) {
  6749. // if the XHR failed, return that error
  6750. if (err) {
  6751. callback(err);
  6752. return;
  6753. } // if the HTTP status code is 4xx or 5xx, the request also failed
  6754. if (response.statusCode >= 400 && response.statusCode <= 599) {
  6755. var cause = responseBody;
  6756. if (decodeResponseBody) {
  6757. if (window_1.TextDecoder) {
  6758. var charset = getCharset(response.headers && response.headers['content-type']);
  6759. try {
  6760. cause = new TextDecoder(charset).decode(responseBody);
  6761. } catch (e) {}
  6762. } else {
  6763. cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
  6764. }
  6765. }
  6766. callback({
  6767. cause: cause
  6768. });
  6769. return;
  6770. } // otherwise, request succeeded
  6771. callback(null, responseBody);
  6772. };
  6773. };
  6774. function getCharset(contentTypeHeader) {
  6775. if (contentTypeHeader === void 0) {
  6776. contentTypeHeader = '';
  6777. }
  6778. return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {
  6779. var _contentType$split = contentType.split('='),
  6780. type = _contentType$split[0],
  6781. value = _contentType$split[1];
  6782. if (type.trim() === 'charset') {
  6783. return value.trim();
  6784. }
  6785. return charset;
  6786. }, 'utf-8');
  6787. }
  6788. var httpHandler = httpResponseHandler;
  6789. createXHR.httpHandler = httpHandler;
  6790. /**
  6791. * @license
  6792. * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
  6793. * Copyright (c) 2014 David Björklund
  6794. * Available under the MIT license
  6795. * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
  6796. */
  6797. var parseHeaders = function parseHeaders(headers) {
  6798. var result = {};
  6799. if (!headers) {
  6800. return result;
  6801. }
  6802. headers.trim().split('\n').forEach(function (row) {
  6803. var index = row.indexOf(':');
  6804. var key = row.slice(0, index).trim().toLowerCase();
  6805. var value = row.slice(index + 1).trim();
  6806. if (typeof result[key] === 'undefined') {
  6807. result[key] = value;
  6808. } else if (Array.isArray(result[key])) {
  6809. result[key].push(value);
  6810. } else {
  6811. result[key] = [result[key], value];
  6812. }
  6813. });
  6814. return result;
  6815. };
  6816. var lib = createXHR; // Allow use of default import syntax in TypeScript
  6817. var default_1 = createXHR;
  6818. createXHR.XMLHttpRequest = window_1.XMLHttpRequest || noop;
  6819. createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window_1.XDomainRequest;
  6820. forEachArray(["get", "put", "post", "patch", "head", "delete"], function (method) {
  6821. createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) {
  6822. options = initParams(uri, options, callback);
  6823. options.method = method.toUpperCase();
  6824. return _createXHR(options);
  6825. };
  6826. });
  6827. function forEachArray(array, iterator) {
  6828. for (var i = 0; i < array.length; i++) {
  6829. iterator(array[i]);
  6830. }
  6831. }
  6832. function isEmpty(obj) {
  6833. for (var i in obj) {
  6834. if (obj.hasOwnProperty(i)) return false;
  6835. }
  6836. return true;
  6837. }
  6838. function initParams(uri, options, callback) {
  6839. var params = uri;
  6840. if (isFunction_1(options)) {
  6841. callback = options;
  6842. if (typeof uri === "string") {
  6843. params = {
  6844. uri: uri
  6845. };
  6846. }
  6847. } else {
  6848. params = _extends_1({}, options, {
  6849. uri: uri
  6850. });
  6851. }
  6852. params.callback = callback;
  6853. return params;
  6854. }
  6855. function createXHR(uri, options, callback) {
  6856. options = initParams(uri, options, callback);
  6857. return _createXHR(options);
  6858. }
  6859. function _createXHR(options) {
  6860. if (typeof options.callback === "undefined") {
  6861. throw new Error("callback argument missing");
  6862. }
  6863. var called = false;
  6864. var callback = function cbOnce(err, response, body) {
  6865. if (!called) {
  6866. called = true;
  6867. options.callback(err, response, body);
  6868. }
  6869. };
  6870. function readystatechange() {
  6871. if (xhr.readyState === 4) {
  6872. setTimeout(loadFunc, 0);
  6873. }
  6874. }
  6875. function getBody() {
  6876. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  6877. var body = undefined;
  6878. if (xhr.response) {
  6879. body = xhr.response;
  6880. } else {
  6881. body = xhr.responseText || getXml(xhr);
  6882. }
  6883. if (isJson) {
  6884. try {
  6885. body = JSON.parse(body);
  6886. } catch (e) {}
  6887. }
  6888. return body;
  6889. }
  6890. function errorFunc(evt) {
  6891. clearTimeout(timeoutTimer);
  6892. if (!(evt instanceof Error)) {
  6893. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
  6894. }
  6895. evt.statusCode = 0;
  6896. return callback(evt, failureResponse);
  6897. } // will load the data & process the response in a special response object
  6898. function loadFunc() {
  6899. if (aborted) return;
  6900. var status;
  6901. clearTimeout(timeoutTimer);
  6902. if (options.useXDR && xhr.status === undefined) {
  6903. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  6904. status = 200;
  6905. } else {
  6906. status = xhr.status === 1223 ? 204 : xhr.status;
  6907. }
  6908. var response = failureResponse;
  6909. var err = null;
  6910. if (status !== 0) {
  6911. response = {
  6912. body: getBody(),
  6913. statusCode: status,
  6914. method: method,
  6915. headers: {},
  6916. url: uri,
  6917. rawRequest: xhr
  6918. };
  6919. if (xhr.getAllResponseHeaders) {
  6920. //remember xhr can in fact be XDR for CORS in IE
  6921. response.headers = parseHeaders(xhr.getAllResponseHeaders());
  6922. }
  6923. } else {
  6924. err = new Error("Internal XMLHttpRequest Error");
  6925. }
  6926. return callback(err, response, response.body);
  6927. }
  6928. var xhr = options.xhr || null;
  6929. if (!xhr) {
  6930. if (options.cors || options.useXDR) {
  6931. xhr = new createXHR.XDomainRequest();
  6932. } else {
  6933. xhr = new createXHR.XMLHttpRequest();
  6934. }
  6935. }
  6936. var key;
  6937. var aborted;
  6938. var uri = xhr.url = options.uri || options.url;
  6939. var method = xhr.method = options.method || "GET";
  6940. var body = options.body || options.data;
  6941. var headers = xhr.headers = options.headers || {};
  6942. var sync = !!options.sync;
  6943. var isJson = false;
  6944. var timeoutTimer;
  6945. var failureResponse = {
  6946. body: undefined,
  6947. headers: {},
  6948. statusCode: 0,
  6949. method: method,
  6950. url: uri,
  6951. rawRequest: xhr
  6952. };
  6953. if ("json" in options && options.json !== false) {
  6954. isJson = true;
  6955. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user
  6956. if (method !== "GET" && method !== "HEAD") {
  6957. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user
  6958. body = JSON.stringify(options.json === true ? body : options.json);
  6959. }
  6960. }
  6961. xhr.onreadystatechange = readystatechange;
  6962. xhr.onload = loadFunc;
  6963. xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.
  6964. xhr.onprogress = function () {// IE must die
  6965. };
  6966. xhr.onabort = function () {
  6967. aborted = true;
  6968. };
  6969. xhr.ontimeout = errorFunc;
  6970. xhr.open(method, uri, !sync, options.username, options.password); //has to be after open
  6971. if (!sync) {
  6972. xhr.withCredentials = !!options.withCredentials;
  6973. } // Cannot set timeout with sync request
  6974. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  6975. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  6976. if (!sync && options.timeout > 0) {
  6977. timeoutTimer = setTimeout(function () {
  6978. if (aborted) return;
  6979. aborted = true; //IE9 may still call readystatechange
  6980. xhr.abort("timeout");
  6981. var e = new Error("XMLHttpRequest timeout");
  6982. e.code = "ETIMEDOUT";
  6983. errorFunc(e);
  6984. }, options.timeout);
  6985. }
  6986. if (xhr.setRequestHeader) {
  6987. for (key in headers) {
  6988. if (headers.hasOwnProperty(key)) {
  6989. xhr.setRequestHeader(key, headers[key]);
  6990. }
  6991. }
  6992. } else if (options.headers && !isEmpty(options.headers)) {
  6993. throw new Error("Headers cannot be set on an XDomainRequest object");
  6994. }
  6995. if ("responseType" in options) {
  6996. xhr.responseType = options.responseType;
  6997. }
  6998. if ("beforeSend" in options && typeof options.beforeSend === "function") {
  6999. options.beforeSend(xhr);
  7000. } // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  7001. // XMLHttpRequest spec says to pass null as body to indicate no body
  7002. // See https://github.com/naugtur/xhr/issues/100.
  7003. xhr.send(body || null);
  7004. return xhr;
  7005. }
  7006. function getXml(xhr) {
  7007. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  7008. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  7009. try {
  7010. if (xhr.responseType === "document") {
  7011. return xhr.responseXML;
  7012. }
  7013. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
  7014. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  7015. return xhr.responseXML;
  7016. }
  7017. } catch (e) {}
  7018. return null;
  7019. }
  7020. function noop() {}
  7021. lib.default = default_1;
  7022. /**
  7023. * @file text-track.js
  7024. */
  7025. /**
  7026. * Takes a webvtt file contents and parses it into cues
  7027. *
  7028. * @param {string} srcContent
  7029. * webVTT file contents
  7030. *
  7031. * @param {TextTrack} track
  7032. * TextTrack to add cues to. Cues come from the srcContent.
  7033. *
  7034. * @private
  7035. */
  7036. const parseCues = function (srcContent, track) {
  7037. const parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  7038. const errors = [];
  7039. parser.oncue = function (cue) {
  7040. track.addCue(cue);
  7041. };
  7042. parser.onparsingerror = function (error) {
  7043. errors.push(error);
  7044. };
  7045. parser.onflush = function () {
  7046. track.trigger({
  7047. type: 'loadeddata',
  7048. target: track
  7049. });
  7050. };
  7051. parser.parse(srcContent);
  7052. if (errors.length > 0) {
  7053. if (window.console && window.console.groupCollapsed) {
  7054. window.console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  7055. }
  7056. errors.forEach(error => log.error(error));
  7057. if (window.console && window.console.groupEnd) {
  7058. window.console.groupEnd();
  7059. }
  7060. }
  7061. parser.flush();
  7062. };
  7063. /**
  7064. * Load a `TextTrack` from a specified url.
  7065. *
  7066. * @param {string} src
  7067. * Url to load track from.
  7068. *
  7069. * @param {TextTrack} track
  7070. * Track to add cues to. Comes from the content at the end of `url`.
  7071. *
  7072. * @private
  7073. */
  7074. const loadTrack = function (src, track) {
  7075. const opts = {
  7076. uri: src
  7077. };
  7078. const crossOrigin = isCrossOrigin(src);
  7079. if (crossOrigin) {
  7080. opts.cors = crossOrigin;
  7081. }
  7082. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  7083. if (withCredentials) {
  7084. opts.withCredentials = withCredentials;
  7085. }
  7086. lib(opts, bind_(this, function (err, response, responseBody) {
  7087. if (err) {
  7088. return log.error(err, response);
  7089. }
  7090. track.loaded_ = true;
  7091. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  7092. // NOTE: this is only used for the alt/video.novtt.js build
  7093. if (typeof window.WebVTT !== 'function') {
  7094. if (track.tech_) {
  7095. // to prevent use before define eslint error, we define loadHandler
  7096. // as a let here
  7097. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  7098. if (event.type === 'vttjserror') {
  7099. log.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  7100. return;
  7101. }
  7102. return parseCues(responseBody, track);
  7103. });
  7104. }
  7105. } else {
  7106. parseCues(responseBody, track);
  7107. }
  7108. }));
  7109. };
  7110. /**
  7111. * A representation of a single `TextTrack`.
  7112. *
  7113. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  7114. * @extends Track
  7115. */
  7116. class TextTrack extends Track {
  7117. /**
  7118. * Create an instance of this class.
  7119. *
  7120. * @param {Object} options={}
  7121. * Object of option names and values
  7122. *
  7123. * @param { import('../tech/tech').default } options.tech
  7124. * A reference to the tech that owns this TextTrack.
  7125. *
  7126. * @param {TextTrack~Kind} [options.kind='subtitles']
  7127. * A valid text track kind.
  7128. *
  7129. * @param {TextTrack~Mode} [options.mode='disabled']
  7130. * A valid text track mode.
  7131. *
  7132. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7133. * A unique id for this TextTrack.
  7134. *
  7135. * @param {string} [options.label='']
  7136. * The menu label for this track.
  7137. *
  7138. * @param {string} [options.language='']
  7139. * A valid two character language code.
  7140. *
  7141. * @param {string} [options.srclang='']
  7142. * A valid two character language code. An alternative, but deprioritized
  7143. * version of `options.language`
  7144. *
  7145. * @param {string} [options.src]
  7146. * A url to TextTrack cues.
  7147. *
  7148. * @param {boolean} [options.default]
  7149. * If this track should default to on or off.
  7150. */
  7151. constructor(options = {}) {
  7152. if (!options.tech) {
  7153. throw new Error('A tech was not provided.');
  7154. }
  7155. const settings = merge(options, {
  7156. kind: TextTrackKind[options.kind] || 'subtitles',
  7157. language: options.language || options.srclang || ''
  7158. });
  7159. let mode = TextTrackMode[settings.mode] || 'disabled';
  7160. const default_ = settings.default;
  7161. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  7162. mode = 'hidden';
  7163. }
  7164. super(settings);
  7165. this.tech_ = settings.tech;
  7166. this.cues_ = [];
  7167. this.activeCues_ = [];
  7168. this.preload_ = this.tech_.preloadTextTracks !== false;
  7169. const cues = new TextTrackCueList(this.cues_);
  7170. const activeCues = new TextTrackCueList(this.activeCues_);
  7171. let changed = false;
  7172. this.timeupdateHandler = bind_(this, function (event = {}) {
  7173. if (this.tech_.isDisposed()) {
  7174. return;
  7175. }
  7176. if (!this.tech_.isReady_) {
  7177. if (event.type !== 'timeupdate') {
  7178. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7179. }
  7180. return;
  7181. }
  7182. // Accessing this.activeCues for the side-effects of updating itself
  7183. // due to its nature as a getter function. Do not remove or cues will
  7184. // stop updating!
  7185. // Use the setter to prevent deletion from uglify (pure_getters rule)
  7186. this.activeCues = this.activeCues;
  7187. if (changed) {
  7188. this.trigger('cuechange');
  7189. changed = false;
  7190. }
  7191. if (event.type !== 'timeupdate') {
  7192. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7193. }
  7194. });
  7195. const disposeHandler = () => {
  7196. this.stopTracking();
  7197. };
  7198. this.tech_.one('dispose', disposeHandler);
  7199. if (mode !== 'disabled') {
  7200. this.startTracking();
  7201. }
  7202. Object.defineProperties(this, {
  7203. /**
  7204. * @memberof TextTrack
  7205. * @member {boolean} default
  7206. * If this track was set to be on or off by default. Cannot be changed after
  7207. * creation.
  7208. * @instance
  7209. *
  7210. * @readonly
  7211. */
  7212. default: {
  7213. get() {
  7214. return default_;
  7215. },
  7216. set() {}
  7217. },
  7218. /**
  7219. * @memberof TextTrack
  7220. * @member {string} mode
  7221. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  7222. * not be set if setting to an invalid mode.
  7223. * @instance
  7224. *
  7225. * @fires TextTrack#modechange
  7226. */
  7227. mode: {
  7228. get() {
  7229. return mode;
  7230. },
  7231. set(newMode) {
  7232. if (!TextTrackMode[newMode]) {
  7233. return;
  7234. }
  7235. if (mode === newMode) {
  7236. return;
  7237. }
  7238. mode = newMode;
  7239. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  7240. // On-demand load.
  7241. loadTrack(this.src, this);
  7242. }
  7243. this.stopTracking();
  7244. if (mode !== 'disabled') {
  7245. this.startTracking();
  7246. }
  7247. /**
  7248. * An event that fires when mode changes on this track. This allows
  7249. * the TextTrackList that holds this track to act accordingly.
  7250. *
  7251. * > Note: This is not part of the spec!
  7252. *
  7253. * @event TextTrack#modechange
  7254. * @type {Event}
  7255. */
  7256. this.trigger('modechange');
  7257. }
  7258. },
  7259. /**
  7260. * @memberof TextTrack
  7261. * @member {TextTrackCueList} cues
  7262. * The text track cue list for this TextTrack.
  7263. * @instance
  7264. */
  7265. cues: {
  7266. get() {
  7267. if (!this.loaded_) {
  7268. return null;
  7269. }
  7270. return cues;
  7271. },
  7272. set() {}
  7273. },
  7274. /**
  7275. * @memberof TextTrack
  7276. * @member {TextTrackCueList} activeCues
  7277. * The list text track cues that are currently active for this TextTrack.
  7278. * @instance
  7279. */
  7280. activeCues: {
  7281. get() {
  7282. if (!this.loaded_) {
  7283. return null;
  7284. }
  7285. // nothing to do
  7286. if (this.cues.length === 0) {
  7287. return activeCues;
  7288. }
  7289. const ct = this.tech_.currentTime();
  7290. const active = [];
  7291. for (let i = 0, l = this.cues.length; i < l; i++) {
  7292. const cue = this.cues[i];
  7293. if (cue.startTime <= ct && cue.endTime >= ct) {
  7294. active.push(cue);
  7295. }
  7296. }
  7297. changed = false;
  7298. if (active.length !== this.activeCues_.length) {
  7299. changed = true;
  7300. } else {
  7301. for (let i = 0; i < active.length; i++) {
  7302. if (this.activeCues_.indexOf(active[i]) === -1) {
  7303. changed = true;
  7304. }
  7305. }
  7306. }
  7307. this.activeCues_ = active;
  7308. activeCues.setCues_(this.activeCues_);
  7309. return activeCues;
  7310. },
  7311. // /!\ Keep this setter empty (see the timeupdate handler above)
  7312. set() {}
  7313. }
  7314. });
  7315. if (settings.src) {
  7316. this.src = settings.src;
  7317. if (!this.preload_) {
  7318. // Tracks will load on-demand.
  7319. // Act like we're loaded for other purposes.
  7320. this.loaded_ = true;
  7321. }
  7322. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  7323. loadTrack(this.src, this);
  7324. }
  7325. } else {
  7326. this.loaded_ = true;
  7327. }
  7328. }
  7329. startTracking() {
  7330. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  7331. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7332. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  7333. this.tech_.on('timeupdate', this.timeupdateHandler);
  7334. }
  7335. stopTracking() {
  7336. if (this.rvf_) {
  7337. this.tech_.cancelVideoFrameCallback(this.rvf_);
  7338. this.rvf_ = undefined;
  7339. }
  7340. this.tech_.off('timeupdate', this.timeupdateHandler);
  7341. }
  7342. /**
  7343. * Add a cue to the internal list of cues.
  7344. *
  7345. * @param {TextTrack~Cue} cue
  7346. * The cue to add to our internal list
  7347. */
  7348. addCue(originalCue) {
  7349. let cue = originalCue;
  7350. if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
  7351. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  7352. for (const prop in originalCue) {
  7353. if (!(prop in cue)) {
  7354. cue[prop] = originalCue[prop];
  7355. }
  7356. }
  7357. // make sure that `id` is copied over
  7358. cue.id = originalCue.id;
  7359. cue.originalCue_ = originalCue;
  7360. }
  7361. const tracks = this.tech_.textTracks();
  7362. for (let i = 0; i < tracks.length; i++) {
  7363. if (tracks[i] !== this) {
  7364. tracks[i].removeCue(cue);
  7365. }
  7366. }
  7367. this.cues_.push(cue);
  7368. this.cues.setCues_(this.cues_);
  7369. }
  7370. /**
  7371. * Remove a cue from our internal list
  7372. *
  7373. * @param {TextTrack~Cue} removeCue
  7374. * The cue to remove from our internal list
  7375. */
  7376. removeCue(removeCue) {
  7377. let i = this.cues_.length;
  7378. while (i--) {
  7379. const cue = this.cues_[i];
  7380. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  7381. this.cues_.splice(i, 1);
  7382. this.cues.setCues_(this.cues_);
  7383. break;
  7384. }
  7385. }
  7386. }
  7387. }
  7388. /**
  7389. * cuechange - One or more cues in the track have become active or stopped being active.
  7390. */
  7391. TextTrack.prototype.allowedEvents_ = {
  7392. cuechange: 'cuechange'
  7393. };
  7394. /**
  7395. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  7396. * only one `AudioTrack` in the list will be enabled at a time.
  7397. *
  7398. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  7399. * @extends Track
  7400. */
  7401. class AudioTrack extends Track {
  7402. /**
  7403. * Create an instance of this class.
  7404. *
  7405. * @param {Object} [options={}]
  7406. * Object of option names and values
  7407. *
  7408. * @param {AudioTrack~Kind} [options.kind='']
  7409. * A valid audio track kind
  7410. *
  7411. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7412. * A unique id for this AudioTrack.
  7413. *
  7414. * @param {string} [options.label='']
  7415. * The menu label for this track.
  7416. *
  7417. * @param {string} [options.language='']
  7418. * A valid two character language code.
  7419. *
  7420. * @param {boolean} [options.enabled]
  7421. * If this track is the one that is currently playing. If this track is part of
  7422. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  7423. */
  7424. constructor(options = {}) {
  7425. const settings = merge(options, {
  7426. kind: AudioTrackKind[options.kind] || ''
  7427. });
  7428. super(settings);
  7429. let enabled = false;
  7430. /**
  7431. * @memberof AudioTrack
  7432. * @member {boolean} enabled
  7433. * If this `AudioTrack` is enabled or not. When setting this will
  7434. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7435. * @instance
  7436. *
  7437. * @fires VideoTrack#selectedchange
  7438. */
  7439. Object.defineProperty(this, 'enabled', {
  7440. get() {
  7441. return enabled;
  7442. },
  7443. set(newEnabled) {
  7444. // an invalid or unchanged value
  7445. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7446. return;
  7447. }
  7448. enabled = newEnabled;
  7449. /**
  7450. * An event that fires when enabled changes on this track. This allows
  7451. * the AudioTrackList that holds this track to act accordingly.
  7452. *
  7453. * > Note: This is not part of the spec! Native tracks will do
  7454. * this internally without an event.
  7455. *
  7456. * @event AudioTrack#enabledchange
  7457. * @type {Event}
  7458. */
  7459. this.trigger('enabledchange');
  7460. }
  7461. });
  7462. // if the user sets this track to selected then
  7463. // set selected to that true value otherwise
  7464. // we keep it false
  7465. if (settings.enabled) {
  7466. this.enabled = settings.enabled;
  7467. }
  7468. this.loaded_ = true;
  7469. }
  7470. }
  7471. /**
  7472. * A representation of a single `VideoTrack`.
  7473. *
  7474. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7475. * @extends Track
  7476. */
  7477. class VideoTrack extends Track {
  7478. /**
  7479. * Create an instance of this class.
  7480. *
  7481. * @param {Object} [options={}]
  7482. * Object of option names and values
  7483. *
  7484. * @param {string} [options.kind='']
  7485. * A valid {@link VideoTrack~Kind}
  7486. *
  7487. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7488. * A unique id for this AudioTrack.
  7489. *
  7490. * @param {string} [options.label='']
  7491. * The menu label for this track.
  7492. *
  7493. * @param {string} [options.language='']
  7494. * A valid two character language code.
  7495. *
  7496. * @param {boolean} [options.selected]
  7497. * If this track is the one that is currently playing.
  7498. */
  7499. constructor(options = {}) {
  7500. const settings = merge(options, {
  7501. kind: VideoTrackKind[options.kind] || ''
  7502. });
  7503. super(settings);
  7504. let selected = false;
  7505. /**
  7506. * @memberof VideoTrack
  7507. * @member {boolean} selected
  7508. * If this `VideoTrack` is selected or not. When setting this will
  7509. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7510. * @instance
  7511. *
  7512. * @fires VideoTrack#selectedchange
  7513. */
  7514. Object.defineProperty(this, 'selected', {
  7515. get() {
  7516. return selected;
  7517. },
  7518. set(newSelected) {
  7519. // an invalid or unchanged value
  7520. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7521. return;
  7522. }
  7523. selected = newSelected;
  7524. /**
  7525. * An event that fires when selected changes on this track. This allows
  7526. * the VideoTrackList that holds this track to act accordingly.
  7527. *
  7528. * > Note: This is not part of the spec! Native tracks will do
  7529. * this internally without an event.
  7530. *
  7531. * @event VideoTrack#selectedchange
  7532. * @type {Event}
  7533. */
  7534. this.trigger('selectedchange');
  7535. }
  7536. });
  7537. // if the user sets this track to selected then
  7538. // set selected to that true value otherwise
  7539. // we keep it false
  7540. if (settings.selected) {
  7541. this.selected = settings.selected;
  7542. }
  7543. }
  7544. }
  7545. /**
  7546. * @file html-track-element.js
  7547. */
  7548. /**
  7549. * A single track represented in the DOM.
  7550. *
  7551. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7552. * @extends EventTarget
  7553. */
  7554. class HTMLTrackElement extends EventTarget {
  7555. /**
  7556. * Create an instance of this class.
  7557. *
  7558. * @param {Object} options={}
  7559. * Object of option names and values
  7560. *
  7561. * @param { import('../tech/tech').default } options.tech
  7562. * A reference to the tech that owns this HTMLTrackElement.
  7563. *
  7564. * @param {TextTrack~Kind} [options.kind='subtitles']
  7565. * A valid text track kind.
  7566. *
  7567. * @param {TextTrack~Mode} [options.mode='disabled']
  7568. * A valid text track mode.
  7569. *
  7570. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7571. * A unique id for this TextTrack.
  7572. *
  7573. * @param {string} [options.label='']
  7574. * The menu label for this track.
  7575. *
  7576. * @param {string} [options.language='']
  7577. * A valid two character language code.
  7578. *
  7579. * @param {string} [options.srclang='']
  7580. * A valid two character language code. An alternative, but deprioritized
  7581. * version of `options.language`
  7582. *
  7583. * @param {string} [options.src]
  7584. * A url to TextTrack cues.
  7585. *
  7586. * @param {boolean} [options.default]
  7587. * If this track should default to on or off.
  7588. */
  7589. constructor(options = {}) {
  7590. super();
  7591. let readyState;
  7592. const track = new TextTrack(options);
  7593. this.kind = track.kind;
  7594. this.src = track.src;
  7595. this.srclang = track.language;
  7596. this.label = track.label;
  7597. this.default = track.default;
  7598. Object.defineProperties(this, {
  7599. /**
  7600. * @memberof HTMLTrackElement
  7601. * @member {HTMLTrackElement~ReadyState} readyState
  7602. * The current ready state of the track element.
  7603. * @instance
  7604. */
  7605. readyState: {
  7606. get() {
  7607. return readyState;
  7608. }
  7609. },
  7610. /**
  7611. * @memberof HTMLTrackElement
  7612. * @member {TextTrack} track
  7613. * The underlying TextTrack object.
  7614. * @instance
  7615. *
  7616. */
  7617. track: {
  7618. get() {
  7619. return track;
  7620. }
  7621. }
  7622. });
  7623. readyState = HTMLTrackElement.NONE;
  7624. /**
  7625. * @listens TextTrack#loadeddata
  7626. * @fires HTMLTrackElement#load
  7627. */
  7628. track.addEventListener('loadeddata', () => {
  7629. readyState = HTMLTrackElement.LOADED;
  7630. this.trigger({
  7631. type: 'load',
  7632. target: this
  7633. });
  7634. });
  7635. }
  7636. }
  7637. HTMLTrackElement.prototype.allowedEvents_ = {
  7638. load: 'load'
  7639. };
  7640. /**
  7641. * The text track not loaded state.
  7642. *
  7643. * @type {number}
  7644. * @static
  7645. */
  7646. HTMLTrackElement.NONE = 0;
  7647. /**
  7648. * The text track loading state.
  7649. *
  7650. * @type {number}
  7651. * @static
  7652. */
  7653. HTMLTrackElement.LOADING = 1;
  7654. /**
  7655. * The text track loaded state.
  7656. *
  7657. * @type {number}
  7658. * @static
  7659. */
  7660. HTMLTrackElement.LOADED = 2;
  7661. /**
  7662. * The text track failed to load state.
  7663. *
  7664. * @type {number}
  7665. * @static
  7666. */
  7667. HTMLTrackElement.ERROR = 3;
  7668. /*
  7669. * This file contains all track properties that are used in
  7670. * player.js, tech.js, html5.js and possibly other techs in the future.
  7671. */
  7672. const NORMAL = {
  7673. audio: {
  7674. ListClass: AudioTrackList,
  7675. TrackClass: AudioTrack,
  7676. capitalName: 'Audio'
  7677. },
  7678. video: {
  7679. ListClass: VideoTrackList,
  7680. TrackClass: VideoTrack,
  7681. capitalName: 'Video'
  7682. },
  7683. text: {
  7684. ListClass: TextTrackList,
  7685. TrackClass: TextTrack,
  7686. capitalName: 'Text'
  7687. }
  7688. };
  7689. Object.keys(NORMAL).forEach(function (type) {
  7690. NORMAL[type].getterName = `${type}Tracks`;
  7691. NORMAL[type].privateName = `${type}Tracks_`;
  7692. });
  7693. const REMOTE = {
  7694. remoteText: {
  7695. ListClass: TextTrackList,
  7696. TrackClass: TextTrack,
  7697. capitalName: 'RemoteText',
  7698. getterName: 'remoteTextTracks',
  7699. privateName: 'remoteTextTracks_'
  7700. },
  7701. remoteTextEl: {
  7702. ListClass: HtmlTrackElementList,
  7703. TrackClass: HTMLTrackElement,
  7704. capitalName: 'RemoteTextTrackEls',
  7705. getterName: 'remoteTextTrackEls',
  7706. privateName: 'remoteTextTrackEls_'
  7707. }
  7708. };
  7709. const ALL = Object.assign({}, NORMAL, REMOTE);
  7710. REMOTE.names = Object.keys(REMOTE);
  7711. NORMAL.names = Object.keys(NORMAL);
  7712. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7713. var minDoc = {};
  7714. var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : {};
  7715. var doccy;
  7716. if (typeof document !== 'undefined') {
  7717. doccy = document;
  7718. } else {
  7719. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  7720. if (!doccy) {
  7721. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  7722. }
  7723. }
  7724. var document_1 = doccy;
  7725. /**
  7726. * Copyright 2013 vtt.js Contributors
  7727. *
  7728. * Licensed under the Apache License, Version 2.0 (the "License");
  7729. * you may not use this file except in compliance with the License.
  7730. * You may obtain a copy of the License at
  7731. *
  7732. * http://www.apache.org/licenses/LICENSE-2.0
  7733. *
  7734. * Unless required by applicable law or agreed to in writing, software
  7735. * distributed under the License is distributed on an "AS IS" BASIS,
  7736. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7737. * See the License for the specific language governing permissions and
  7738. * limitations under the License.
  7739. */
  7740. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  7741. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  7742. var _objCreate = Object.create || function () {
  7743. function F() {}
  7744. return function (o) {
  7745. if (arguments.length !== 1) {
  7746. throw new Error('Object.create shim only accepts one parameter.');
  7747. }
  7748. F.prototype = o;
  7749. return new F();
  7750. };
  7751. }();
  7752. // Creates a new ParserError object from an errorData object. The errorData
  7753. // object should have default code and message properties. The default message
  7754. // property can be overriden by passing in a message parameter.
  7755. // See ParsingError.Errors below for acceptable errors.
  7756. function ParsingError(errorData, message) {
  7757. this.name = "ParsingError";
  7758. this.code = errorData.code;
  7759. this.message = message || errorData.message;
  7760. }
  7761. ParsingError.prototype = _objCreate(Error.prototype);
  7762. ParsingError.prototype.constructor = ParsingError;
  7763. // ParsingError metadata for acceptable ParsingErrors.
  7764. ParsingError.Errors = {
  7765. BadSignature: {
  7766. code: 0,
  7767. message: "Malformed WebVTT signature."
  7768. },
  7769. BadTimeStamp: {
  7770. code: 1,
  7771. message: "Malformed time stamp."
  7772. }
  7773. };
  7774. // Try to parse input as a time stamp.
  7775. function parseTimeStamp(input) {
  7776. function computeSeconds(h, m, s, f) {
  7777. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  7778. }
  7779. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  7780. if (!m) {
  7781. return null;
  7782. }
  7783. if (m[3]) {
  7784. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  7785. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  7786. } else if (m[1] > 59) {
  7787. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  7788. // First position is hours as it's over 59.
  7789. return computeSeconds(m[1], m[2], 0, m[4]);
  7790. } else {
  7791. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  7792. return computeSeconds(0, m[1], m[2], m[4]);
  7793. }
  7794. }
  7795. // A settings object holds key/value pairs and will ignore anything but the first
  7796. // assignment to a specific key.
  7797. function Settings() {
  7798. this.values = _objCreate(null);
  7799. }
  7800. Settings.prototype = {
  7801. // Only accept the first assignment to any key.
  7802. set: function (k, v) {
  7803. if (!this.get(k) && v !== "") {
  7804. this.values[k] = v;
  7805. }
  7806. },
  7807. // Return the value for a key, or a default value.
  7808. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  7809. // a number of possible default values as properties where 'defaultKey' is
  7810. // the key of the property that will be chosen; otherwise it's assumed to be
  7811. // a single value.
  7812. get: function (k, dflt, defaultKey) {
  7813. if (defaultKey) {
  7814. return this.has(k) ? this.values[k] : dflt[defaultKey];
  7815. }
  7816. return this.has(k) ? this.values[k] : dflt;
  7817. },
  7818. // Check whether we have a value for a key.
  7819. has: function (k) {
  7820. return k in this.values;
  7821. },
  7822. // Accept a setting if its one of the given alternatives.
  7823. alt: function (k, v, a) {
  7824. for (var n = 0; n < a.length; ++n) {
  7825. if (v === a[n]) {
  7826. this.set(k, v);
  7827. break;
  7828. }
  7829. }
  7830. },
  7831. // Accept a setting if its a valid (signed) integer.
  7832. integer: function (k, v) {
  7833. if (/^-?\d+$/.test(v)) {
  7834. // integer
  7835. this.set(k, parseInt(v, 10));
  7836. }
  7837. },
  7838. // Accept a setting if its a valid percentage.
  7839. percent: function (k, v) {
  7840. if (v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  7841. v = parseFloat(v);
  7842. if (v >= 0 && v <= 100) {
  7843. this.set(k, v);
  7844. return true;
  7845. }
  7846. }
  7847. return false;
  7848. }
  7849. };
  7850. // Helper function to parse input into groups separated by 'groupDelim', and
  7851. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  7852. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  7853. var groups = groupDelim ? input.split(groupDelim) : [input];
  7854. for (var i in groups) {
  7855. if (typeof groups[i] !== "string") {
  7856. continue;
  7857. }
  7858. var kv = groups[i].split(keyValueDelim);
  7859. if (kv.length !== 2) {
  7860. continue;
  7861. }
  7862. var k = kv[0].trim();
  7863. var v = kv[1].trim();
  7864. callback(k, v);
  7865. }
  7866. }
  7867. function parseCue(input, cue, regionList) {
  7868. // Remember the original input if we need to throw an error.
  7869. var oInput = input;
  7870. // 4.1 WebVTT timestamp
  7871. function consumeTimeStamp() {
  7872. var ts = parseTimeStamp(input);
  7873. if (ts === null) {
  7874. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput);
  7875. }
  7876. // Remove time stamp from input.
  7877. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  7878. return ts;
  7879. }
  7880. // 4.4.2 WebVTT cue settings
  7881. function consumeCueSettings(input, cue) {
  7882. var settings = new Settings();
  7883. parseOptions(input, function (k, v) {
  7884. switch (k) {
  7885. case "region":
  7886. // Find the last region we parsed with the same region id.
  7887. for (var i = regionList.length - 1; i >= 0; i--) {
  7888. if (regionList[i].id === v) {
  7889. settings.set(k, regionList[i].region);
  7890. break;
  7891. }
  7892. }
  7893. break;
  7894. case "vertical":
  7895. settings.alt(k, v, ["rl", "lr"]);
  7896. break;
  7897. case "line":
  7898. var vals = v.split(","),
  7899. vals0 = vals[0];
  7900. settings.integer(k, vals0);
  7901. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  7902. settings.alt(k, vals0, ["auto"]);
  7903. if (vals.length === 2) {
  7904. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  7905. }
  7906. break;
  7907. case "position":
  7908. vals = v.split(",");
  7909. settings.percent(k, vals[0]);
  7910. if (vals.length === 2) {
  7911. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  7912. }
  7913. break;
  7914. case "size":
  7915. settings.percent(k, v);
  7916. break;
  7917. case "align":
  7918. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  7919. break;
  7920. }
  7921. }, /:/, /\s/);
  7922. // Apply default values for any missing fields.
  7923. cue.region = settings.get("region", null);
  7924. cue.vertical = settings.get("vertical", "");
  7925. try {
  7926. cue.line = settings.get("line", "auto");
  7927. } catch (e) {}
  7928. cue.lineAlign = settings.get("lineAlign", "start");
  7929. cue.snapToLines = settings.get("snapToLines", true);
  7930. cue.size = settings.get("size", 100);
  7931. // Safari still uses the old middle value and won't accept center
  7932. try {
  7933. cue.align = settings.get("align", "center");
  7934. } catch (e) {
  7935. cue.align = settings.get("align", "middle");
  7936. }
  7937. try {
  7938. cue.position = settings.get("position", "auto");
  7939. } catch (e) {
  7940. cue.position = settings.get("position", {
  7941. start: 0,
  7942. left: 0,
  7943. center: 50,
  7944. middle: 50,
  7945. end: 100,
  7946. right: 100
  7947. }, cue.align);
  7948. }
  7949. cue.positionAlign = settings.get("positionAlign", {
  7950. start: "start",
  7951. left: "start",
  7952. center: "center",
  7953. middle: "center",
  7954. end: "end",
  7955. right: "end"
  7956. }, cue.align);
  7957. }
  7958. function skipWhitespace() {
  7959. input = input.replace(/^\s+/, "");
  7960. }
  7961. // 4.1 WebVTT cue timings.
  7962. skipWhitespace();
  7963. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  7964. skipWhitespace();
  7965. if (input.substr(0, 3) !== "-->") {
  7966. // (3) next characters must match "-->"
  7967. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  7968. }
  7969. input = input.substr(3);
  7970. skipWhitespace();
  7971. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  7972. // 4.1 WebVTT cue settings list.
  7973. skipWhitespace();
  7974. consumeCueSettings(input, cue);
  7975. }
  7976. // When evaluating this file as part of a Webpack bundle for server
  7977. // side rendering, `document` is an empty object.
  7978. var TEXTAREA_ELEMENT = document_1.createElement && document_1.createElement("textarea");
  7979. var TAG_NAME = {
  7980. c: "span",
  7981. i: "i",
  7982. b: "b",
  7983. u: "u",
  7984. ruby: "ruby",
  7985. rt: "rt",
  7986. v: "span",
  7987. lang: "span"
  7988. };
  7989. // 5.1 default text color
  7990. // 5.2 default text background color is equivalent to text color with bg_ prefix
  7991. var DEFAULT_COLOR_CLASS = {
  7992. white: 'rgba(255,255,255,1)',
  7993. lime: 'rgba(0,255,0,1)',
  7994. cyan: 'rgba(0,255,255,1)',
  7995. red: 'rgba(255,0,0,1)',
  7996. yellow: 'rgba(255,255,0,1)',
  7997. magenta: 'rgba(255,0,255,1)',
  7998. blue: 'rgba(0,0,255,1)',
  7999. black: 'rgba(0,0,0,1)'
  8000. };
  8001. var TAG_ANNOTATION = {
  8002. v: "title",
  8003. lang: "lang"
  8004. };
  8005. var NEEDS_PARENT = {
  8006. rt: "ruby"
  8007. };
  8008. // Parse content into a document fragment.
  8009. function parseContent(window, input) {
  8010. function nextToken() {
  8011. // Check for end-of-string.
  8012. if (!input) {
  8013. return null;
  8014. }
  8015. // Consume 'n' characters from the input.
  8016. function consume(result) {
  8017. input = input.substr(result.length);
  8018. return result;
  8019. }
  8020. var m = input.match(/^([^<]*)(<[^>]*>?)?/);
  8021. // If there is some text before the next tag, return it, otherwise return
  8022. // the tag.
  8023. return consume(m[1] ? m[1] : m[2]);
  8024. }
  8025. function unescape(s) {
  8026. TEXTAREA_ELEMENT.innerHTML = s;
  8027. s = TEXTAREA_ELEMENT.textContent;
  8028. TEXTAREA_ELEMENT.textContent = "";
  8029. return s;
  8030. }
  8031. function shouldAdd(current, element) {
  8032. return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName;
  8033. }
  8034. // Create an element for this tag.
  8035. function createElement(type, annotation) {
  8036. var tagName = TAG_NAME[type];
  8037. if (!tagName) {
  8038. return null;
  8039. }
  8040. var element = window.document.createElement(tagName);
  8041. var name = TAG_ANNOTATION[type];
  8042. if (name && annotation) {
  8043. element[name] = annotation.trim();
  8044. }
  8045. return element;
  8046. }
  8047. var rootDiv = window.document.createElement("div"),
  8048. current = rootDiv,
  8049. t,
  8050. tagStack = [];
  8051. while ((t = nextToken()) !== null) {
  8052. if (t[0] === '<') {
  8053. if (t[1] === "/") {
  8054. // If the closing tag matches, move back up to the parent node.
  8055. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  8056. tagStack.pop();
  8057. current = current.parentNode;
  8058. }
  8059. // Otherwise just ignore the end tag.
  8060. continue;
  8061. }
  8062. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  8063. var node;
  8064. if (ts) {
  8065. // Timestamps are lead nodes as well.
  8066. node = window.document.createProcessingInstruction("timestamp", ts);
  8067. current.appendChild(node);
  8068. continue;
  8069. }
  8070. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/);
  8071. // If we can't parse the tag, skip to the next tag.
  8072. if (!m) {
  8073. continue;
  8074. }
  8075. // Try to construct an element, and ignore the tag if we couldn't.
  8076. node = createElement(m[1], m[3]);
  8077. if (!node) {
  8078. continue;
  8079. }
  8080. // Determine if the tag should be added based on the context of where it
  8081. // is placed in the cuetext.
  8082. if (!shouldAdd(current, node)) {
  8083. continue;
  8084. }
  8085. // Set the class list (as a list of classes, separated by space).
  8086. if (m[2]) {
  8087. var classes = m[2].split('.');
  8088. classes.forEach(function (cl) {
  8089. var bgColor = /^bg_/.test(cl);
  8090. // slice out `bg_` if it's a background color
  8091. var colorName = bgColor ? cl.slice(3) : cl;
  8092. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  8093. var propName = bgColor ? 'background-color' : 'color';
  8094. var propValue = DEFAULT_COLOR_CLASS[colorName];
  8095. node.style[propName] = propValue;
  8096. }
  8097. });
  8098. node.className = classes.join(' ');
  8099. }
  8100. // Append the node to the current node, and enter the scope of the new
  8101. // node.
  8102. tagStack.push(m[1]);
  8103. current.appendChild(node);
  8104. current = node;
  8105. continue;
  8106. }
  8107. // Text nodes are leaf nodes.
  8108. current.appendChild(window.document.createTextNode(unescape(t)));
  8109. }
  8110. return rootDiv;
  8111. }
  8112. // This is a list of all the Unicode characters that have a strong
  8113. // right-to-left category. What this means is that these characters are
  8114. // written right-to-left for sure. It was generated by pulling all the strong
  8115. // right-to-left characters out of the Unicode data table. That table can
  8116. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  8117. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6], [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d], [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6], [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5], [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815], [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858], [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f], [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c], [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1], [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc], [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808], [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855], [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f], [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13], [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58], [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72], [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f], [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32], [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42], [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f], [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59], [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62], [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77], [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b], [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  8118. function isStrongRTLChar(charCode) {
  8119. for (var i = 0; i < strongRTLRanges.length; i++) {
  8120. var currentRange = strongRTLRanges[i];
  8121. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  8122. return true;
  8123. }
  8124. }
  8125. return false;
  8126. }
  8127. function determineBidi(cueDiv) {
  8128. var nodeStack = [],
  8129. text = "",
  8130. charCode;
  8131. if (!cueDiv || !cueDiv.childNodes) {
  8132. return "ltr";
  8133. }
  8134. function pushNodes(nodeStack, node) {
  8135. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  8136. nodeStack.push(node.childNodes[i]);
  8137. }
  8138. }
  8139. function nextTextNode(nodeStack) {
  8140. if (!nodeStack || !nodeStack.length) {
  8141. return null;
  8142. }
  8143. var node = nodeStack.pop(),
  8144. text = node.textContent || node.innerText;
  8145. if (text) {
  8146. // TODO: This should match all unicode type B characters (paragraph
  8147. // separator characters). See issue #115.
  8148. var m = text.match(/^.*(\n|\r)/);
  8149. if (m) {
  8150. nodeStack.length = 0;
  8151. return m[0];
  8152. }
  8153. return text;
  8154. }
  8155. if (node.tagName === "ruby") {
  8156. return nextTextNode(nodeStack);
  8157. }
  8158. if (node.childNodes) {
  8159. pushNodes(nodeStack, node);
  8160. return nextTextNode(nodeStack);
  8161. }
  8162. }
  8163. pushNodes(nodeStack, cueDiv);
  8164. while (text = nextTextNode(nodeStack)) {
  8165. for (var i = 0; i < text.length; i++) {
  8166. charCode = text.charCodeAt(i);
  8167. if (isStrongRTLChar(charCode)) {
  8168. return "rtl";
  8169. }
  8170. }
  8171. }
  8172. return "ltr";
  8173. }
  8174. function computeLinePos(cue) {
  8175. if (typeof cue.line === "number" && (cue.snapToLines || cue.line >= 0 && cue.line <= 100)) {
  8176. return cue.line;
  8177. }
  8178. if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) {
  8179. return -1;
  8180. }
  8181. var track = cue.track,
  8182. trackList = track.textTrackList,
  8183. count = 0;
  8184. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  8185. if (trackList[i].mode === "showing") {
  8186. count++;
  8187. }
  8188. }
  8189. return ++count * -1;
  8190. }
  8191. function StyleBox() {}
  8192. // Apply styles to a div. If there is no div passed then it defaults to the
  8193. // div on 'this'.
  8194. StyleBox.prototype.applyStyles = function (styles, div) {
  8195. div = div || this.div;
  8196. for (var prop in styles) {
  8197. if (styles.hasOwnProperty(prop)) {
  8198. div.style[prop] = styles[prop];
  8199. }
  8200. }
  8201. };
  8202. StyleBox.prototype.formatStyle = function (val, unit) {
  8203. return val === 0 ? 0 : val + unit;
  8204. };
  8205. // Constructs the computed display state of the cue (a div). Places the div
  8206. // into the overlay which should be a block level element (usually a div).
  8207. function CueStyleBox(window, cue, styleOptions) {
  8208. StyleBox.call(this);
  8209. this.cue = cue;
  8210. // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  8211. // have inline positioning and will function as the cue background box.
  8212. this.cueDiv = parseContent(window, cue.text);
  8213. var styles = {
  8214. color: "rgba(255, 255, 255, 1)",
  8215. backgroundColor: "rgba(0, 0, 0, 0.8)",
  8216. position: "relative",
  8217. left: 0,
  8218. right: 0,
  8219. top: 0,
  8220. bottom: 0,
  8221. display: "inline",
  8222. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8223. unicodeBidi: "plaintext"
  8224. };
  8225. this.applyStyles(styles, this.cueDiv);
  8226. // Create an absolutely positioned div that will be used to position the cue
  8227. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  8228. // mirrors of them except middle instead of center on Safari.
  8229. this.div = window.document.createElement("div");
  8230. styles = {
  8231. direction: determineBidi(this.cueDiv),
  8232. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8233. unicodeBidi: "plaintext",
  8234. textAlign: cue.align === "middle" ? "center" : cue.align,
  8235. font: styleOptions.font,
  8236. whiteSpace: "pre-line",
  8237. position: "absolute"
  8238. };
  8239. this.applyStyles(styles);
  8240. this.div.appendChild(this.cueDiv);
  8241. // Calculate the distance from the reference edge of the viewport to the text
  8242. // position of the cue box. The reference edge will be resolved later when
  8243. // the box orientation styles are applied.
  8244. var textPos = 0;
  8245. switch (cue.positionAlign) {
  8246. case "start":
  8247. textPos = cue.position;
  8248. break;
  8249. case "center":
  8250. textPos = cue.position - cue.size / 2;
  8251. break;
  8252. case "end":
  8253. textPos = cue.position - cue.size;
  8254. break;
  8255. }
  8256. // Horizontal box orientation; textPos is the distance from the left edge of the
  8257. // area to the left edge of the box and cue.size is the distance extending to
  8258. // the right from there.
  8259. if (cue.vertical === "") {
  8260. this.applyStyles({
  8261. left: this.formatStyle(textPos, "%"),
  8262. width: this.formatStyle(cue.size, "%")
  8263. });
  8264. // Vertical box orientation; textPos is the distance from the top edge of the
  8265. // area to the top edge of the box and cue.size is the height extending
  8266. // downwards from there.
  8267. } else {
  8268. this.applyStyles({
  8269. top: this.formatStyle(textPos, "%"),
  8270. height: this.formatStyle(cue.size, "%")
  8271. });
  8272. }
  8273. this.move = function (box) {
  8274. this.applyStyles({
  8275. top: this.formatStyle(box.top, "px"),
  8276. bottom: this.formatStyle(box.bottom, "px"),
  8277. left: this.formatStyle(box.left, "px"),
  8278. right: this.formatStyle(box.right, "px"),
  8279. height: this.formatStyle(box.height, "px"),
  8280. width: this.formatStyle(box.width, "px")
  8281. });
  8282. };
  8283. }
  8284. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  8285. CueStyleBox.prototype.constructor = CueStyleBox;
  8286. // Represents the co-ordinates of an Element in a way that we can easily
  8287. // compute things with such as if it overlaps or intersects with another Element.
  8288. // Can initialize it with either a StyleBox or another BoxPosition.
  8289. function BoxPosition(obj) {
  8290. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  8291. // was passed in and we need to copy the results of 'getBoundingClientRect'
  8292. // as the object returned is readonly. All co-ordinate values are in reference
  8293. // to the viewport origin (top left).
  8294. var lh, height, width, top;
  8295. if (obj.div) {
  8296. height = obj.div.offsetHeight;
  8297. width = obj.div.offsetWidth;
  8298. top = obj.div.offsetTop;
  8299. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects();
  8300. obj = obj.div.getBoundingClientRect();
  8301. // In certain cases the outter div will be slightly larger then the sum of
  8302. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  8303. // In this case we should get the average line height and use that. This will
  8304. // result in the desired behaviour.
  8305. lh = rects ? Math.max(rects[0] && rects[0].height || 0, obj.height / rects.length) : 0;
  8306. }
  8307. this.left = obj.left;
  8308. this.right = obj.right;
  8309. this.top = obj.top || top;
  8310. this.height = obj.height || height;
  8311. this.bottom = obj.bottom || top + (obj.height || height);
  8312. this.width = obj.width || width;
  8313. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  8314. }
  8315. // Move the box along a particular axis. Optionally pass in an amount to move
  8316. // the box. If no amount is passed then the default is the line height of the
  8317. // box.
  8318. BoxPosition.prototype.move = function (axis, toMove) {
  8319. toMove = toMove !== undefined ? toMove : this.lineHeight;
  8320. switch (axis) {
  8321. case "+x":
  8322. this.left += toMove;
  8323. this.right += toMove;
  8324. break;
  8325. case "-x":
  8326. this.left -= toMove;
  8327. this.right -= toMove;
  8328. break;
  8329. case "+y":
  8330. this.top += toMove;
  8331. this.bottom += toMove;
  8332. break;
  8333. case "-y":
  8334. this.top -= toMove;
  8335. this.bottom -= toMove;
  8336. break;
  8337. }
  8338. };
  8339. // Check if this box overlaps another box, b2.
  8340. BoxPosition.prototype.overlaps = function (b2) {
  8341. return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top;
  8342. };
  8343. // Check if this box overlaps any other boxes in boxes.
  8344. BoxPosition.prototype.overlapsAny = function (boxes) {
  8345. for (var i = 0; i < boxes.length; i++) {
  8346. if (this.overlaps(boxes[i])) {
  8347. return true;
  8348. }
  8349. }
  8350. return false;
  8351. };
  8352. // Check if this box is within another box.
  8353. BoxPosition.prototype.within = function (container) {
  8354. return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right;
  8355. };
  8356. // Check if this box is entirely within the container or it is overlapping
  8357. // on the edge opposite of the axis direction passed. For example, if "+x" is
  8358. // passed and the box is overlapping on the left edge of the container, then
  8359. // return true.
  8360. BoxPosition.prototype.overlapsOppositeAxis = function (container, axis) {
  8361. switch (axis) {
  8362. case "+x":
  8363. return this.left < container.left;
  8364. case "-x":
  8365. return this.right > container.right;
  8366. case "+y":
  8367. return this.top < container.top;
  8368. case "-y":
  8369. return this.bottom > container.bottom;
  8370. }
  8371. };
  8372. // Find the percentage of the area that this box is overlapping with another
  8373. // box.
  8374. BoxPosition.prototype.intersectPercentage = function (b2) {
  8375. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  8376. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  8377. intersectArea = x * y;
  8378. return intersectArea / (this.height * this.width);
  8379. };
  8380. // Convert the positions from this box to CSS compatible positions using
  8381. // the reference container's positions. This has to be done because this
  8382. // box's positions are in reference to the viewport origin, whereas, CSS
  8383. // values are in referecne to their respective edges.
  8384. BoxPosition.prototype.toCSSCompatValues = function (reference) {
  8385. return {
  8386. top: this.top - reference.top,
  8387. bottom: reference.bottom - this.bottom,
  8388. left: this.left - reference.left,
  8389. right: reference.right - this.right,
  8390. height: this.height,
  8391. width: this.width
  8392. };
  8393. };
  8394. // Get an object that represents the box's position without anything extra.
  8395. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  8396. BoxPosition.getSimpleBoxPosition = function (obj) {
  8397. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  8398. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  8399. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  8400. obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj;
  8401. var ret = {
  8402. left: obj.left,
  8403. right: obj.right,
  8404. top: obj.top || top,
  8405. height: obj.height || height,
  8406. bottom: obj.bottom || top + (obj.height || height),
  8407. width: obj.width || width
  8408. };
  8409. return ret;
  8410. };
  8411. // Move a StyleBox to its specified, or next best, position. The containerBox
  8412. // is the box that contains the StyleBox, such as a div. boxPositions are
  8413. // a list of other boxes that the styleBox can't overlap with.
  8414. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  8415. // Find the best position for a cue box, b, on the video. The axis parameter
  8416. // is a list of axis, the order of which, it will move the box along. For example:
  8417. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  8418. // direction. If it doesn't find a good position for it there it will then move
  8419. // it along the x axis in the negative direction.
  8420. function findBestPosition(b, axis) {
  8421. var bestPosition,
  8422. specifiedPosition = new BoxPosition(b),
  8423. percentage = 1; // Highest possible so the first thing we get is better.
  8424. for (var i = 0; i < axis.length; i++) {
  8425. while (b.overlapsOppositeAxis(containerBox, axis[i]) || b.within(containerBox) && b.overlapsAny(boxPositions)) {
  8426. b.move(axis[i]);
  8427. }
  8428. // We found a spot where we aren't overlapping anything. This is our
  8429. // best position.
  8430. if (b.within(containerBox)) {
  8431. return b;
  8432. }
  8433. var p = b.intersectPercentage(containerBox);
  8434. // If we're outside the container box less then we were on our last try
  8435. // then remember this position as the best position.
  8436. if (percentage > p) {
  8437. bestPosition = new BoxPosition(b);
  8438. percentage = p;
  8439. }
  8440. // Reset the box position to the specified position.
  8441. b = new BoxPosition(specifiedPosition);
  8442. }
  8443. return bestPosition || specifiedPosition;
  8444. }
  8445. var boxPosition = new BoxPosition(styleBox),
  8446. cue = styleBox.cue,
  8447. linePos = computeLinePos(cue),
  8448. axis = [];
  8449. // If we have a line number to align the cue to.
  8450. if (cue.snapToLines) {
  8451. var size;
  8452. switch (cue.vertical) {
  8453. case "":
  8454. axis = ["+y", "-y"];
  8455. size = "height";
  8456. break;
  8457. case "rl":
  8458. axis = ["+x", "-x"];
  8459. size = "width";
  8460. break;
  8461. case "lr":
  8462. axis = ["-x", "+x"];
  8463. size = "width";
  8464. break;
  8465. }
  8466. var step = boxPosition.lineHeight,
  8467. position = step * Math.round(linePos),
  8468. maxPosition = containerBox[size] + step,
  8469. initialAxis = axis[0];
  8470. // If the specified intial position is greater then the max position then
  8471. // clamp the box to the amount of steps it would take for the box to
  8472. // reach the max position.
  8473. if (Math.abs(position) > maxPosition) {
  8474. position = position < 0 ? -1 : 1;
  8475. position *= Math.ceil(maxPosition / step) * step;
  8476. }
  8477. // If computed line position returns negative then line numbers are
  8478. // relative to the bottom of the video instead of the top. Therefore, we
  8479. // need to increase our initial position by the length or width of the
  8480. // video, depending on the writing direction, and reverse our axis directions.
  8481. if (linePos < 0) {
  8482. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  8483. axis = axis.reverse();
  8484. }
  8485. // Move the box to the specified position. This may not be its best
  8486. // position.
  8487. boxPosition.move(initialAxis, position);
  8488. } else {
  8489. // If we have a percentage line value for the cue.
  8490. var calculatedPercentage = boxPosition.lineHeight / containerBox.height * 100;
  8491. switch (cue.lineAlign) {
  8492. case "center":
  8493. linePos -= calculatedPercentage / 2;
  8494. break;
  8495. case "end":
  8496. linePos -= calculatedPercentage;
  8497. break;
  8498. }
  8499. // Apply initial line position to the cue box.
  8500. switch (cue.vertical) {
  8501. case "":
  8502. styleBox.applyStyles({
  8503. top: styleBox.formatStyle(linePos, "%")
  8504. });
  8505. break;
  8506. case "rl":
  8507. styleBox.applyStyles({
  8508. left: styleBox.formatStyle(linePos, "%")
  8509. });
  8510. break;
  8511. case "lr":
  8512. styleBox.applyStyles({
  8513. right: styleBox.formatStyle(linePos, "%")
  8514. });
  8515. break;
  8516. }
  8517. axis = ["+y", "-x", "+x", "-y"];
  8518. // Get the box position again after we've applied the specified positioning
  8519. // to it.
  8520. boxPosition = new BoxPosition(styleBox);
  8521. }
  8522. var bestPosition = findBestPosition(boxPosition, axis);
  8523. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  8524. }
  8525. function WebVTT$1() {
  8526. // Nothing
  8527. }
  8528. // Helper to allow strings to be decoded instead of the default binary utf8 data.
  8529. WebVTT$1.StringDecoder = function () {
  8530. return {
  8531. decode: function (data) {
  8532. if (!data) {
  8533. return "";
  8534. }
  8535. if (typeof data !== "string") {
  8536. throw new Error("Error - expected string data.");
  8537. }
  8538. return decodeURIComponent(encodeURIComponent(data));
  8539. }
  8540. };
  8541. };
  8542. WebVTT$1.convertCueToDOMTree = function (window, cuetext) {
  8543. if (!window || !cuetext) {
  8544. return null;
  8545. }
  8546. return parseContent(window, cuetext);
  8547. };
  8548. var FONT_SIZE_PERCENT = 0.05;
  8549. var FONT_STYLE = "sans-serif";
  8550. var CUE_BACKGROUND_PADDING = "1.5%";
  8551. // Runs the processing model over the cues and regions passed to it.
  8552. // @param overlay A block level element (usually a div) that the computed cues
  8553. // and regions will be placed into.
  8554. WebVTT$1.processCues = function (window, cues, overlay) {
  8555. if (!window || !cues || !overlay) {
  8556. return null;
  8557. }
  8558. // Remove all previous children.
  8559. while (overlay.firstChild) {
  8560. overlay.removeChild(overlay.firstChild);
  8561. }
  8562. var paddedOverlay = window.document.createElement("div");
  8563. paddedOverlay.style.position = "absolute";
  8564. paddedOverlay.style.left = "0";
  8565. paddedOverlay.style.right = "0";
  8566. paddedOverlay.style.top = "0";
  8567. paddedOverlay.style.bottom = "0";
  8568. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  8569. overlay.appendChild(paddedOverlay);
  8570. // Determine if we need to compute the display states of the cues. This could
  8571. // be the case if a cue's state has been changed since the last computation or
  8572. // if it has not been computed yet.
  8573. function shouldCompute(cues) {
  8574. for (var i = 0; i < cues.length; i++) {
  8575. if (cues[i].hasBeenReset || !cues[i].displayState) {
  8576. return true;
  8577. }
  8578. }
  8579. return false;
  8580. }
  8581. // We don't need to recompute the cues' display states. Just reuse them.
  8582. if (!shouldCompute(cues)) {
  8583. for (var i = 0; i < cues.length; i++) {
  8584. paddedOverlay.appendChild(cues[i].displayState);
  8585. }
  8586. return;
  8587. }
  8588. var boxPositions = [],
  8589. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  8590. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  8591. var styleOptions = {
  8592. font: fontSize + "px " + FONT_STYLE
  8593. };
  8594. (function () {
  8595. var styleBox, cue;
  8596. for (var i = 0; i < cues.length; i++) {
  8597. cue = cues[i];
  8598. // Compute the intial position and styles of the cue div.
  8599. styleBox = new CueStyleBox(window, cue, styleOptions);
  8600. paddedOverlay.appendChild(styleBox.div);
  8601. // Move the cue div to it's correct line position.
  8602. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions);
  8603. // Remember the computed div so that we don't have to recompute it later
  8604. // if we don't have too.
  8605. cue.displayState = styleBox.div;
  8606. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  8607. }
  8608. })();
  8609. };
  8610. WebVTT$1.Parser = function (window, vttjs, decoder) {
  8611. if (!decoder) {
  8612. decoder = vttjs;
  8613. vttjs = {};
  8614. }
  8615. if (!vttjs) {
  8616. vttjs = {};
  8617. }
  8618. this.window = window;
  8619. this.vttjs = vttjs;
  8620. this.state = "INITIAL";
  8621. this.buffer = "";
  8622. this.decoder = decoder || new TextDecoder("utf8");
  8623. this.regionList = [];
  8624. };
  8625. WebVTT$1.Parser.prototype = {
  8626. // If the error is a ParsingError then report it to the consumer if
  8627. // possible. If it's not a ParsingError then throw it like normal.
  8628. reportOrThrowError: function (e) {
  8629. if (e instanceof ParsingError) {
  8630. this.onparsingerror && this.onparsingerror(e);
  8631. } else {
  8632. throw e;
  8633. }
  8634. },
  8635. parse: function (data) {
  8636. var self = this;
  8637. // If there is no data then we won't decode it, but will just try to parse
  8638. // whatever is in buffer already. This may occur in circumstances, for
  8639. // example when flush() is called.
  8640. if (data) {
  8641. // Try to decode the data that we received.
  8642. self.buffer += self.decoder.decode(data, {
  8643. stream: true
  8644. });
  8645. }
  8646. function collectNextLine() {
  8647. var buffer = self.buffer;
  8648. var pos = 0;
  8649. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  8650. ++pos;
  8651. }
  8652. var line = buffer.substr(0, pos);
  8653. // Advance the buffer early in case we fail below.
  8654. if (buffer[pos] === '\r') {
  8655. ++pos;
  8656. }
  8657. if (buffer[pos] === '\n') {
  8658. ++pos;
  8659. }
  8660. self.buffer = buffer.substr(pos);
  8661. return line;
  8662. }
  8663. // 3.4 WebVTT region and WebVTT region settings syntax
  8664. function parseRegion(input) {
  8665. var settings = new Settings();
  8666. parseOptions(input, function (k, v) {
  8667. switch (k) {
  8668. case "id":
  8669. settings.set(k, v);
  8670. break;
  8671. case "width":
  8672. settings.percent(k, v);
  8673. break;
  8674. case "lines":
  8675. settings.integer(k, v);
  8676. break;
  8677. case "regionanchor":
  8678. case "viewportanchor":
  8679. var xy = v.split(',');
  8680. if (xy.length !== 2) {
  8681. break;
  8682. }
  8683. // We have to make sure both x and y parse, so use a temporary
  8684. // settings object here.
  8685. var anchor = new Settings();
  8686. anchor.percent("x", xy[0]);
  8687. anchor.percent("y", xy[1]);
  8688. if (!anchor.has("x") || !anchor.has("y")) {
  8689. break;
  8690. }
  8691. settings.set(k + "X", anchor.get("x"));
  8692. settings.set(k + "Y", anchor.get("y"));
  8693. break;
  8694. case "scroll":
  8695. settings.alt(k, v, ["up"]);
  8696. break;
  8697. }
  8698. }, /=/, /\s/);
  8699. // Create the region, using default values for any values that were not
  8700. // specified.
  8701. if (settings.has("id")) {
  8702. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  8703. region.width = settings.get("width", 100);
  8704. region.lines = settings.get("lines", 3);
  8705. region.regionAnchorX = settings.get("regionanchorX", 0);
  8706. region.regionAnchorY = settings.get("regionanchorY", 100);
  8707. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  8708. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  8709. region.scroll = settings.get("scroll", "");
  8710. // Register the region.
  8711. self.onregion && self.onregion(region);
  8712. // Remember the VTTRegion for later in case we parse any VTTCues that
  8713. // reference it.
  8714. self.regionList.push({
  8715. id: settings.get("id"),
  8716. region: region
  8717. });
  8718. }
  8719. }
  8720. // draft-pantos-http-live-streaming-20
  8721. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  8722. // 3.5 WebVTT
  8723. function parseTimestampMap(input) {
  8724. var settings = new Settings();
  8725. parseOptions(input, function (k, v) {
  8726. switch (k) {
  8727. case "MPEGT":
  8728. settings.integer(k + 'S', v);
  8729. break;
  8730. case "LOCA":
  8731. settings.set(k + 'L', parseTimeStamp(v));
  8732. break;
  8733. }
  8734. }, /[^\d]:/, /,/);
  8735. self.ontimestampmap && self.ontimestampmap({
  8736. "MPEGTS": settings.get("MPEGTS"),
  8737. "LOCAL": settings.get("LOCAL")
  8738. });
  8739. }
  8740. // 3.2 WebVTT metadata header syntax
  8741. function parseHeader(input) {
  8742. if (input.match(/X-TIMESTAMP-MAP/)) {
  8743. // This line contains HLS X-TIMESTAMP-MAP metadata
  8744. parseOptions(input, function (k, v) {
  8745. switch (k) {
  8746. case "X-TIMESTAMP-MAP":
  8747. parseTimestampMap(v);
  8748. break;
  8749. }
  8750. }, /=/);
  8751. } else {
  8752. parseOptions(input, function (k, v) {
  8753. switch (k) {
  8754. case "Region":
  8755. // 3.3 WebVTT region metadata header syntax
  8756. parseRegion(v);
  8757. break;
  8758. }
  8759. }, /:/);
  8760. }
  8761. }
  8762. // 5.1 WebVTT file parsing.
  8763. try {
  8764. var line;
  8765. if (self.state === "INITIAL") {
  8766. // We can't start parsing until we have the first line.
  8767. if (!/\r\n|\n/.test(self.buffer)) {
  8768. return this;
  8769. }
  8770. line = collectNextLine();
  8771. var m = line.match(/^WEBVTT([ \t].*)?$/);
  8772. if (!m || !m[0]) {
  8773. throw new ParsingError(ParsingError.Errors.BadSignature);
  8774. }
  8775. self.state = "HEADER";
  8776. }
  8777. var alreadyCollectedLine = false;
  8778. while (self.buffer) {
  8779. // We can't parse a line until we have the full line.
  8780. if (!/\r\n|\n/.test(self.buffer)) {
  8781. return this;
  8782. }
  8783. if (!alreadyCollectedLine) {
  8784. line = collectNextLine();
  8785. } else {
  8786. alreadyCollectedLine = false;
  8787. }
  8788. switch (self.state) {
  8789. case "HEADER":
  8790. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  8791. if (/:/.test(line)) {
  8792. parseHeader(line);
  8793. } else if (!line) {
  8794. // An empty line terminates the header and starts the body (cues).
  8795. self.state = "ID";
  8796. }
  8797. continue;
  8798. case "NOTE":
  8799. // Ignore NOTE blocks.
  8800. if (!line) {
  8801. self.state = "ID";
  8802. }
  8803. continue;
  8804. case "ID":
  8805. // Check for the start of NOTE blocks.
  8806. if (/^NOTE($|[ \t])/.test(line)) {
  8807. self.state = "NOTE";
  8808. break;
  8809. }
  8810. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  8811. if (!line) {
  8812. continue;
  8813. }
  8814. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, "");
  8815. // Safari still uses the old middle value and won't accept center
  8816. try {
  8817. self.cue.align = "center";
  8818. } catch (e) {
  8819. self.cue.align = "middle";
  8820. }
  8821. self.state = "CUE";
  8822. // 30-39 - Check if self line contains an optional identifier or timing data.
  8823. if (line.indexOf("-->") === -1) {
  8824. self.cue.id = line;
  8825. continue;
  8826. }
  8827. // Process line as start of a cue.
  8828. /*falls through*/
  8829. case "CUE":
  8830. // 40 - Collect cue timings and settings.
  8831. try {
  8832. parseCue(line, self.cue, self.regionList);
  8833. } catch (e) {
  8834. self.reportOrThrowError(e);
  8835. // In case of an error ignore rest of the cue.
  8836. self.cue = null;
  8837. self.state = "BADCUE";
  8838. continue;
  8839. }
  8840. self.state = "CUETEXT";
  8841. continue;
  8842. case "CUETEXT":
  8843. var hasSubstring = line.indexOf("-->") !== -1;
  8844. // 34 - If we have an empty line then report the cue.
  8845. // 35 - If we have the special substring '-->' then report the cue,
  8846. // but do not collect the line as we need to process the current
  8847. // one as a new cue.
  8848. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  8849. // We are done parsing self cue.
  8850. self.oncue && self.oncue(self.cue);
  8851. self.cue = null;
  8852. self.state = "ID";
  8853. continue;
  8854. }
  8855. if (self.cue.text) {
  8856. self.cue.text += "\n";
  8857. }
  8858. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  8859. continue;
  8860. case "BADCUE":
  8861. // BADCUE
  8862. // 54-62 - Collect and discard the remaining cue.
  8863. if (!line) {
  8864. self.state = "ID";
  8865. }
  8866. continue;
  8867. }
  8868. }
  8869. } catch (e) {
  8870. self.reportOrThrowError(e);
  8871. // If we are currently parsing a cue, report what we have.
  8872. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  8873. self.oncue(self.cue);
  8874. }
  8875. self.cue = null;
  8876. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  8877. // another exception occurred so enter BADCUE state.
  8878. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  8879. }
  8880. return this;
  8881. },
  8882. flush: function () {
  8883. var self = this;
  8884. try {
  8885. // Finish decoding the stream.
  8886. self.buffer += self.decoder.decode();
  8887. // Synthesize the end of the current cue or region.
  8888. if (self.cue || self.state === "HEADER") {
  8889. self.buffer += "\n\n";
  8890. self.parse();
  8891. }
  8892. // If we've flushed, parsed, and we're still on the INITIAL state then
  8893. // that means we don't have enough of the stream to parse the first
  8894. // line.
  8895. if (self.state === "INITIAL") {
  8896. throw new ParsingError(ParsingError.Errors.BadSignature);
  8897. }
  8898. } catch (e) {
  8899. self.reportOrThrowError(e);
  8900. }
  8901. self.onflush && self.onflush();
  8902. return this;
  8903. }
  8904. };
  8905. var vtt = WebVTT$1;
  8906. /**
  8907. * Copyright 2013 vtt.js Contributors
  8908. *
  8909. * Licensed under the Apache License, Version 2.0 (the "License");
  8910. * you may not use this file except in compliance with the License.
  8911. * You may obtain a copy of the License at
  8912. *
  8913. * http://www.apache.org/licenses/LICENSE-2.0
  8914. *
  8915. * Unless required by applicable law or agreed to in writing, software
  8916. * distributed under the License is distributed on an "AS IS" BASIS,
  8917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8918. * See the License for the specific language governing permissions and
  8919. * limitations under the License.
  8920. */
  8921. var autoKeyword = "auto";
  8922. var directionSetting = {
  8923. "": 1,
  8924. "lr": 1,
  8925. "rl": 1
  8926. };
  8927. var alignSetting = {
  8928. "start": 1,
  8929. "center": 1,
  8930. "end": 1,
  8931. "left": 1,
  8932. "right": 1,
  8933. "auto": 1,
  8934. "line-left": 1,
  8935. "line-right": 1
  8936. };
  8937. function findDirectionSetting(value) {
  8938. if (typeof value !== "string") {
  8939. return false;
  8940. }
  8941. var dir = directionSetting[value.toLowerCase()];
  8942. return dir ? value.toLowerCase() : false;
  8943. }
  8944. function findAlignSetting(value) {
  8945. if (typeof value !== "string") {
  8946. return false;
  8947. }
  8948. var align = alignSetting[value.toLowerCase()];
  8949. return align ? value.toLowerCase() : false;
  8950. }
  8951. function VTTCue(startTime, endTime, text) {
  8952. /**
  8953. * Shim implementation specific properties. These properties are not in
  8954. * the spec.
  8955. */
  8956. // Lets us know when the VTTCue's data has changed in such a way that we need
  8957. // to recompute its display state. This lets us compute its display state
  8958. // lazily.
  8959. this.hasBeenReset = false;
  8960. /**
  8961. * VTTCue and TextTrackCue properties
  8962. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  8963. */
  8964. var _id = "";
  8965. var _pauseOnExit = false;
  8966. var _startTime = startTime;
  8967. var _endTime = endTime;
  8968. var _text = text;
  8969. var _region = null;
  8970. var _vertical = "";
  8971. var _snapToLines = true;
  8972. var _line = "auto";
  8973. var _lineAlign = "start";
  8974. var _position = "auto";
  8975. var _positionAlign = "auto";
  8976. var _size = 100;
  8977. var _align = "center";
  8978. Object.defineProperties(this, {
  8979. "id": {
  8980. enumerable: true,
  8981. get: function () {
  8982. return _id;
  8983. },
  8984. set: function (value) {
  8985. _id = "" + value;
  8986. }
  8987. },
  8988. "pauseOnExit": {
  8989. enumerable: true,
  8990. get: function () {
  8991. return _pauseOnExit;
  8992. },
  8993. set: function (value) {
  8994. _pauseOnExit = !!value;
  8995. }
  8996. },
  8997. "startTime": {
  8998. enumerable: true,
  8999. get: function () {
  9000. return _startTime;
  9001. },
  9002. set: function (value) {
  9003. if (typeof value !== "number") {
  9004. throw new TypeError("Start time must be set to a number.");
  9005. }
  9006. _startTime = value;
  9007. this.hasBeenReset = true;
  9008. }
  9009. },
  9010. "endTime": {
  9011. enumerable: true,
  9012. get: function () {
  9013. return _endTime;
  9014. },
  9015. set: function (value) {
  9016. if (typeof value !== "number") {
  9017. throw new TypeError("End time must be set to a number.");
  9018. }
  9019. _endTime = value;
  9020. this.hasBeenReset = true;
  9021. }
  9022. },
  9023. "text": {
  9024. enumerable: true,
  9025. get: function () {
  9026. return _text;
  9027. },
  9028. set: function (value) {
  9029. _text = "" + value;
  9030. this.hasBeenReset = true;
  9031. }
  9032. },
  9033. "region": {
  9034. enumerable: true,
  9035. get: function () {
  9036. return _region;
  9037. },
  9038. set: function (value) {
  9039. _region = value;
  9040. this.hasBeenReset = true;
  9041. }
  9042. },
  9043. "vertical": {
  9044. enumerable: true,
  9045. get: function () {
  9046. return _vertical;
  9047. },
  9048. set: function (value) {
  9049. var setting = findDirectionSetting(value);
  9050. // Have to check for false because the setting an be an empty string.
  9051. if (setting === false) {
  9052. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  9053. }
  9054. _vertical = setting;
  9055. this.hasBeenReset = true;
  9056. }
  9057. },
  9058. "snapToLines": {
  9059. enumerable: true,
  9060. get: function () {
  9061. return _snapToLines;
  9062. },
  9063. set: function (value) {
  9064. _snapToLines = !!value;
  9065. this.hasBeenReset = true;
  9066. }
  9067. },
  9068. "line": {
  9069. enumerable: true,
  9070. get: function () {
  9071. return _line;
  9072. },
  9073. set: function (value) {
  9074. if (typeof value !== "number" && value !== autoKeyword) {
  9075. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  9076. }
  9077. _line = value;
  9078. this.hasBeenReset = true;
  9079. }
  9080. },
  9081. "lineAlign": {
  9082. enumerable: true,
  9083. get: function () {
  9084. return _lineAlign;
  9085. },
  9086. set: function (value) {
  9087. var setting = findAlignSetting(value);
  9088. if (!setting) {
  9089. console.warn("lineAlign: an invalid or illegal string was specified.");
  9090. } else {
  9091. _lineAlign = setting;
  9092. this.hasBeenReset = true;
  9093. }
  9094. }
  9095. },
  9096. "position": {
  9097. enumerable: true,
  9098. get: function () {
  9099. return _position;
  9100. },
  9101. set: function (value) {
  9102. if (value < 0 || value > 100) {
  9103. throw new Error("Position must be between 0 and 100.");
  9104. }
  9105. _position = value;
  9106. this.hasBeenReset = true;
  9107. }
  9108. },
  9109. "positionAlign": {
  9110. enumerable: true,
  9111. get: function () {
  9112. return _positionAlign;
  9113. },
  9114. set: function (value) {
  9115. var setting = findAlignSetting(value);
  9116. if (!setting) {
  9117. console.warn("positionAlign: an invalid or illegal string was specified.");
  9118. } else {
  9119. _positionAlign = setting;
  9120. this.hasBeenReset = true;
  9121. }
  9122. }
  9123. },
  9124. "size": {
  9125. enumerable: true,
  9126. get: function () {
  9127. return _size;
  9128. },
  9129. set: function (value) {
  9130. if (value < 0 || value > 100) {
  9131. throw new Error("Size must be between 0 and 100.");
  9132. }
  9133. _size = value;
  9134. this.hasBeenReset = true;
  9135. }
  9136. },
  9137. "align": {
  9138. enumerable: true,
  9139. get: function () {
  9140. return _align;
  9141. },
  9142. set: function (value) {
  9143. var setting = findAlignSetting(value);
  9144. if (!setting) {
  9145. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  9146. }
  9147. _align = setting;
  9148. this.hasBeenReset = true;
  9149. }
  9150. }
  9151. });
  9152. /**
  9153. * Other <track> spec defined properties
  9154. */
  9155. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  9156. this.displayState = undefined;
  9157. }
  9158. /**
  9159. * VTTCue methods
  9160. */
  9161. VTTCue.prototype.getCueAsHTML = function () {
  9162. // Assume WebVTT.convertCueToDOMTree is on the global.
  9163. return WebVTT.convertCueToDOMTree(window, this.text);
  9164. };
  9165. var vttcue = VTTCue;
  9166. /**
  9167. * Copyright 2013 vtt.js Contributors
  9168. *
  9169. * Licensed under the Apache License, Version 2.0 (the "License");
  9170. * you may not use this file except in compliance with the License.
  9171. * You may obtain a copy of the License at
  9172. *
  9173. * http://www.apache.org/licenses/LICENSE-2.0
  9174. *
  9175. * Unless required by applicable law or agreed to in writing, software
  9176. * distributed under the License is distributed on an "AS IS" BASIS,
  9177. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9178. * See the License for the specific language governing permissions and
  9179. * limitations under the License.
  9180. */
  9181. var scrollSetting = {
  9182. "": true,
  9183. "up": true
  9184. };
  9185. function findScrollSetting(value) {
  9186. if (typeof value !== "string") {
  9187. return false;
  9188. }
  9189. var scroll = scrollSetting[value.toLowerCase()];
  9190. return scroll ? value.toLowerCase() : false;
  9191. }
  9192. function isValidPercentValue(value) {
  9193. return typeof value === "number" && value >= 0 && value <= 100;
  9194. }
  9195. // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  9196. function VTTRegion() {
  9197. var _width = 100;
  9198. var _lines = 3;
  9199. var _regionAnchorX = 0;
  9200. var _regionAnchorY = 100;
  9201. var _viewportAnchorX = 0;
  9202. var _viewportAnchorY = 100;
  9203. var _scroll = "";
  9204. Object.defineProperties(this, {
  9205. "width": {
  9206. enumerable: true,
  9207. get: function () {
  9208. return _width;
  9209. },
  9210. set: function (value) {
  9211. if (!isValidPercentValue(value)) {
  9212. throw new Error("Width must be between 0 and 100.");
  9213. }
  9214. _width = value;
  9215. }
  9216. },
  9217. "lines": {
  9218. enumerable: true,
  9219. get: function () {
  9220. return _lines;
  9221. },
  9222. set: function (value) {
  9223. if (typeof value !== "number") {
  9224. throw new TypeError("Lines must be set to a number.");
  9225. }
  9226. _lines = value;
  9227. }
  9228. },
  9229. "regionAnchorY": {
  9230. enumerable: true,
  9231. get: function () {
  9232. return _regionAnchorY;
  9233. },
  9234. set: function (value) {
  9235. if (!isValidPercentValue(value)) {
  9236. throw new Error("RegionAnchorX must be between 0 and 100.");
  9237. }
  9238. _regionAnchorY = value;
  9239. }
  9240. },
  9241. "regionAnchorX": {
  9242. enumerable: true,
  9243. get: function () {
  9244. return _regionAnchorX;
  9245. },
  9246. set: function (value) {
  9247. if (!isValidPercentValue(value)) {
  9248. throw new Error("RegionAnchorY must be between 0 and 100.");
  9249. }
  9250. _regionAnchorX = value;
  9251. }
  9252. },
  9253. "viewportAnchorY": {
  9254. enumerable: true,
  9255. get: function () {
  9256. return _viewportAnchorY;
  9257. },
  9258. set: function (value) {
  9259. if (!isValidPercentValue(value)) {
  9260. throw new Error("ViewportAnchorY must be between 0 and 100.");
  9261. }
  9262. _viewportAnchorY = value;
  9263. }
  9264. },
  9265. "viewportAnchorX": {
  9266. enumerable: true,
  9267. get: function () {
  9268. return _viewportAnchorX;
  9269. },
  9270. set: function (value) {
  9271. if (!isValidPercentValue(value)) {
  9272. throw new Error("ViewportAnchorX must be between 0 and 100.");
  9273. }
  9274. _viewportAnchorX = value;
  9275. }
  9276. },
  9277. "scroll": {
  9278. enumerable: true,
  9279. get: function () {
  9280. return _scroll;
  9281. },
  9282. set: function (value) {
  9283. var setting = findScrollSetting(value);
  9284. // Have to check for false as an empty string is a legal value.
  9285. if (setting === false) {
  9286. console.warn("Scroll: an invalid or illegal string was specified.");
  9287. } else {
  9288. _scroll = setting;
  9289. }
  9290. }
  9291. }
  9292. });
  9293. }
  9294. var vttregion = VTTRegion;
  9295. var browserIndex = createCommonjsModule(function (module) {
  9296. /**
  9297. * Copyright 2013 vtt.js Contributors
  9298. *
  9299. * Licensed under the Apache License, Version 2.0 (the "License");
  9300. * you may not use this file except in compliance with the License.
  9301. * You may obtain a copy of the License at
  9302. *
  9303. * http://www.apache.org/licenses/LICENSE-2.0
  9304. *
  9305. * Unless required by applicable law or agreed to in writing, software
  9306. * distributed under the License is distributed on an "AS IS" BASIS,
  9307. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9308. * See the License for the specific language governing permissions and
  9309. * limitations under the License.
  9310. */
  9311. // Default exports for Node. Export the extended versions of VTTCue and
  9312. // VTTRegion in Node since we likely want the capability to convert back and
  9313. // forth between JSON. If we don't then it's not that big of a deal since we're
  9314. // off browser.
  9315. var vttjs = module.exports = {
  9316. WebVTT: vtt,
  9317. VTTCue: vttcue,
  9318. VTTRegion: vttregion
  9319. };
  9320. window_1.vttjs = vttjs;
  9321. window_1.WebVTT = vttjs.WebVTT;
  9322. var cueShim = vttjs.VTTCue;
  9323. var regionShim = vttjs.VTTRegion;
  9324. var nativeVTTCue = window_1.VTTCue;
  9325. var nativeVTTRegion = window_1.VTTRegion;
  9326. vttjs.shim = function () {
  9327. window_1.VTTCue = cueShim;
  9328. window_1.VTTRegion = regionShim;
  9329. };
  9330. vttjs.restore = function () {
  9331. window_1.VTTCue = nativeVTTCue;
  9332. window_1.VTTRegion = nativeVTTRegion;
  9333. };
  9334. if (!window_1.VTTCue) {
  9335. vttjs.shim();
  9336. }
  9337. });
  9338. browserIndex.WebVTT;
  9339. browserIndex.VTTCue;
  9340. browserIndex.VTTRegion;
  9341. /**
  9342. * @file tech.js
  9343. */
  9344. /**
  9345. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  9346. * that just contains the src url alone.
  9347. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  9348. * `var SourceString = 'http://example.com/some-video.mp4';`
  9349. *
  9350. * @typedef {Object|string} Tech~SourceObject
  9351. *
  9352. * @property {string} src
  9353. * The url to the source
  9354. *
  9355. * @property {string} type
  9356. * The mime type of the source
  9357. */
  9358. /**
  9359. * A function used by {@link Tech} to create a new {@link TextTrack}.
  9360. *
  9361. * @private
  9362. *
  9363. * @param {Tech} self
  9364. * An instance of the Tech class.
  9365. *
  9366. * @param {string} kind
  9367. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9368. *
  9369. * @param {string} [label]
  9370. * Label to identify the text track
  9371. *
  9372. * @param {string} [language]
  9373. * Two letter language abbreviation
  9374. *
  9375. * @param {Object} [options={}]
  9376. * An object with additional text track options
  9377. *
  9378. * @return {TextTrack}
  9379. * The text track that was created.
  9380. */
  9381. function createTrackHelper(self, kind, label, language, options = {}) {
  9382. const tracks = self.textTracks();
  9383. options.kind = kind;
  9384. if (label) {
  9385. options.label = label;
  9386. }
  9387. if (language) {
  9388. options.language = language;
  9389. }
  9390. options.tech = self;
  9391. const track = new ALL.text.TrackClass(options);
  9392. tracks.addTrack(track);
  9393. return track;
  9394. }
  9395. /**
  9396. * This is the base class for media playback technology controllers, such as
  9397. * {@link HTML5}
  9398. *
  9399. * @extends Component
  9400. */
  9401. class Tech extends Component {
  9402. /**
  9403. * Create an instance of this Tech.
  9404. *
  9405. * @param {Object} [options]
  9406. * The key/value store of player options.
  9407. *
  9408. * @param {Function} [ready]
  9409. * Callback function to call when the `HTML5` Tech is ready.
  9410. */
  9411. constructor(options = {}, ready = function () {}) {
  9412. // we don't want the tech to report user activity automatically.
  9413. // This is done manually in addControlsListeners
  9414. options.reportTouchActivity = false;
  9415. super(null, options, ready);
  9416. this.onDurationChange_ = e => this.onDurationChange(e);
  9417. this.trackProgress_ = e => this.trackProgress(e);
  9418. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  9419. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  9420. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  9421. this.queuedHanders_ = new Set();
  9422. // keep track of whether the current source has played at all to
  9423. // implement a very limited played()
  9424. this.hasStarted_ = false;
  9425. this.on('playing', function () {
  9426. this.hasStarted_ = true;
  9427. });
  9428. this.on('loadstart', function () {
  9429. this.hasStarted_ = false;
  9430. });
  9431. ALL.names.forEach(name => {
  9432. const props = ALL[name];
  9433. if (options && options[props.getterName]) {
  9434. this[props.privateName] = options[props.getterName];
  9435. }
  9436. });
  9437. // Manually track progress in cases where the browser/tech doesn't report it.
  9438. if (!this.featuresProgressEvents) {
  9439. this.manualProgressOn();
  9440. }
  9441. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  9442. if (!this.featuresTimeupdateEvents) {
  9443. this.manualTimeUpdatesOn();
  9444. }
  9445. ['Text', 'Audio', 'Video'].forEach(track => {
  9446. if (options[`native${track}Tracks`] === false) {
  9447. this[`featuresNative${track}Tracks`] = false;
  9448. }
  9449. });
  9450. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  9451. this.featuresNativeTextTracks = false;
  9452. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  9453. this.featuresNativeTextTracks = true;
  9454. }
  9455. if (!this.featuresNativeTextTracks) {
  9456. this.emulateTextTracks();
  9457. }
  9458. this.preloadTextTracks = options.preloadTextTracks !== false;
  9459. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  9460. this.initTrackListeners();
  9461. // Turn on component tap events only if not using native controls
  9462. if (!options.nativeControlsForTouch) {
  9463. this.emitTapEvents();
  9464. }
  9465. if (this.constructor) {
  9466. this.name_ = this.constructor.name || 'Unknown Tech';
  9467. }
  9468. }
  9469. /**
  9470. * A special function to trigger source set in a way that will allow player
  9471. * to re-trigger if the player or tech are not ready yet.
  9472. *
  9473. * @fires Tech#sourceset
  9474. * @param {string} src The source string at the time of the source changing.
  9475. */
  9476. triggerSourceset(src) {
  9477. if (!this.isReady_) {
  9478. // on initial ready we have to trigger source set
  9479. // 1ms after ready so that player can watch for it.
  9480. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  9481. }
  9482. /**
  9483. * Fired when the source is set on the tech causing the media element
  9484. * to reload.
  9485. *
  9486. * @see {@link Player#event:sourceset}
  9487. * @event Tech#sourceset
  9488. * @type {Event}
  9489. */
  9490. this.trigger({
  9491. src,
  9492. type: 'sourceset'
  9493. });
  9494. }
  9495. /* Fallbacks for unsupported event types
  9496. ================================================================================ */
  9497. /**
  9498. * Polyfill the `progress` event for browsers that don't support it natively.
  9499. *
  9500. * @see {@link Tech#trackProgress}
  9501. */
  9502. manualProgressOn() {
  9503. this.on('durationchange', this.onDurationChange_);
  9504. this.manualProgress = true;
  9505. // Trigger progress watching when a source begins loading
  9506. this.one('ready', this.trackProgress_);
  9507. }
  9508. /**
  9509. * Turn off the polyfill for `progress` events that was created in
  9510. * {@link Tech#manualProgressOn}
  9511. */
  9512. manualProgressOff() {
  9513. this.manualProgress = false;
  9514. this.stopTrackingProgress();
  9515. this.off('durationchange', this.onDurationChange_);
  9516. }
  9517. /**
  9518. * This is used to trigger a `progress` event when the buffered percent changes. It
  9519. * sets an interval function that will be called every 500 milliseconds to check if the
  9520. * buffer end percent has changed.
  9521. *
  9522. * > This function is called by {@link Tech#manualProgressOn}
  9523. *
  9524. * @param {Event} event
  9525. * The `ready` event that caused this to run.
  9526. *
  9527. * @listens Tech#ready
  9528. * @fires Tech#progress
  9529. */
  9530. trackProgress(event) {
  9531. this.stopTrackingProgress();
  9532. this.progressInterval = this.setInterval(bind_(this, function () {
  9533. // Don't trigger unless buffered amount is greater than last time
  9534. const numBufferedPercent = this.bufferedPercent();
  9535. if (this.bufferedPercent_ !== numBufferedPercent) {
  9536. /**
  9537. * See {@link Player#progress}
  9538. *
  9539. * @event Tech#progress
  9540. * @type {Event}
  9541. */
  9542. this.trigger('progress');
  9543. }
  9544. this.bufferedPercent_ = numBufferedPercent;
  9545. if (numBufferedPercent === 1) {
  9546. this.stopTrackingProgress();
  9547. }
  9548. }), 500);
  9549. }
  9550. /**
  9551. * Update our internal duration on a `durationchange` event by calling
  9552. * {@link Tech#duration}.
  9553. *
  9554. * @param {Event} event
  9555. * The `durationchange` event that caused this to run.
  9556. *
  9557. * @listens Tech#durationchange
  9558. */
  9559. onDurationChange(event) {
  9560. this.duration_ = this.duration();
  9561. }
  9562. /**
  9563. * Get and create a `TimeRange` object for buffering.
  9564. *
  9565. * @return { import('../utils/time').TimeRange }
  9566. * The time range object that was created.
  9567. */
  9568. buffered() {
  9569. return createTimeRanges(0, 0);
  9570. }
  9571. /**
  9572. * Get the percentage of the current video that is currently buffered.
  9573. *
  9574. * @return {number}
  9575. * A number from 0 to 1 that represents the decimal percentage of the
  9576. * video that is buffered.
  9577. *
  9578. */
  9579. bufferedPercent() {
  9580. return bufferedPercent(this.buffered(), this.duration_);
  9581. }
  9582. /**
  9583. * Turn off the polyfill for `progress` events that was created in
  9584. * {@link Tech#manualProgressOn}
  9585. * Stop manually tracking progress events by clearing the interval that was set in
  9586. * {@link Tech#trackProgress}.
  9587. */
  9588. stopTrackingProgress() {
  9589. this.clearInterval(this.progressInterval);
  9590. }
  9591. /**
  9592. * Polyfill the `timeupdate` event for browsers that don't support it.
  9593. *
  9594. * @see {@link Tech#trackCurrentTime}
  9595. */
  9596. manualTimeUpdatesOn() {
  9597. this.manualTimeUpdates = true;
  9598. this.on('play', this.trackCurrentTime_);
  9599. this.on('pause', this.stopTrackingCurrentTime_);
  9600. }
  9601. /**
  9602. * Turn off the polyfill for `timeupdate` events that was created in
  9603. * {@link Tech#manualTimeUpdatesOn}
  9604. */
  9605. manualTimeUpdatesOff() {
  9606. this.manualTimeUpdates = false;
  9607. this.stopTrackingCurrentTime();
  9608. this.off('play', this.trackCurrentTime_);
  9609. this.off('pause', this.stopTrackingCurrentTime_);
  9610. }
  9611. /**
  9612. * Sets up an interval function to track current time and trigger `timeupdate` every
  9613. * 250 milliseconds.
  9614. *
  9615. * @listens Tech#play
  9616. * @triggers Tech#timeupdate
  9617. */
  9618. trackCurrentTime() {
  9619. if (this.currentTimeInterval) {
  9620. this.stopTrackingCurrentTime();
  9621. }
  9622. this.currentTimeInterval = this.setInterval(function () {
  9623. /**
  9624. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  9625. *
  9626. * @event Tech#timeupdate
  9627. * @type {Event}
  9628. */
  9629. this.trigger({
  9630. type: 'timeupdate',
  9631. target: this,
  9632. manuallyTriggered: true
  9633. });
  9634. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  9635. }, 250);
  9636. }
  9637. /**
  9638. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  9639. * `timeupdate` event is no longer triggered.
  9640. *
  9641. * @listens {Tech#pause}
  9642. */
  9643. stopTrackingCurrentTime() {
  9644. this.clearInterval(this.currentTimeInterval);
  9645. // #1002 - if the video ends right before the next timeupdate would happen,
  9646. // the progress bar won't make it all the way to the end
  9647. this.trigger({
  9648. type: 'timeupdate',
  9649. target: this,
  9650. manuallyTriggered: true
  9651. });
  9652. }
  9653. /**
  9654. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  9655. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  9656. *
  9657. * @fires Component#dispose
  9658. */
  9659. dispose() {
  9660. // clear out all tracks because we can't reuse them between techs
  9661. this.clearTracks(NORMAL.names);
  9662. // Turn off any manual progress or timeupdate tracking
  9663. if (this.manualProgress) {
  9664. this.manualProgressOff();
  9665. }
  9666. if (this.manualTimeUpdates) {
  9667. this.manualTimeUpdatesOff();
  9668. }
  9669. super.dispose();
  9670. }
  9671. /**
  9672. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  9673. *
  9674. * > Note: Techs without source handlers should call this between sources for `video`
  9675. * & `audio` tracks. You don't want to use them between tracks!
  9676. *
  9677. * @param {string[]|string} types
  9678. * TrackList names to clear, valid names are `video`, `audio`, and
  9679. * `text`.
  9680. */
  9681. clearTracks(types) {
  9682. types = [].concat(types);
  9683. // clear out all tracks because we can't reuse them between techs
  9684. types.forEach(type => {
  9685. const list = this[`${type}Tracks`]() || [];
  9686. let i = list.length;
  9687. while (i--) {
  9688. const track = list[i];
  9689. if (type === 'text') {
  9690. this.removeRemoteTextTrack(track);
  9691. }
  9692. list.removeTrack(track);
  9693. }
  9694. });
  9695. }
  9696. /**
  9697. * Remove any TextTracks added via addRemoteTextTrack that are
  9698. * flagged for automatic garbage collection
  9699. */
  9700. cleanupAutoTextTracks() {
  9701. const list = this.autoRemoteTextTracks_ || [];
  9702. let i = list.length;
  9703. while (i--) {
  9704. const track = list[i];
  9705. this.removeRemoteTextTrack(track);
  9706. }
  9707. }
  9708. /**
  9709. * Reset the tech, which will removes all sources and reset the internal readyState.
  9710. *
  9711. * @abstract
  9712. */
  9713. reset() {}
  9714. /**
  9715. * Get the value of `crossOrigin` from the tech.
  9716. *
  9717. * @abstract
  9718. *
  9719. * @see {Html5#crossOrigin}
  9720. */
  9721. crossOrigin() {}
  9722. /**
  9723. * Set the value of `crossOrigin` on the tech.
  9724. *
  9725. * @abstract
  9726. *
  9727. * @param {string} crossOrigin the crossOrigin value
  9728. * @see {Html5#setCrossOrigin}
  9729. */
  9730. setCrossOrigin() {}
  9731. /**
  9732. * Get or set an error on the Tech.
  9733. *
  9734. * @param {MediaError} [err]
  9735. * Error to set on the Tech
  9736. *
  9737. * @return {MediaError|null}
  9738. * The current error object on the tech, or null if there isn't one.
  9739. */
  9740. error(err) {
  9741. if (err !== undefined) {
  9742. this.error_ = new MediaError(err);
  9743. this.trigger('error');
  9744. }
  9745. return this.error_;
  9746. }
  9747. /**
  9748. * Returns the `TimeRange`s that have been played through for the current source.
  9749. *
  9750. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  9751. * It only checks whether the source has played at all or not.
  9752. *
  9753. * @return {TimeRange}
  9754. * - A single time range if this video has played
  9755. * - An empty set of ranges if not.
  9756. */
  9757. played() {
  9758. if (this.hasStarted_) {
  9759. return createTimeRanges(0, 0);
  9760. }
  9761. return createTimeRanges();
  9762. }
  9763. /**
  9764. * Start playback
  9765. *
  9766. * @abstract
  9767. *
  9768. * @see {Html5#play}
  9769. */
  9770. play() {}
  9771. /**
  9772. * Set whether we are scrubbing or not
  9773. *
  9774. * @abstract
  9775. * @param {boolean} _isScrubbing
  9776. * - true for we are currently scrubbing
  9777. * - false for we are no longer scrubbing
  9778. *
  9779. * @see {Html5#setScrubbing}
  9780. */
  9781. setScrubbing(_isScrubbing) {}
  9782. /**
  9783. * Get whether we are scrubbing or not
  9784. *
  9785. * @abstract
  9786. *
  9787. * @see {Html5#scrubbing}
  9788. */
  9789. scrubbing() {}
  9790. /**
  9791. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  9792. * previously called.
  9793. *
  9794. * @param {number} _seconds
  9795. * Set the current time of the media to this.
  9796. * @fires Tech#timeupdate
  9797. */
  9798. setCurrentTime(_seconds) {
  9799. // improve the accuracy of manual timeupdates
  9800. if (this.manualTimeUpdates) {
  9801. /**
  9802. * A manual `timeupdate` event.
  9803. *
  9804. * @event Tech#timeupdate
  9805. * @type {Event}
  9806. */
  9807. this.trigger({
  9808. type: 'timeupdate',
  9809. target: this,
  9810. manuallyTriggered: true
  9811. });
  9812. }
  9813. }
  9814. /**
  9815. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  9816. * {@link TextTrackList} events.
  9817. *
  9818. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  9819. *
  9820. * @fires Tech#audiotrackchange
  9821. * @fires Tech#videotrackchange
  9822. * @fires Tech#texttrackchange
  9823. */
  9824. initTrackListeners() {
  9825. /**
  9826. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  9827. *
  9828. * @event Tech#audiotrackchange
  9829. * @type {Event}
  9830. */
  9831. /**
  9832. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  9833. *
  9834. * @event Tech#videotrackchange
  9835. * @type {Event}
  9836. */
  9837. /**
  9838. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  9839. *
  9840. * @event Tech#texttrackchange
  9841. * @type {Event}
  9842. */
  9843. NORMAL.names.forEach(name => {
  9844. const props = NORMAL[name];
  9845. const trackListChanges = () => {
  9846. this.trigger(`${name}trackchange`);
  9847. };
  9848. const tracks = this[props.getterName]();
  9849. tracks.addEventListener('removetrack', trackListChanges);
  9850. tracks.addEventListener('addtrack', trackListChanges);
  9851. this.on('dispose', () => {
  9852. tracks.removeEventListener('removetrack', trackListChanges);
  9853. tracks.removeEventListener('addtrack', trackListChanges);
  9854. });
  9855. });
  9856. }
  9857. /**
  9858. * Emulate TextTracks using vtt.js if necessary
  9859. *
  9860. * @fires Tech#vttjsloaded
  9861. * @fires Tech#vttjserror
  9862. */
  9863. addWebVttScript_() {
  9864. if (window.WebVTT) {
  9865. return;
  9866. }
  9867. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  9868. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  9869. // before inserting the WebVTT script
  9870. if (document.body.contains(this.el())) {
  9871. // load via require if available and vtt.js script location was not passed in
  9872. // as an option. novtt builds will turn the above require call into an empty object
  9873. // which will cause this if check to always fail.
  9874. if (!this.options_['vtt.js'] && isPlain(browserIndex) && Object.keys(browserIndex).length > 0) {
  9875. this.trigger('vttjsloaded');
  9876. return;
  9877. }
  9878. // load vtt.js via the script location option or the cdn of no location was
  9879. // passed in
  9880. const script = document.createElement('script');
  9881. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  9882. script.onload = () => {
  9883. /**
  9884. * Fired when vtt.js is loaded.
  9885. *
  9886. * @event Tech#vttjsloaded
  9887. * @type {Event}
  9888. */
  9889. this.trigger('vttjsloaded');
  9890. };
  9891. script.onerror = () => {
  9892. /**
  9893. * Fired when vtt.js was not loaded due to an error
  9894. *
  9895. * @event Tech#vttjsloaded
  9896. * @type {Event}
  9897. */
  9898. this.trigger('vttjserror');
  9899. };
  9900. this.on('dispose', () => {
  9901. script.onload = null;
  9902. script.onerror = null;
  9903. });
  9904. // but have not loaded yet and we set it to true before the inject so that
  9905. // we don't overwrite the injected window.WebVTT if it loads right away
  9906. window.WebVTT = true;
  9907. this.el().parentNode.appendChild(script);
  9908. } else {
  9909. this.ready(this.addWebVttScript_);
  9910. }
  9911. }
  9912. /**
  9913. * Emulate texttracks
  9914. *
  9915. */
  9916. emulateTextTracks() {
  9917. const tracks = this.textTracks();
  9918. const remoteTracks = this.remoteTextTracks();
  9919. const handleAddTrack = e => tracks.addTrack(e.track);
  9920. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  9921. remoteTracks.on('addtrack', handleAddTrack);
  9922. remoteTracks.on('removetrack', handleRemoveTrack);
  9923. this.addWebVttScript_();
  9924. const updateDisplay = () => this.trigger('texttrackchange');
  9925. const textTracksChanges = () => {
  9926. updateDisplay();
  9927. for (let i = 0; i < tracks.length; i++) {
  9928. const track = tracks[i];
  9929. track.removeEventListener('cuechange', updateDisplay);
  9930. if (track.mode === 'showing') {
  9931. track.addEventListener('cuechange', updateDisplay);
  9932. }
  9933. }
  9934. };
  9935. textTracksChanges();
  9936. tracks.addEventListener('change', textTracksChanges);
  9937. tracks.addEventListener('addtrack', textTracksChanges);
  9938. tracks.addEventListener('removetrack', textTracksChanges);
  9939. this.on('dispose', function () {
  9940. remoteTracks.off('addtrack', handleAddTrack);
  9941. remoteTracks.off('removetrack', handleRemoveTrack);
  9942. tracks.removeEventListener('change', textTracksChanges);
  9943. tracks.removeEventListener('addtrack', textTracksChanges);
  9944. tracks.removeEventListener('removetrack', textTracksChanges);
  9945. for (let i = 0; i < tracks.length; i++) {
  9946. const track = tracks[i];
  9947. track.removeEventListener('cuechange', updateDisplay);
  9948. }
  9949. });
  9950. }
  9951. /**
  9952. * Create and returns a remote {@link TextTrack} object.
  9953. *
  9954. * @param {string} kind
  9955. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9956. *
  9957. * @param {string} [label]
  9958. * Label to identify the text track
  9959. *
  9960. * @param {string} [language]
  9961. * Two letter language abbreviation
  9962. *
  9963. * @return {TextTrack}
  9964. * The TextTrack that gets created.
  9965. */
  9966. addTextTrack(kind, label, language) {
  9967. if (!kind) {
  9968. throw new Error('TextTrack kind is required but was not provided');
  9969. }
  9970. return createTrackHelper(this, kind, label, language);
  9971. }
  9972. /**
  9973. * Create an emulated TextTrack for use by addRemoteTextTrack
  9974. *
  9975. * This is intended to be overridden by classes that inherit from
  9976. * Tech in order to create native or custom TextTracks.
  9977. *
  9978. * @param {Object} options
  9979. * The object should contain the options to initialize the TextTrack with.
  9980. *
  9981. * @param {string} [options.kind]
  9982. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  9983. *
  9984. * @param {string} [options.label].
  9985. * Label to identify the text track
  9986. *
  9987. * @param {string} [options.language]
  9988. * Two letter language abbreviation.
  9989. *
  9990. * @return {HTMLTrackElement}
  9991. * The track element that gets created.
  9992. */
  9993. createRemoteTextTrack(options) {
  9994. const track = merge(options, {
  9995. tech: this
  9996. });
  9997. return new REMOTE.remoteTextEl.TrackClass(track);
  9998. }
  9999. /**
  10000. * Creates a remote text track object and returns an html track element.
  10001. *
  10002. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  10003. *
  10004. * @param {Object} options
  10005. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  10006. *
  10007. * @param {boolean} [manualCleanup=false]
  10008. * - When false: the TextTrack will be automatically removed from the video
  10009. * element whenever the source changes
  10010. * - When True: The TextTrack will have to be cleaned up manually
  10011. *
  10012. * @return {HTMLTrackElement}
  10013. * An Html Track Element.
  10014. *
  10015. */
  10016. addRemoteTextTrack(options = {}, manualCleanup) {
  10017. const htmlTrackElement = this.createRemoteTextTrack(options);
  10018. if (typeof manualCleanup !== 'boolean') {
  10019. manualCleanup = false;
  10020. }
  10021. // store HTMLTrackElement and TextTrack to remote list
  10022. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  10023. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  10024. if (manualCleanup === false) {
  10025. // create the TextTrackList if it doesn't exist
  10026. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  10027. }
  10028. return htmlTrackElement;
  10029. }
  10030. /**
  10031. * Remove a remote text track from the remote `TextTrackList`.
  10032. *
  10033. * @param {TextTrack} track
  10034. * `TextTrack` to remove from the `TextTrackList`
  10035. */
  10036. removeRemoteTextTrack(track) {
  10037. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  10038. // remove HTMLTrackElement and TextTrack from remote list
  10039. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  10040. this.remoteTextTracks().removeTrack(track);
  10041. this.autoRemoteTextTracks_.removeTrack(track);
  10042. }
  10043. /**
  10044. * Gets available media playback quality metrics as specified by the W3C's Media
  10045. * Playback Quality API.
  10046. *
  10047. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  10048. *
  10049. * @return {Object}
  10050. * An object with supported media playback quality metrics
  10051. *
  10052. * @abstract
  10053. */
  10054. getVideoPlaybackQuality() {
  10055. return {};
  10056. }
  10057. /**
  10058. * Attempt to create a floating video window always on top of other windows
  10059. * so that users may continue consuming media while they interact with other
  10060. * content sites, or applications on their device.
  10061. *
  10062. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  10063. *
  10064. * @return {Promise|undefined}
  10065. * A promise with a Picture-in-Picture window if the browser supports
  10066. * Promises (or one was passed in as an option). It returns undefined
  10067. * otherwise.
  10068. *
  10069. * @abstract
  10070. */
  10071. requestPictureInPicture() {
  10072. return Promise.reject();
  10073. }
  10074. /**
  10075. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  10076. * Defaults to true, as it should be considered disabled if the tech does not support pip
  10077. *
  10078. * @abstract
  10079. */
  10080. disablePictureInPicture() {
  10081. return true;
  10082. }
  10083. /**
  10084. * A method to set or unset the 'disablePictureInPicture' <video> property.
  10085. *
  10086. * @abstract
  10087. */
  10088. setDisablePictureInPicture() {}
  10089. /**
  10090. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  10091. *
  10092. * @param {function} cb
  10093. * @return {number} request id
  10094. */
  10095. requestVideoFrameCallback(cb) {
  10096. const id = newGUID();
  10097. if (!this.isReady_ || this.paused()) {
  10098. this.queuedHanders_.add(id);
  10099. this.one('playing', () => {
  10100. if (this.queuedHanders_.has(id)) {
  10101. this.queuedHanders_.delete(id);
  10102. cb();
  10103. }
  10104. });
  10105. } else {
  10106. this.requestNamedAnimationFrame(id, cb);
  10107. }
  10108. return id;
  10109. }
  10110. /**
  10111. * A fallback implementation of cancelVideoFrameCallback
  10112. *
  10113. * @param {number} id id of callback to be cancelled
  10114. */
  10115. cancelVideoFrameCallback(id) {
  10116. if (this.queuedHanders_.has(id)) {
  10117. this.queuedHanders_.delete(id);
  10118. } else {
  10119. this.cancelNamedAnimationFrame(id);
  10120. }
  10121. }
  10122. /**
  10123. * A method to set a poster from a `Tech`.
  10124. *
  10125. * @abstract
  10126. */
  10127. setPoster() {}
  10128. /**
  10129. * A method to check for the presence of the 'playsinline' <video> attribute.
  10130. *
  10131. * @abstract
  10132. */
  10133. playsinline() {}
  10134. /**
  10135. * A method to set or unset the 'playsinline' <video> attribute.
  10136. *
  10137. * @abstract
  10138. */
  10139. setPlaysinline() {}
  10140. /**
  10141. * Attempt to force override of native audio tracks.
  10142. *
  10143. * @param {boolean} override - If set to true native audio will be overridden,
  10144. * otherwise native audio will potentially be used.
  10145. *
  10146. * @abstract
  10147. */
  10148. overrideNativeAudioTracks(override) {}
  10149. /**
  10150. * Attempt to force override of native video tracks.
  10151. *
  10152. * @param {boolean} override - If set to true native video will be overridden,
  10153. * otherwise native video will potentially be used.
  10154. *
  10155. * @abstract
  10156. */
  10157. overrideNativeVideoTracks(override) {}
  10158. /**
  10159. * Check if the tech can support the given mime-type.
  10160. *
  10161. * The base tech does not support any type, but source handlers might
  10162. * overwrite this.
  10163. *
  10164. * @param {string} _type
  10165. * The mimetype to check for support
  10166. *
  10167. * @return {string}
  10168. * 'probably', 'maybe', or empty string
  10169. *
  10170. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  10171. *
  10172. * @abstract
  10173. */
  10174. canPlayType(_type) {
  10175. return '';
  10176. }
  10177. /**
  10178. * Check if the type is supported by this tech.
  10179. *
  10180. * The base tech does not support any type, but source handlers might
  10181. * overwrite this.
  10182. *
  10183. * @param {string} _type
  10184. * The media type to check
  10185. * @return {string} Returns the native video element's response
  10186. */
  10187. static canPlayType(_type) {
  10188. return '';
  10189. }
  10190. /**
  10191. * Check if the tech can support the given source
  10192. *
  10193. * @param {Object} srcObj
  10194. * The source object
  10195. * @param {Object} options
  10196. * The options passed to the tech
  10197. * @return {string} 'probably', 'maybe', or '' (empty string)
  10198. */
  10199. static canPlaySource(srcObj, options) {
  10200. return Tech.canPlayType(srcObj.type);
  10201. }
  10202. /*
  10203. * Return whether the argument is a Tech or not.
  10204. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  10205. *
  10206. * @param {Object} component
  10207. * The item to check
  10208. *
  10209. * @return {boolean}
  10210. * Whether it is a tech or not
  10211. * - True if it is a tech
  10212. * - False if it is not
  10213. */
  10214. static isTech(component) {
  10215. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  10216. }
  10217. /**
  10218. * Registers a `Tech` into a shared list for videojs.
  10219. *
  10220. * @param {string} name
  10221. * Name of the `Tech` to register.
  10222. *
  10223. * @param {Object} tech
  10224. * The `Tech` class to register.
  10225. */
  10226. static registerTech(name, tech) {
  10227. if (!Tech.techs_) {
  10228. Tech.techs_ = {};
  10229. }
  10230. if (!Tech.isTech(tech)) {
  10231. throw new Error(`Tech ${name} must be a Tech`);
  10232. }
  10233. if (!Tech.canPlayType) {
  10234. throw new Error('Techs must have a static canPlayType method on them');
  10235. }
  10236. if (!Tech.canPlaySource) {
  10237. throw new Error('Techs must have a static canPlaySource method on them');
  10238. }
  10239. name = toTitleCase(name);
  10240. Tech.techs_[name] = tech;
  10241. Tech.techs_[toLowerCase(name)] = tech;
  10242. if (name !== 'Tech') {
  10243. // camel case the techName for use in techOrder
  10244. Tech.defaultTechOrder_.push(name);
  10245. }
  10246. return tech;
  10247. }
  10248. /**
  10249. * Get a `Tech` from the shared list by name.
  10250. *
  10251. * @param {string} name
  10252. * `camelCase` or `TitleCase` name of the Tech to get
  10253. *
  10254. * @return {Tech|undefined}
  10255. * The `Tech` or undefined if there was no tech with the name requested.
  10256. */
  10257. static getTech(name) {
  10258. if (!name) {
  10259. return;
  10260. }
  10261. if (Tech.techs_ && Tech.techs_[name]) {
  10262. return Tech.techs_[name];
  10263. }
  10264. name = toTitleCase(name);
  10265. if (window && window.videojs && window.videojs[name]) {
  10266. log.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  10267. return window.videojs[name];
  10268. }
  10269. }
  10270. }
  10271. /**
  10272. * Get the {@link VideoTrackList}
  10273. *
  10274. * @returns {VideoTrackList}
  10275. * @method Tech.prototype.videoTracks
  10276. */
  10277. /**
  10278. * Get the {@link AudioTrackList}
  10279. *
  10280. * @returns {AudioTrackList}
  10281. * @method Tech.prototype.audioTracks
  10282. */
  10283. /**
  10284. * Get the {@link TextTrackList}
  10285. *
  10286. * @returns {TextTrackList}
  10287. * @method Tech.prototype.textTracks
  10288. */
  10289. /**
  10290. * Get the remote element {@link TextTrackList}
  10291. *
  10292. * @returns {TextTrackList}
  10293. * @method Tech.prototype.remoteTextTracks
  10294. */
  10295. /**
  10296. * Get the remote element {@link HtmlTrackElementList}
  10297. *
  10298. * @returns {HtmlTrackElementList}
  10299. * @method Tech.prototype.remoteTextTrackEls
  10300. */
  10301. ALL.names.forEach(function (name) {
  10302. const props = ALL[name];
  10303. Tech.prototype[props.getterName] = function () {
  10304. this[props.privateName] = this[props.privateName] || new props.ListClass();
  10305. return this[props.privateName];
  10306. };
  10307. });
  10308. /**
  10309. * List of associated text tracks
  10310. *
  10311. * @type {TextTrackList}
  10312. * @private
  10313. * @property Tech#textTracks_
  10314. */
  10315. /**
  10316. * List of associated audio tracks.
  10317. *
  10318. * @type {AudioTrackList}
  10319. * @private
  10320. * @property Tech#audioTracks_
  10321. */
  10322. /**
  10323. * List of associated video tracks.
  10324. *
  10325. * @type {VideoTrackList}
  10326. * @private
  10327. * @property Tech#videoTracks_
  10328. */
  10329. /**
  10330. * Boolean indicating whether the `Tech` supports volume control.
  10331. *
  10332. * @type {boolean}
  10333. * @default
  10334. */
  10335. Tech.prototype.featuresVolumeControl = true;
  10336. /**
  10337. * Boolean indicating whether the `Tech` supports muting volume.
  10338. *
  10339. * @type {boolean}
  10340. * @default
  10341. */
  10342. Tech.prototype.featuresMuteControl = true;
  10343. /**
  10344. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  10345. * Resizing plugins using request fullscreen reloads the plugin
  10346. *
  10347. * @type {boolean}
  10348. * @default
  10349. */
  10350. Tech.prototype.featuresFullscreenResize = false;
  10351. /**
  10352. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  10353. * plays. Examples:
  10354. * - Set player to play 2x (twice) as fast
  10355. * - Set player to play 0.5x (half) as fast
  10356. *
  10357. * @type {boolean}
  10358. * @default
  10359. */
  10360. Tech.prototype.featuresPlaybackRate = false;
  10361. /**
  10362. * Boolean indicating whether the `Tech` supports the `progress` event.
  10363. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  10364. *
  10365. * @type {boolean}
  10366. * @default
  10367. */
  10368. Tech.prototype.featuresProgressEvents = false;
  10369. /**
  10370. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  10371. *
  10372. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  10373. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  10374. * a new source.
  10375. *
  10376. * @type {boolean}
  10377. * @default
  10378. */
  10379. Tech.prototype.featuresSourceset = false;
  10380. /**
  10381. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  10382. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  10383. *
  10384. * @type {boolean}
  10385. * @default
  10386. */
  10387. Tech.prototype.featuresTimeupdateEvents = false;
  10388. /**
  10389. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  10390. * This will help us integrate with native `TextTrack`s if the browser supports them.
  10391. *
  10392. * @type {boolean}
  10393. * @default
  10394. */
  10395. Tech.prototype.featuresNativeTextTracks = false;
  10396. /**
  10397. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  10398. *
  10399. * @type {boolean}
  10400. * @default
  10401. */
  10402. Tech.prototype.featuresVideoFrameCallback = false;
  10403. /**
  10404. * A functional mixin for techs that want to use the Source Handler pattern.
  10405. * Source handlers are scripts for handling specific formats.
  10406. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  10407. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  10408. * Example: `Tech.withSourceHandlers.call(MyTech);`
  10409. *
  10410. * @param {Tech} _Tech
  10411. * The tech to add source handler functions to.
  10412. *
  10413. * @mixes Tech~SourceHandlerAdditions
  10414. */
  10415. Tech.withSourceHandlers = function (_Tech) {
  10416. /**
  10417. * Register a source handler
  10418. *
  10419. * @param {Function} handler
  10420. * The source handler class
  10421. *
  10422. * @param {number} [index]
  10423. * Register it at the following index
  10424. */
  10425. _Tech.registerSourceHandler = function (handler, index) {
  10426. let handlers = _Tech.sourceHandlers;
  10427. if (!handlers) {
  10428. handlers = _Tech.sourceHandlers = [];
  10429. }
  10430. if (index === undefined) {
  10431. // add to the end of the list
  10432. index = handlers.length;
  10433. }
  10434. handlers.splice(index, 0, handler);
  10435. };
  10436. /**
  10437. * Check if the tech can support the given type. Also checks the
  10438. * Techs sourceHandlers.
  10439. *
  10440. * @param {string} type
  10441. * The mimetype to check.
  10442. *
  10443. * @return {string}
  10444. * 'probably', 'maybe', or '' (empty string)
  10445. */
  10446. _Tech.canPlayType = function (type) {
  10447. const handlers = _Tech.sourceHandlers || [];
  10448. let can;
  10449. for (let i = 0; i < handlers.length; i++) {
  10450. can = handlers[i].canPlayType(type);
  10451. if (can) {
  10452. return can;
  10453. }
  10454. }
  10455. return '';
  10456. };
  10457. /**
  10458. * Returns the first source handler that supports the source.
  10459. *
  10460. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  10461. *
  10462. * @param {Tech~SourceObject} source
  10463. * The source object
  10464. *
  10465. * @param {Object} options
  10466. * The options passed to the tech
  10467. *
  10468. * @return {SourceHandler|null}
  10469. * The first source handler that supports the source or null if
  10470. * no SourceHandler supports the source
  10471. */
  10472. _Tech.selectSourceHandler = function (source, options) {
  10473. const handlers = _Tech.sourceHandlers || [];
  10474. let can;
  10475. for (let i = 0; i < handlers.length; i++) {
  10476. can = handlers[i].canHandleSource(source, options);
  10477. if (can) {
  10478. return handlers[i];
  10479. }
  10480. }
  10481. return null;
  10482. };
  10483. /**
  10484. * Check if the tech can support the given source.
  10485. *
  10486. * @param {Tech~SourceObject} srcObj
  10487. * The source object
  10488. *
  10489. * @param {Object} options
  10490. * The options passed to the tech
  10491. *
  10492. * @return {string}
  10493. * 'probably', 'maybe', or '' (empty string)
  10494. */
  10495. _Tech.canPlaySource = function (srcObj, options) {
  10496. const sh = _Tech.selectSourceHandler(srcObj, options);
  10497. if (sh) {
  10498. return sh.canHandleSource(srcObj, options);
  10499. }
  10500. return '';
  10501. };
  10502. /**
  10503. * When using a source handler, prefer its implementation of
  10504. * any function normally provided by the tech.
  10505. */
  10506. const deferrable = ['seekable', 'seeking', 'duration'];
  10507. /**
  10508. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  10509. * function if it exists, with a fallback to the Techs seekable function.
  10510. *
  10511. * @method _Tech.seekable
  10512. */
  10513. /**
  10514. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  10515. * function if it exists, otherwise it will fallback to the techs duration function.
  10516. *
  10517. * @method _Tech.duration
  10518. */
  10519. deferrable.forEach(function (fnName) {
  10520. const originalFn = this[fnName];
  10521. if (typeof originalFn !== 'function') {
  10522. return;
  10523. }
  10524. this[fnName] = function () {
  10525. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  10526. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  10527. }
  10528. return originalFn.apply(this, arguments);
  10529. };
  10530. }, _Tech.prototype);
  10531. /**
  10532. * Create a function for setting the source using a source object
  10533. * and source handlers.
  10534. * Should never be called unless a source handler was found.
  10535. *
  10536. * @param {Tech~SourceObject} source
  10537. * A source object with src and type keys
  10538. */
  10539. _Tech.prototype.setSource = function (source) {
  10540. let sh = _Tech.selectSourceHandler(source, this.options_);
  10541. if (!sh) {
  10542. // Fall back to a native source handler when unsupported sources are
  10543. // deliberately set
  10544. if (_Tech.nativeSourceHandler) {
  10545. sh = _Tech.nativeSourceHandler;
  10546. } else {
  10547. log.error('No source handler found for the current source.');
  10548. }
  10549. }
  10550. // Dispose any existing source handler
  10551. this.disposeSourceHandler();
  10552. this.off('dispose', this.disposeSourceHandler_);
  10553. if (sh !== _Tech.nativeSourceHandler) {
  10554. this.currentSource_ = source;
  10555. }
  10556. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  10557. this.one('dispose', this.disposeSourceHandler_);
  10558. };
  10559. /**
  10560. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  10561. *
  10562. * @listens Tech#dispose
  10563. */
  10564. _Tech.prototype.disposeSourceHandler = function () {
  10565. // if we have a source and get another one
  10566. // then we are loading something new
  10567. // than clear all of our current tracks
  10568. if (this.currentSource_) {
  10569. this.clearTracks(['audio', 'video']);
  10570. this.currentSource_ = null;
  10571. }
  10572. // always clean up auto-text tracks
  10573. this.cleanupAutoTextTracks();
  10574. if (this.sourceHandler_) {
  10575. if (this.sourceHandler_.dispose) {
  10576. this.sourceHandler_.dispose();
  10577. }
  10578. this.sourceHandler_ = null;
  10579. }
  10580. };
  10581. };
  10582. // The base Tech class needs to be registered as a Component. It is the only
  10583. // Tech that can be registered as a Component.
  10584. Component.registerComponent('Tech', Tech);
  10585. Tech.registerTech('Tech', Tech);
  10586. /**
  10587. * A list of techs that should be added to techOrder on Players
  10588. *
  10589. * @private
  10590. */
  10591. Tech.defaultTechOrder_ = [];
  10592. /**
  10593. * @file middleware.js
  10594. * @module middleware
  10595. */
  10596. const middlewares = {};
  10597. const middlewareInstances = {};
  10598. const TERMINATOR = {};
  10599. /**
  10600. * A middleware object is a plain JavaScript object that has methods that
  10601. * match the {@link Tech} methods found in the lists of allowed
  10602. * {@link module:middleware.allowedGetters|getters},
  10603. * {@link module:middleware.allowedSetters|setters}, and
  10604. * {@link module:middleware.allowedMediators|mediators}.
  10605. *
  10606. * @typedef {Object} MiddlewareObject
  10607. */
  10608. /**
  10609. * A middleware factory function that should return a
  10610. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  10611. *
  10612. * This factory will be called for each player when needed, with the player
  10613. * passed in as an argument.
  10614. *
  10615. * @callback MiddlewareFactory
  10616. * @param { import('../player').default } player
  10617. * A Video.js player.
  10618. */
  10619. /**
  10620. * Define a middleware that the player should use by way of a factory function
  10621. * that returns a middleware object.
  10622. *
  10623. * @param {string} type
  10624. * The MIME type to match or `"*"` for all MIME types.
  10625. *
  10626. * @param {MiddlewareFactory} middleware
  10627. * A middleware factory function that will be executed for
  10628. * matching types.
  10629. */
  10630. function use(type, middleware) {
  10631. middlewares[type] = middlewares[type] || [];
  10632. middlewares[type].push(middleware);
  10633. }
  10634. /**
  10635. * Asynchronously sets a source using middleware by recursing through any
  10636. * matching middlewares and calling `setSource` on each, passing along the
  10637. * previous returned value each time.
  10638. *
  10639. * @param { import('../player').default } player
  10640. * A {@link Player} instance.
  10641. *
  10642. * @param {Tech~SourceObject} src
  10643. * A source object.
  10644. *
  10645. * @param {Function}
  10646. * The next middleware to run.
  10647. */
  10648. function setSource(player, src, next) {
  10649. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  10650. }
  10651. /**
  10652. * When the tech is set, passes the tech to each middleware's `setTech` method.
  10653. *
  10654. * @param {Object[]} middleware
  10655. * An array of middleware instances.
  10656. *
  10657. * @param { import('../tech/tech').default } tech
  10658. * A Video.js tech.
  10659. */
  10660. function setTech(middleware, tech) {
  10661. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  10662. }
  10663. /**
  10664. * Calls a getter on the tech first, through each middleware
  10665. * from right to left to the player.
  10666. *
  10667. * @param {Object[]} middleware
  10668. * An array of middleware instances.
  10669. *
  10670. * @param { import('../tech/tech').default } tech
  10671. * The current tech.
  10672. *
  10673. * @param {string} method
  10674. * A method name.
  10675. *
  10676. * @return {*}
  10677. * The final value from the tech after middleware has intercepted it.
  10678. */
  10679. function get(middleware, tech, method) {
  10680. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  10681. }
  10682. /**
  10683. * Takes the argument given to the player and calls the setter method on each
  10684. * middleware from left to right to the tech.
  10685. *
  10686. * @param {Object[]} middleware
  10687. * An array of middleware instances.
  10688. *
  10689. * @param { import('../tech/tech').default } tech
  10690. * The current tech.
  10691. *
  10692. * @param {string} method
  10693. * A method name.
  10694. *
  10695. * @param {*} arg
  10696. * The value to set on the tech.
  10697. *
  10698. * @return {*}
  10699. * The return value of the `method` of the `tech`.
  10700. */
  10701. function set(middleware, tech, method, arg) {
  10702. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  10703. }
  10704. /**
  10705. * Takes the argument given to the player and calls the `call` version of the
  10706. * method on each middleware from left to right.
  10707. *
  10708. * Then, call the passed in method on the tech and return the result unchanged
  10709. * back to the player, through middleware, this time from right to left.
  10710. *
  10711. * @param {Object[]} middleware
  10712. * An array of middleware instances.
  10713. *
  10714. * @param { import('../tech/tech').default } tech
  10715. * The current tech.
  10716. *
  10717. * @param {string} method
  10718. * A method name.
  10719. *
  10720. * @param {*} arg
  10721. * The value to set on the tech.
  10722. *
  10723. * @return {*}
  10724. * The return value of the `method` of the `tech`, regardless of the
  10725. * return values of middlewares.
  10726. */
  10727. function mediate(middleware, tech, method, arg = null) {
  10728. const callMethod = 'call' + toTitleCase(method);
  10729. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  10730. const terminated = middlewareValue === TERMINATOR;
  10731. // deprecated. The `null` return value should instead return TERMINATOR to
  10732. // prevent confusion if a techs method actually returns null.
  10733. const returnValue = terminated ? null : tech[method](middlewareValue);
  10734. executeRight(middleware, method, returnValue, terminated);
  10735. return returnValue;
  10736. }
  10737. /**
  10738. * Enumeration of allowed getters where the keys are method names.
  10739. *
  10740. * @type {Object}
  10741. */
  10742. const allowedGetters = {
  10743. buffered: 1,
  10744. currentTime: 1,
  10745. duration: 1,
  10746. muted: 1,
  10747. played: 1,
  10748. paused: 1,
  10749. seekable: 1,
  10750. volume: 1,
  10751. ended: 1
  10752. };
  10753. /**
  10754. * Enumeration of allowed setters where the keys are method names.
  10755. *
  10756. * @type {Object}
  10757. */
  10758. const allowedSetters = {
  10759. setCurrentTime: 1,
  10760. setMuted: 1,
  10761. setVolume: 1
  10762. };
  10763. /**
  10764. * Enumeration of allowed mediators where the keys are method names.
  10765. *
  10766. * @type {Object}
  10767. */
  10768. const allowedMediators = {
  10769. play: 1,
  10770. pause: 1
  10771. };
  10772. function middlewareIterator(method) {
  10773. return (value, mw) => {
  10774. // if the previous middleware terminated, pass along the termination
  10775. if (value === TERMINATOR) {
  10776. return TERMINATOR;
  10777. }
  10778. if (mw[method]) {
  10779. return mw[method](value);
  10780. }
  10781. return value;
  10782. };
  10783. }
  10784. function executeRight(mws, method, value, terminated) {
  10785. for (let i = mws.length - 1; i >= 0; i--) {
  10786. const mw = mws[i];
  10787. if (mw[method]) {
  10788. mw[method](terminated, value);
  10789. }
  10790. }
  10791. }
  10792. /**
  10793. * Clear the middleware cache for a player.
  10794. *
  10795. * @param { import('../player').default } player
  10796. * A {@link Player} instance.
  10797. */
  10798. function clearCacheForPlayer(player) {
  10799. middlewareInstances[player.id()] = null;
  10800. }
  10801. /**
  10802. * {
  10803. * [playerId]: [[mwFactory, mwInstance], ...]
  10804. * }
  10805. *
  10806. * @private
  10807. */
  10808. function getOrCreateFactory(player, mwFactory) {
  10809. const mws = middlewareInstances[player.id()];
  10810. let mw = null;
  10811. if (mws === undefined || mws === null) {
  10812. mw = mwFactory(player);
  10813. middlewareInstances[player.id()] = [[mwFactory, mw]];
  10814. return mw;
  10815. }
  10816. for (let i = 0; i < mws.length; i++) {
  10817. const [mwf, mwi] = mws[i];
  10818. if (mwf !== mwFactory) {
  10819. continue;
  10820. }
  10821. mw = mwi;
  10822. }
  10823. if (mw === null) {
  10824. mw = mwFactory(player);
  10825. mws.push([mwFactory, mw]);
  10826. }
  10827. return mw;
  10828. }
  10829. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  10830. const [mwFactory, ...mwrest] = middleware;
  10831. // if mwFactory is a string, then we're at a fork in the road
  10832. if (typeof mwFactory === 'string') {
  10833. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  10834. // if we have an mwFactory, call it with the player to get the mw,
  10835. // then call the mw's setSource method
  10836. } else if (mwFactory) {
  10837. const mw = getOrCreateFactory(player, mwFactory);
  10838. // if setSource isn't present, implicitly select this middleware
  10839. if (!mw.setSource) {
  10840. acc.push(mw);
  10841. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10842. }
  10843. mw.setSource(Object.assign({}, src), function (err, _src) {
  10844. // something happened, try the next middleware on the current level
  10845. // make sure to use the old src
  10846. if (err) {
  10847. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10848. }
  10849. // we've succeeded, now we need to go deeper
  10850. acc.push(mw);
  10851. // if it's the same type, continue down the current chain
  10852. // otherwise, we want to go down the new chain
  10853. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  10854. });
  10855. } else if (mwrest.length) {
  10856. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10857. } else if (lastRun) {
  10858. next(src, acc);
  10859. } else {
  10860. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  10861. }
  10862. }
  10863. /**
  10864. * Mimetypes
  10865. *
  10866. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  10867. * @typedef Mimetypes~Kind
  10868. * @enum
  10869. */
  10870. const MimetypesKind = {
  10871. opus: 'video/ogg',
  10872. ogv: 'video/ogg',
  10873. mp4: 'video/mp4',
  10874. mov: 'video/mp4',
  10875. m4v: 'video/mp4',
  10876. mkv: 'video/x-matroska',
  10877. m4a: 'audio/mp4',
  10878. mp3: 'audio/mpeg',
  10879. aac: 'audio/aac',
  10880. caf: 'audio/x-caf',
  10881. flac: 'audio/flac',
  10882. oga: 'audio/ogg',
  10883. wav: 'audio/wav',
  10884. m3u8: 'application/x-mpegURL',
  10885. mpd: 'application/dash+xml',
  10886. jpg: 'image/jpeg',
  10887. jpeg: 'image/jpeg',
  10888. gif: 'image/gif',
  10889. png: 'image/png',
  10890. svg: 'image/svg+xml',
  10891. webp: 'image/webp'
  10892. };
  10893. /**
  10894. * Get the mimetype of a given src url if possible
  10895. *
  10896. * @param {string} src
  10897. * The url to the src
  10898. *
  10899. * @return {string}
  10900. * return the mimetype if it was known or empty string otherwise
  10901. */
  10902. const getMimetype = function (src = '') {
  10903. const ext = getFileExtension(src);
  10904. const mimetype = MimetypesKind[ext.toLowerCase()];
  10905. return mimetype || '';
  10906. };
  10907. /**
  10908. * Find the mime type of a given source string if possible. Uses the player
  10909. * source cache.
  10910. *
  10911. * @param { import('../player').default } player
  10912. * The player object
  10913. *
  10914. * @param {string} src
  10915. * The source string
  10916. *
  10917. * @return {string}
  10918. * The type that was found
  10919. */
  10920. const findMimetype = (player, src) => {
  10921. if (!src) {
  10922. return '';
  10923. }
  10924. // 1. check for the type in the `source` cache
  10925. if (player.cache_.source.src === src && player.cache_.source.type) {
  10926. return player.cache_.source.type;
  10927. }
  10928. // 2. see if we have this source in our `currentSources` cache
  10929. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  10930. if (matchingSources.length) {
  10931. return matchingSources[0].type;
  10932. }
  10933. // 3. look for the src url in source elements and use the type there
  10934. const sources = player.$$('source');
  10935. for (let i = 0; i < sources.length; i++) {
  10936. const s = sources[i];
  10937. if (s.type && s.src && s.src === src) {
  10938. return s.type;
  10939. }
  10940. }
  10941. // 4. finally fallback to our list of mime types based on src url extension
  10942. return getMimetype(src);
  10943. };
  10944. /**
  10945. * @module filter-source
  10946. */
  10947. /**
  10948. * Filter out single bad source objects or multiple source objects in an
  10949. * array. Also flattens nested source object arrays into a 1 dimensional
  10950. * array of source objects.
  10951. *
  10952. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  10953. * The src object to filter
  10954. *
  10955. * @return {Tech~SourceObject[]}
  10956. * An array of sourceobjects containing only valid sources
  10957. *
  10958. * @private
  10959. */
  10960. const filterSource = function (src) {
  10961. // traverse array
  10962. if (Array.isArray(src)) {
  10963. let newsrc = [];
  10964. src.forEach(function (srcobj) {
  10965. srcobj = filterSource(srcobj);
  10966. if (Array.isArray(srcobj)) {
  10967. newsrc = newsrc.concat(srcobj);
  10968. } else if (isObject(srcobj)) {
  10969. newsrc.push(srcobj);
  10970. }
  10971. });
  10972. src = newsrc;
  10973. } else if (typeof src === 'string' && src.trim()) {
  10974. // convert string into object
  10975. src = [fixSource({
  10976. src
  10977. })];
  10978. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  10979. // src is already valid
  10980. src = [fixSource(src)];
  10981. } else {
  10982. // invalid source, turn it into an empty array
  10983. src = [];
  10984. }
  10985. return src;
  10986. };
  10987. /**
  10988. * Checks src mimetype, adding it when possible
  10989. *
  10990. * @param {Tech~SourceObject} src
  10991. * The src object to check
  10992. * @return {Tech~SourceObject}
  10993. * src Object with known type
  10994. */
  10995. function fixSource(src) {
  10996. if (!src.type) {
  10997. const mimetype = getMimetype(src.src);
  10998. if (mimetype) {
  10999. src.type = mimetype;
  11000. }
  11001. }
  11002. return src;
  11003. }
  11004. /**
  11005. * @file loader.js
  11006. */
  11007. /**
  11008. * The `MediaLoader` is the `Component` that decides which playback technology to load
  11009. * when a player is initialized.
  11010. *
  11011. * @extends Component
  11012. */
  11013. class MediaLoader extends Component {
  11014. /**
  11015. * Create an instance of this class.
  11016. *
  11017. * @param { import('../player').default } player
  11018. * The `Player` that this class should attach to.
  11019. *
  11020. * @param {Object} [options]
  11021. * The key/value store of player options.
  11022. *
  11023. * @param {Function} [ready]
  11024. * The function that is run when this component is ready.
  11025. */
  11026. constructor(player, options, ready) {
  11027. // MediaLoader has no element
  11028. const options_ = merge({
  11029. createEl: false
  11030. }, options);
  11031. super(player, options_, ready);
  11032. // If there are no sources when the player is initialized,
  11033. // load the first supported playback technology.
  11034. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  11035. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  11036. const techName = toTitleCase(j[i]);
  11037. let tech = Tech.getTech(techName);
  11038. // Support old behavior of techs being registered as components.
  11039. // Remove once that deprecated behavior is removed.
  11040. if (!techName) {
  11041. tech = Component.getComponent(techName);
  11042. }
  11043. // Check if the browser supports this technology
  11044. if (tech && tech.isSupported()) {
  11045. player.loadTech_(techName);
  11046. break;
  11047. }
  11048. }
  11049. } else {
  11050. // Loop through playback technologies (e.g. HTML5) and check for support.
  11051. // Then load the best source.
  11052. // A few assumptions here:
  11053. // All playback technologies respect preload false.
  11054. player.src(options.playerOptions.sources);
  11055. }
  11056. }
  11057. }
  11058. Component.registerComponent('MediaLoader', MediaLoader);
  11059. /**
  11060. * @file clickable-component.js
  11061. */
  11062. /**
  11063. * Component which is clickable or keyboard actionable, but is not a
  11064. * native HTML button.
  11065. *
  11066. * @extends Component
  11067. */
  11068. class ClickableComponent extends Component {
  11069. /**
  11070. * Creates an instance of this class.
  11071. *
  11072. * @param { import('./player').default } player
  11073. * The `Player` that this class should be attached to.
  11074. *
  11075. * @param {Object} [options]
  11076. * The key/value store of component options.
  11077. *
  11078. * @param {function} [options.clickHandler]
  11079. * The function to call when the button is clicked / activated
  11080. *
  11081. * @param {string} [options.controlText]
  11082. * The text to set on the button
  11083. *
  11084. * @param {string} [options.className]
  11085. * A class or space separated list of classes to add the component
  11086. *
  11087. */
  11088. constructor(player, options) {
  11089. super(player, options);
  11090. if (this.options_.controlText) {
  11091. this.controlText(this.options_.controlText);
  11092. }
  11093. this.handleMouseOver_ = e => this.handleMouseOver(e);
  11094. this.handleMouseOut_ = e => this.handleMouseOut(e);
  11095. this.handleClick_ = e => this.handleClick(e);
  11096. this.handleKeyDown_ = e => this.handleKeyDown(e);
  11097. this.emitTapEvents();
  11098. this.enable();
  11099. }
  11100. /**
  11101. * Create the `ClickableComponent`s DOM element.
  11102. *
  11103. * @param {string} [tag=div]
  11104. * The element's node type.
  11105. *
  11106. * @param {Object} [props={}]
  11107. * An object of properties that should be set on the element.
  11108. *
  11109. * @param {Object} [attributes={}]
  11110. * An object of attributes that should be set on the element.
  11111. *
  11112. * @return {Element}
  11113. * The element that gets created.
  11114. */
  11115. createEl(tag = 'div', props = {}, attributes = {}) {
  11116. props = Object.assign({
  11117. className: this.buildCSSClass(),
  11118. tabIndex: 0
  11119. }, props);
  11120. if (tag === 'button') {
  11121. log.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  11122. }
  11123. // Add ARIA attributes for clickable element which is not a native HTML button
  11124. attributes = Object.assign({
  11125. role: 'button'
  11126. }, attributes);
  11127. this.tabIndex_ = props.tabIndex;
  11128. const el = createEl(tag, props, attributes);
  11129. el.appendChild(createEl('span', {
  11130. className: 'vjs-icon-placeholder'
  11131. }, {
  11132. 'aria-hidden': true
  11133. }));
  11134. this.createControlTextEl(el);
  11135. return el;
  11136. }
  11137. dispose() {
  11138. // remove controlTextEl_ on dispose
  11139. this.controlTextEl_ = null;
  11140. super.dispose();
  11141. }
  11142. /**
  11143. * Create a control text element on this `ClickableComponent`
  11144. *
  11145. * @param {Element} [el]
  11146. * Parent element for the control text.
  11147. *
  11148. * @return {Element}
  11149. * The control text element that gets created.
  11150. */
  11151. createControlTextEl(el) {
  11152. this.controlTextEl_ = createEl('span', {
  11153. className: 'vjs-control-text'
  11154. }, {
  11155. // let the screen reader user know that the text of the element may change
  11156. 'aria-live': 'polite'
  11157. });
  11158. if (el) {
  11159. el.appendChild(this.controlTextEl_);
  11160. }
  11161. this.controlText(this.controlText_, el);
  11162. return this.controlTextEl_;
  11163. }
  11164. /**
  11165. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  11166. *
  11167. * @param {string} [text]
  11168. * Control text for element.
  11169. *
  11170. * @param {Element} [el=this.el()]
  11171. * Element to set the title on.
  11172. *
  11173. * @return {string}
  11174. * - The control text when getting
  11175. */
  11176. controlText(text, el = this.el()) {
  11177. if (text === undefined) {
  11178. return this.controlText_ || 'Need Text';
  11179. }
  11180. const localizedText = this.localize(text);
  11181. /** @protected */
  11182. this.controlText_ = text;
  11183. textContent(this.controlTextEl_, localizedText);
  11184. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  11185. // Set title attribute if only an icon is shown
  11186. el.setAttribute('title', localizedText);
  11187. }
  11188. }
  11189. /**
  11190. * Builds the default DOM `className`.
  11191. *
  11192. * @return {string}
  11193. * The DOM `className` for this object.
  11194. */
  11195. buildCSSClass() {
  11196. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  11197. }
  11198. /**
  11199. * Enable this `ClickableComponent`
  11200. */
  11201. enable() {
  11202. if (!this.enabled_) {
  11203. this.enabled_ = true;
  11204. this.removeClass('vjs-disabled');
  11205. this.el_.setAttribute('aria-disabled', 'false');
  11206. if (typeof this.tabIndex_ !== 'undefined') {
  11207. this.el_.setAttribute('tabIndex', this.tabIndex_);
  11208. }
  11209. this.on(['tap', 'click'], this.handleClick_);
  11210. this.on('keydown', this.handleKeyDown_);
  11211. }
  11212. }
  11213. /**
  11214. * Disable this `ClickableComponent`
  11215. */
  11216. disable() {
  11217. this.enabled_ = false;
  11218. this.addClass('vjs-disabled');
  11219. this.el_.setAttribute('aria-disabled', 'true');
  11220. if (typeof this.tabIndex_ !== 'undefined') {
  11221. this.el_.removeAttribute('tabIndex');
  11222. }
  11223. this.off('mouseover', this.handleMouseOver_);
  11224. this.off('mouseout', this.handleMouseOut_);
  11225. this.off(['tap', 'click'], this.handleClick_);
  11226. this.off('keydown', this.handleKeyDown_);
  11227. }
  11228. /**
  11229. * Handles language change in ClickableComponent for the player in components
  11230. *
  11231. *
  11232. */
  11233. handleLanguagechange() {
  11234. this.controlText(this.controlText_);
  11235. }
  11236. /**
  11237. * Event handler that is called when a `ClickableComponent` receives a
  11238. * `click` or `tap` event.
  11239. *
  11240. * @param {Event} event
  11241. * The `tap` or `click` event that caused this function to be called.
  11242. *
  11243. * @listens tap
  11244. * @listens click
  11245. * @abstract
  11246. */
  11247. handleClick(event) {
  11248. if (this.options_.clickHandler) {
  11249. this.options_.clickHandler.call(this, arguments);
  11250. }
  11251. }
  11252. /**
  11253. * Event handler that is called when a `ClickableComponent` receives a
  11254. * `keydown` event.
  11255. *
  11256. * By default, if the key is Space or Enter, it will trigger a `click` event.
  11257. *
  11258. * @param {Event} event
  11259. * The `keydown` event that caused this function to be called.
  11260. *
  11261. * @listens keydown
  11262. */
  11263. handleKeyDown(event) {
  11264. // Support Space or Enter key operation to fire a click event. Also,
  11265. // prevent the event from propagating through the DOM and triggering
  11266. // Player hotkeys.
  11267. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11268. event.preventDefault();
  11269. event.stopPropagation();
  11270. this.trigger('click');
  11271. } else {
  11272. // Pass keypress handling up for unsupported keys
  11273. super.handleKeyDown(event);
  11274. }
  11275. }
  11276. }
  11277. Component.registerComponent('ClickableComponent', ClickableComponent);
  11278. /**
  11279. * @file poster-image.js
  11280. */
  11281. /**
  11282. * A `ClickableComponent` that handles showing the poster image for the player.
  11283. *
  11284. * @extends ClickableComponent
  11285. */
  11286. class PosterImage extends ClickableComponent {
  11287. /**
  11288. * Create an instance of this class.
  11289. *
  11290. * @param { import('./player').default } player
  11291. * The `Player` that this class should attach to.
  11292. *
  11293. * @param {Object} [options]
  11294. * The key/value store of player options.
  11295. */
  11296. constructor(player, options) {
  11297. super(player, options);
  11298. this.update();
  11299. this.update_ = e => this.update(e);
  11300. player.on('posterchange', this.update_);
  11301. }
  11302. /**
  11303. * Clean up and dispose of the `PosterImage`.
  11304. */
  11305. dispose() {
  11306. this.player().off('posterchange', this.update_);
  11307. super.dispose();
  11308. }
  11309. /**
  11310. * Create the `PosterImage`s DOM element.
  11311. *
  11312. * @return {Element}
  11313. * The element that gets created.
  11314. */
  11315. createEl() {
  11316. // The el is an empty div to keep position in the DOM
  11317. // A picture and img el will be inserted when a source is set
  11318. return createEl('div', {
  11319. className: 'vjs-poster'
  11320. });
  11321. }
  11322. /**
  11323. * Get or set the `PosterImage`'s crossOrigin option.
  11324. *
  11325. * @param {string|null} [value]
  11326. * The value to set the crossOrigin to. If an argument is
  11327. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  11328. *
  11329. * @return {string|null}
  11330. * - The current crossOrigin value of the `Player` when getting.
  11331. * - undefined when setting
  11332. */
  11333. crossOrigin(value) {
  11334. // `null` can be set to unset a value
  11335. if (typeof value === 'undefined') {
  11336. if (this.$('img')) {
  11337. // If the poster's element exists, give its value
  11338. return this.$('img').crossOrigin;
  11339. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  11340. // If not but the tech is ready, query the tech
  11341. return this.player_.crossOrigin();
  11342. }
  11343. // Otherwise check options as the poster is usually set before the state of crossorigin
  11344. // can be retrieved by the getter
  11345. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  11346. }
  11347. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  11348. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  11349. return;
  11350. }
  11351. if (this.$('img')) {
  11352. this.$('img').crossOrigin = value;
  11353. }
  11354. return;
  11355. }
  11356. /**
  11357. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  11358. *
  11359. * @listens Player#posterchange
  11360. *
  11361. * @param {Event} [event]
  11362. * The `Player#posterchange` event that triggered this function.
  11363. */
  11364. update(event) {
  11365. const url = this.player().poster();
  11366. this.setSrc(url);
  11367. // If there's no poster source we should display:none on this component
  11368. // so it's not still clickable or right-clickable
  11369. if (url) {
  11370. this.show();
  11371. } else {
  11372. this.hide();
  11373. }
  11374. }
  11375. /**
  11376. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  11377. * the inner picture and img elementss when needed.
  11378. *
  11379. * @param {string} [url]
  11380. * The URL to the source for the `PosterImage`. If not specified or falsy,
  11381. * any source and ant inner picture/img are removed.
  11382. */
  11383. setSrc(url) {
  11384. if (!url) {
  11385. this.el_.textContent = '';
  11386. return;
  11387. }
  11388. if (!this.$('img')) {
  11389. this.el_.appendChild(createEl('picture', {
  11390. className: 'vjs-poster',
  11391. // Don't want poster to be tabbable.
  11392. tabIndex: -1
  11393. }, {}, createEl('img', {
  11394. loading: 'lazy',
  11395. crossOrigin: this.crossOrigin()
  11396. }, {
  11397. alt: ''
  11398. })));
  11399. }
  11400. this.$('img').src = url;
  11401. }
  11402. /**
  11403. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  11404. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  11405. *
  11406. * @listens tap
  11407. * @listens click
  11408. * @listens keydown
  11409. *
  11410. * @param {Event} event
  11411. + The `click`, `tap` or `keydown` event that caused this function to be called.
  11412. */
  11413. handleClick(event) {
  11414. // We don't want a click to trigger playback when controls are disabled
  11415. if (!this.player_.controls()) {
  11416. return;
  11417. }
  11418. if (this.player_.tech(true)) {
  11419. this.player_.tech(true).focus();
  11420. }
  11421. if (this.player_.paused()) {
  11422. silencePromise(this.player_.play());
  11423. } else {
  11424. this.player_.pause();
  11425. }
  11426. }
  11427. }
  11428. /**
  11429. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  11430. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  11431. * behavior.
  11432. *
  11433. * @param {string|null} [value]
  11434. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  11435. * given, must be one of `anonymous` or `use-credentials`.
  11436. *
  11437. * @return {string|null|undefined}
  11438. * - The current crossorigin value of the `Player` when getting.
  11439. * - undefined when setting
  11440. */
  11441. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  11442. Component.registerComponent('PosterImage', PosterImage);
  11443. /**
  11444. * @file text-track-display.js
  11445. */
  11446. const darkGray = '#222';
  11447. const lightGray = '#ccc';
  11448. const fontMap = {
  11449. monospace: 'monospace',
  11450. sansSerif: 'sans-serif',
  11451. serif: 'serif',
  11452. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  11453. monospaceSerif: '"Courier New", monospace',
  11454. proportionalSansSerif: 'sans-serif',
  11455. proportionalSerif: 'serif',
  11456. casual: '"Comic Sans MS", Impact, fantasy',
  11457. script: '"Monotype Corsiva", cursive',
  11458. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  11459. };
  11460. /**
  11461. * Construct an rgba color from a given hex color code.
  11462. *
  11463. * @param {number} color
  11464. * Hex number for color, like #f0e or #f604e2.
  11465. *
  11466. * @param {number} opacity
  11467. * Value for opacity, 0.0 - 1.0.
  11468. *
  11469. * @return {string}
  11470. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  11471. */
  11472. function constructColor(color, opacity) {
  11473. let hex;
  11474. if (color.length === 4) {
  11475. // color looks like "#f0e"
  11476. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  11477. } else if (color.length === 7) {
  11478. // color looks like "#f604e2"
  11479. hex = color.slice(1);
  11480. } else {
  11481. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  11482. }
  11483. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  11484. }
  11485. /**
  11486. * Try to update the style of a DOM element. Some style changes will throw an error,
  11487. * particularly in IE8. Those should be noops.
  11488. *
  11489. * @param {Element} el
  11490. * The DOM element to be styled.
  11491. *
  11492. * @param {string} style
  11493. * The CSS property on the element that should be styled.
  11494. *
  11495. * @param {string} rule
  11496. * The style rule that should be applied to the property.
  11497. *
  11498. * @private
  11499. */
  11500. function tryUpdateStyle(el, style, rule) {
  11501. try {
  11502. el.style[style] = rule;
  11503. } catch (e) {
  11504. // Satisfies linter.
  11505. return;
  11506. }
  11507. }
  11508. /**
  11509. * The component for displaying text track cues.
  11510. *
  11511. * @extends Component
  11512. */
  11513. class TextTrackDisplay extends Component {
  11514. /**
  11515. * Creates an instance of this class.
  11516. *
  11517. * @param { import('../player').default } player
  11518. * The `Player` that this class should be attached to.
  11519. *
  11520. * @param {Object} [options]
  11521. * The key/value store of player options.
  11522. *
  11523. * @param {Function} [ready]
  11524. * The function to call when `TextTrackDisplay` is ready.
  11525. */
  11526. constructor(player, options, ready) {
  11527. super(player, options, ready);
  11528. const updateDisplayHandler = e => this.updateDisplay(e);
  11529. player.on('loadstart', e => this.toggleDisplay(e));
  11530. player.on('texttrackchange', updateDisplayHandler);
  11531. player.on('loadedmetadata', e => this.preselectTrack(e));
  11532. // This used to be called during player init, but was causing an error
  11533. // if a track should show by default and the display hadn't loaded yet.
  11534. // Should probably be moved to an external track loader when we support
  11535. // tracks that don't need a display.
  11536. player.ready(bind_(this, function () {
  11537. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  11538. this.hide();
  11539. return;
  11540. }
  11541. player.on('fullscreenchange', updateDisplayHandler);
  11542. player.on('playerresize', updateDisplayHandler);
  11543. const screenOrientation = window.screen.orientation || window;
  11544. const changeOrientationEvent = window.screen.orientation ? 'change' : 'orientationchange';
  11545. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  11546. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  11547. const tracks = this.options_.playerOptions.tracks || [];
  11548. for (let i = 0; i < tracks.length; i++) {
  11549. this.player_.addRemoteTextTrack(tracks[i], true);
  11550. }
  11551. this.preselectTrack();
  11552. }));
  11553. }
  11554. /**
  11555. * Preselect a track following this precedence:
  11556. * - matches the previously selected {@link TextTrack}'s language and kind
  11557. * - matches the previously selected {@link TextTrack}'s language only
  11558. * - is the first default captions track
  11559. * - is the first default descriptions track
  11560. *
  11561. * @listens Player#loadstart
  11562. */
  11563. preselectTrack() {
  11564. const modes = {
  11565. captions: 1,
  11566. subtitles: 1
  11567. };
  11568. const trackList = this.player_.textTracks();
  11569. const userPref = this.player_.cache_.selectedLanguage;
  11570. let firstDesc;
  11571. let firstCaptions;
  11572. let preferredTrack;
  11573. for (let i = 0; i < trackList.length; i++) {
  11574. const track = trackList[i];
  11575. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  11576. // Always choose the track that matches both language and kind
  11577. if (track.kind === userPref.kind) {
  11578. preferredTrack = track;
  11579. // or choose the first track that matches language
  11580. } else if (!preferredTrack) {
  11581. preferredTrack = track;
  11582. }
  11583. // clear everything if offTextTrackMenuItem was clicked
  11584. } else if (userPref && !userPref.enabled) {
  11585. preferredTrack = null;
  11586. firstDesc = null;
  11587. firstCaptions = null;
  11588. } else if (track.default) {
  11589. if (track.kind === 'descriptions' && !firstDesc) {
  11590. firstDesc = track;
  11591. } else if (track.kind in modes && !firstCaptions) {
  11592. firstCaptions = track;
  11593. }
  11594. }
  11595. }
  11596. // The preferredTrack matches the user preference and takes
  11597. // precedence over all the other tracks.
  11598. // So, display the preferredTrack before the first default track
  11599. // and the subtitles/captions track before the descriptions track
  11600. if (preferredTrack) {
  11601. preferredTrack.mode = 'showing';
  11602. } else if (firstCaptions) {
  11603. firstCaptions.mode = 'showing';
  11604. } else if (firstDesc) {
  11605. firstDesc.mode = 'showing';
  11606. }
  11607. }
  11608. /**
  11609. * Turn display of {@link TextTrack}'s from the current state into the other state.
  11610. * There are only two states:
  11611. * - 'shown'
  11612. * - 'hidden'
  11613. *
  11614. * @listens Player#loadstart
  11615. */
  11616. toggleDisplay() {
  11617. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  11618. this.hide();
  11619. } else {
  11620. this.show();
  11621. }
  11622. }
  11623. /**
  11624. * Create the {@link Component}'s DOM element.
  11625. *
  11626. * @return {Element}
  11627. * The element that was created.
  11628. */
  11629. createEl() {
  11630. return super.createEl('div', {
  11631. className: 'vjs-text-track-display'
  11632. }, {
  11633. 'translate': 'yes',
  11634. 'aria-live': 'off',
  11635. 'aria-atomic': 'true'
  11636. });
  11637. }
  11638. /**
  11639. * Clear all displayed {@link TextTrack}s.
  11640. */
  11641. clearDisplay() {
  11642. if (typeof window.WebVTT === 'function') {
  11643. window.WebVTT.processCues(window, [], this.el_);
  11644. }
  11645. }
  11646. /**
  11647. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  11648. * a {@link Player#fullscreenchange} is fired.
  11649. *
  11650. * @listens Player#texttrackchange
  11651. * @listens Player#fullscreenchange
  11652. */
  11653. updateDisplay() {
  11654. const tracks = this.player_.textTracks();
  11655. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  11656. this.clearDisplay();
  11657. if (allowMultipleShowingTracks) {
  11658. const showingTracks = [];
  11659. for (let i = 0; i < tracks.length; ++i) {
  11660. const track = tracks[i];
  11661. if (track.mode !== 'showing') {
  11662. continue;
  11663. }
  11664. showingTracks.push(track);
  11665. }
  11666. this.updateForTrack(showingTracks);
  11667. return;
  11668. }
  11669. // Track display prioritization model: if multiple tracks are 'showing',
  11670. // display the first 'subtitles' or 'captions' track which is 'showing',
  11671. // otherwise display the first 'descriptions' track which is 'showing'
  11672. let descriptionsTrack = null;
  11673. let captionsSubtitlesTrack = null;
  11674. let i = tracks.length;
  11675. while (i--) {
  11676. const track = tracks[i];
  11677. if (track.mode === 'showing') {
  11678. if (track.kind === 'descriptions') {
  11679. descriptionsTrack = track;
  11680. } else {
  11681. captionsSubtitlesTrack = track;
  11682. }
  11683. }
  11684. }
  11685. if (captionsSubtitlesTrack) {
  11686. if (this.getAttribute('aria-live') !== 'off') {
  11687. this.setAttribute('aria-live', 'off');
  11688. }
  11689. this.updateForTrack(captionsSubtitlesTrack);
  11690. } else if (descriptionsTrack) {
  11691. if (this.getAttribute('aria-live') !== 'assertive') {
  11692. this.setAttribute('aria-live', 'assertive');
  11693. }
  11694. this.updateForTrack(descriptionsTrack);
  11695. }
  11696. }
  11697. /**
  11698. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  11699. *
  11700. * @param {TextTrack} track
  11701. * Text track object containing active cues to style.
  11702. */
  11703. updateDisplayState(track) {
  11704. const overrides = this.player_.textTrackSettings.getValues();
  11705. const cues = track.activeCues;
  11706. let i = cues.length;
  11707. while (i--) {
  11708. const cue = cues[i];
  11709. if (!cue) {
  11710. continue;
  11711. }
  11712. const cueDiv = cue.displayState;
  11713. if (overrides.color) {
  11714. cueDiv.firstChild.style.color = overrides.color;
  11715. }
  11716. if (overrides.textOpacity) {
  11717. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  11718. }
  11719. if (overrides.backgroundColor) {
  11720. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  11721. }
  11722. if (overrides.backgroundOpacity) {
  11723. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  11724. }
  11725. if (overrides.windowColor) {
  11726. if (overrides.windowOpacity) {
  11727. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  11728. } else {
  11729. cueDiv.style.backgroundColor = overrides.windowColor;
  11730. }
  11731. }
  11732. if (overrides.edgeStyle) {
  11733. if (overrides.edgeStyle === 'dropshadow') {
  11734. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  11735. } else if (overrides.edgeStyle === 'raised') {
  11736. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  11737. } else if (overrides.edgeStyle === 'depressed') {
  11738. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  11739. } else if (overrides.edgeStyle === 'uniform') {
  11740. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  11741. }
  11742. }
  11743. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  11744. const fontSize = window.parseFloat(cueDiv.style.fontSize);
  11745. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  11746. cueDiv.style.height = 'auto';
  11747. cueDiv.style.top = 'auto';
  11748. }
  11749. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  11750. if (overrides.fontFamily === 'small-caps') {
  11751. cueDiv.firstChild.style.fontVariant = 'small-caps';
  11752. } else {
  11753. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  11754. }
  11755. }
  11756. }
  11757. }
  11758. /**
  11759. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  11760. *
  11761. * @param {TextTrack|TextTrack[]} tracks
  11762. * Text track object or text track array to be added to the list.
  11763. */
  11764. updateForTrack(tracks) {
  11765. if (!Array.isArray(tracks)) {
  11766. tracks = [tracks];
  11767. }
  11768. if (typeof window.WebVTT !== 'function' || tracks.every(track => {
  11769. return !track.activeCues;
  11770. })) {
  11771. return;
  11772. }
  11773. const cues = [];
  11774. // push all active track cues
  11775. for (let i = 0; i < tracks.length; ++i) {
  11776. const track = tracks[i];
  11777. for (let j = 0; j < track.activeCues.length; ++j) {
  11778. cues.push(track.activeCues[j]);
  11779. }
  11780. }
  11781. // removes all cues before it processes new ones
  11782. window.WebVTT.processCues(window, cues, this.el_);
  11783. // add unique class to each language text track & add settings styling if necessary
  11784. for (let i = 0; i < tracks.length; ++i) {
  11785. const track = tracks[i];
  11786. for (let j = 0; j < track.activeCues.length; ++j) {
  11787. const cueEl = track.activeCues[j].displayState;
  11788. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  11789. if (track.language) {
  11790. setAttribute(cueEl, 'lang', track.language);
  11791. }
  11792. }
  11793. if (this.player_.textTrackSettings) {
  11794. this.updateDisplayState(track);
  11795. }
  11796. }
  11797. }
  11798. }
  11799. Component.registerComponent('TextTrackDisplay', TextTrackDisplay);
  11800. /**
  11801. * @file loading-spinner.js
  11802. */
  11803. /**
  11804. * A loading spinner for use during waiting/loading events.
  11805. *
  11806. * @extends Component
  11807. */
  11808. class LoadingSpinner extends Component {
  11809. /**
  11810. * Create the `LoadingSpinner`s DOM element.
  11811. *
  11812. * @return {Element}
  11813. * The dom element that gets created.
  11814. */
  11815. createEl() {
  11816. const isAudio = this.player_.isAudio();
  11817. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  11818. const controlText = createEl('span', {
  11819. className: 'vjs-control-text',
  11820. textContent: this.localize('{1} is loading.', [playerType])
  11821. });
  11822. const el = super.createEl('div', {
  11823. className: 'vjs-loading-spinner',
  11824. dir: 'ltr'
  11825. });
  11826. el.appendChild(controlText);
  11827. return el;
  11828. }
  11829. /**
  11830. * Update control text on languagechange
  11831. */
  11832. handleLanguagechange() {
  11833. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  11834. }
  11835. }
  11836. Component.registerComponent('LoadingSpinner', LoadingSpinner);
  11837. /**
  11838. * @file button.js
  11839. */
  11840. /**
  11841. * Base class for all buttons.
  11842. *
  11843. * @extends ClickableComponent
  11844. */
  11845. class Button extends ClickableComponent {
  11846. /**
  11847. * Create the `Button`s DOM element.
  11848. *
  11849. * @param {string} [tag="button"]
  11850. * The element's node type. This argument is IGNORED: no matter what
  11851. * is passed, it will always create a `button` element.
  11852. *
  11853. * @param {Object} [props={}]
  11854. * An object of properties that should be set on the element.
  11855. *
  11856. * @param {Object} [attributes={}]
  11857. * An object of attributes that should be set on the element.
  11858. *
  11859. * @return {Element}
  11860. * The element that gets created.
  11861. */
  11862. createEl(tag, props = {}, attributes = {}) {
  11863. tag = 'button';
  11864. props = Object.assign({
  11865. className: this.buildCSSClass()
  11866. }, props);
  11867. // Add attributes for button element
  11868. attributes = Object.assign({
  11869. // Necessary since the default button type is "submit"
  11870. type: 'button'
  11871. }, attributes);
  11872. const el = createEl(tag, props, attributes);
  11873. el.appendChild(createEl('span', {
  11874. className: 'vjs-icon-placeholder'
  11875. }, {
  11876. 'aria-hidden': true
  11877. }));
  11878. this.createControlTextEl(el);
  11879. return el;
  11880. }
  11881. /**
  11882. * Add a child `Component` inside of this `Button`.
  11883. *
  11884. * @param {string|Component} child
  11885. * The name or instance of a child to add.
  11886. *
  11887. * @param {Object} [options={}]
  11888. * The key/value store of options that will get passed to children of
  11889. * the child.
  11890. *
  11891. * @return {Component}
  11892. * The `Component` that gets added as a child. When using a string the
  11893. * `Component` will get created by this process.
  11894. *
  11895. * @deprecated since version 5
  11896. */
  11897. addChild(child, options = {}) {
  11898. const className = this.constructor.name;
  11899. log.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  11900. // Avoid the error message generated by ClickableComponent's addChild method
  11901. return Component.prototype.addChild.call(this, child, options);
  11902. }
  11903. /**
  11904. * Enable the `Button` element so that it can be activated or clicked. Use this with
  11905. * {@link Button#disable}.
  11906. */
  11907. enable() {
  11908. super.enable();
  11909. this.el_.removeAttribute('disabled');
  11910. }
  11911. /**
  11912. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  11913. * {@link Button#enable}.
  11914. */
  11915. disable() {
  11916. super.disable();
  11917. this.el_.setAttribute('disabled', 'disabled');
  11918. }
  11919. /**
  11920. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  11921. * press.
  11922. *
  11923. * @param {Event} event
  11924. * The event that caused this function to get called.
  11925. *
  11926. * @listens keydown
  11927. */
  11928. handleKeyDown(event) {
  11929. // Ignore Space or Enter key operation, which is handled by the browser for
  11930. // a button - though not for its super class, ClickableComponent. Also,
  11931. // prevent the event from propagating through the DOM and triggering Player
  11932. // hotkeys. We do not preventDefault here because we _want_ the browser to
  11933. // handle it.
  11934. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11935. event.stopPropagation();
  11936. return;
  11937. }
  11938. // Pass keypress handling up for unsupported keys
  11939. super.handleKeyDown(event);
  11940. }
  11941. }
  11942. Component.registerComponent('Button', Button);
  11943. /**
  11944. * @file big-play-button.js
  11945. */
  11946. /**
  11947. * The initial play button that shows before the video has played. The hiding of the
  11948. * `BigPlayButton` get done via CSS and `Player` states.
  11949. *
  11950. * @extends Button
  11951. */
  11952. class BigPlayButton extends Button {
  11953. constructor(player, options) {
  11954. super(player, options);
  11955. this.mouseused_ = false;
  11956. this.on('mousedown', e => this.handleMouseDown(e));
  11957. }
  11958. /**
  11959. * Builds the default DOM `className`.
  11960. *
  11961. * @return {string}
  11962. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  11963. */
  11964. buildCSSClass() {
  11965. return 'vjs-big-play-button';
  11966. }
  11967. /**
  11968. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  11969. * for more detailed information on what a click can be.
  11970. *
  11971. * @param {KeyboardEvent} event
  11972. * The `keydown`, `tap`, or `click` event that caused this function to be
  11973. * called.
  11974. *
  11975. * @listens tap
  11976. * @listens click
  11977. */
  11978. handleClick(event) {
  11979. const playPromise = this.player_.play();
  11980. // exit early if clicked via the mouse
  11981. if (this.mouseused_ && event.clientX && event.clientY) {
  11982. silencePromise(playPromise);
  11983. if (this.player_.tech(true)) {
  11984. this.player_.tech(true).focus();
  11985. }
  11986. return;
  11987. }
  11988. const cb = this.player_.getChild('controlBar');
  11989. const playToggle = cb && cb.getChild('playToggle');
  11990. if (!playToggle) {
  11991. this.player_.tech(true).focus();
  11992. return;
  11993. }
  11994. const playFocus = () => playToggle.focus();
  11995. if (isPromise(playPromise)) {
  11996. playPromise.then(playFocus, () => {});
  11997. } else {
  11998. this.setTimeout(playFocus, 1);
  11999. }
  12000. }
  12001. handleKeyDown(event) {
  12002. this.mouseused_ = false;
  12003. super.handleKeyDown(event);
  12004. }
  12005. handleMouseDown(event) {
  12006. this.mouseused_ = true;
  12007. }
  12008. }
  12009. /**
  12010. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  12011. *
  12012. * @type {string}
  12013. * @protected
  12014. */
  12015. BigPlayButton.prototype.controlText_ = 'Play Video';
  12016. Component.registerComponent('BigPlayButton', BigPlayButton);
  12017. /**
  12018. * @file close-button.js
  12019. */
  12020. /**
  12021. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  12022. * it gets clicked.
  12023. *
  12024. * @extends Button
  12025. */
  12026. class CloseButton extends Button {
  12027. /**
  12028. * Creates an instance of the this class.
  12029. *
  12030. * @param { import('./player').default } player
  12031. * The `Player` that this class should be attached to.
  12032. *
  12033. * @param {Object} [options]
  12034. * The key/value store of player options.
  12035. */
  12036. constructor(player, options) {
  12037. super(player, options);
  12038. this.controlText(options && options.controlText || this.localize('Close'));
  12039. }
  12040. /**
  12041. * Builds the default DOM `className`.
  12042. *
  12043. * @return {string}
  12044. * The DOM `className` for this object.
  12045. */
  12046. buildCSSClass() {
  12047. return `vjs-close-button ${super.buildCSSClass()}`;
  12048. }
  12049. /**
  12050. * This gets called when a `CloseButton` gets clicked. See
  12051. * {@link ClickableComponent#handleClick} for more information on when
  12052. * this will be triggered
  12053. *
  12054. * @param {Event} event
  12055. * The `keydown`, `tap`, or `click` event that caused this function to be
  12056. * called.
  12057. *
  12058. * @listens tap
  12059. * @listens click
  12060. * @fires CloseButton#close
  12061. */
  12062. handleClick(event) {
  12063. /**
  12064. * Triggered when the a `CloseButton` is clicked.
  12065. *
  12066. * @event CloseButton#close
  12067. * @type {Event}
  12068. *
  12069. * @property {boolean} [bubbles=false]
  12070. * set to false so that the close event does not
  12071. * bubble up to parents if there is no listener
  12072. */
  12073. this.trigger({
  12074. type: 'close',
  12075. bubbles: false
  12076. });
  12077. }
  12078. /**
  12079. * Event handler that is called when a `CloseButton` receives a
  12080. * `keydown` event.
  12081. *
  12082. * By default, if the key is Esc, it will trigger a `click` event.
  12083. *
  12084. * @param {Event} event
  12085. * The `keydown` event that caused this function to be called.
  12086. *
  12087. * @listens keydown
  12088. */
  12089. handleKeyDown(event) {
  12090. // Esc button will trigger `click` event
  12091. if (keycode.isEventKey(event, 'Esc')) {
  12092. event.preventDefault();
  12093. event.stopPropagation();
  12094. this.trigger('click');
  12095. } else {
  12096. // Pass keypress handling up for unsupported keys
  12097. super.handleKeyDown(event);
  12098. }
  12099. }
  12100. }
  12101. Component.registerComponent('CloseButton', CloseButton);
  12102. /**
  12103. * @file play-toggle.js
  12104. */
  12105. /**
  12106. * Button to toggle between play and pause.
  12107. *
  12108. * @extends Button
  12109. */
  12110. class PlayToggle extends Button {
  12111. /**
  12112. * Creates an instance of this class.
  12113. *
  12114. * @param { import('./player').default } player
  12115. * The `Player` that this class should be attached to.
  12116. *
  12117. * @param {Object} [options={}]
  12118. * The key/value store of player options.
  12119. */
  12120. constructor(player, options = {}) {
  12121. super(player, options);
  12122. // show or hide replay icon
  12123. options.replay = options.replay === undefined || options.replay;
  12124. this.on(player, 'play', e => this.handlePlay(e));
  12125. this.on(player, 'pause', e => this.handlePause(e));
  12126. if (options.replay) {
  12127. this.on(player, 'ended', e => this.handleEnded(e));
  12128. }
  12129. }
  12130. /**
  12131. * Builds the default DOM `className`.
  12132. *
  12133. * @return {string}
  12134. * The DOM `className` for this object.
  12135. */
  12136. buildCSSClass() {
  12137. return `vjs-play-control ${super.buildCSSClass()}`;
  12138. }
  12139. /**
  12140. * This gets called when an `PlayToggle` is "clicked". See
  12141. * {@link ClickableComponent} for more detailed information on what a click can be.
  12142. *
  12143. * @param {Event} [event]
  12144. * The `keydown`, `tap`, or `click` event that caused this function to be
  12145. * called.
  12146. *
  12147. * @listens tap
  12148. * @listens click
  12149. */
  12150. handleClick(event) {
  12151. if (this.player_.paused()) {
  12152. silencePromise(this.player_.play());
  12153. } else {
  12154. this.player_.pause();
  12155. }
  12156. }
  12157. /**
  12158. * This gets called once after the video has ended and the user seeks so that
  12159. * we can change the replay button back to a play button.
  12160. *
  12161. * @param {Event} [event]
  12162. * The event that caused this function to run.
  12163. *
  12164. * @listens Player#seeked
  12165. */
  12166. handleSeeked(event) {
  12167. this.removeClass('vjs-ended');
  12168. if (this.player_.paused()) {
  12169. this.handlePause(event);
  12170. } else {
  12171. this.handlePlay(event);
  12172. }
  12173. }
  12174. /**
  12175. * Add the vjs-playing class to the element so it can change appearance.
  12176. *
  12177. * @param {Event} [event]
  12178. * The event that caused this function to run.
  12179. *
  12180. * @listens Player#play
  12181. */
  12182. handlePlay(event) {
  12183. this.removeClass('vjs-ended', 'vjs-paused');
  12184. this.addClass('vjs-playing');
  12185. // change the button text to "Pause"
  12186. this.controlText('Pause');
  12187. }
  12188. /**
  12189. * Add the vjs-paused class to the element so it can change appearance.
  12190. *
  12191. * @param {Event} [event]
  12192. * The event that caused this function to run.
  12193. *
  12194. * @listens Player#pause
  12195. */
  12196. handlePause(event) {
  12197. this.removeClass('vjs-playing');
  12198. this.addClass('vjs-paused');
  12199. // change the button text to "Play"
  12200. this.controlText('Play');
  12201. }
  12202. /**
  12203. * Add the vjs-ended class to the element so it can change appearance
  12204. *
  12205. * @param {Event} [event]
  12206. * The event that caused this function to run.
  12207. *
  12208. * @listens Player#ended
  12209. */
  12210. handleEnded(event) {
  12211. this.removeClass('vjs-playing');
  12212. this.addClass('vjs-ended');
  12213. // change the button text to "Replay"
  12214. this.controlText('Replay');
  12215. // on the next seek remove the replay button
  12216. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  12217. }
  12218. }
  12219. /**
  12220. * The text that should display over the `PlayToggle`s controls. Added for localization.
  12221. *
  12222. * @type {string}
  12223. * @protected
  12224. */
  12225. PlayToggle.prototype.controlText_ = 'Play';
  12226. Component.registerComponent('PlayToggle', PlayToggle);
  12227. /**
  12228. * @file time-display.js
  12229. */
  12230. /**
  12231. * Displays time information about the video
  12232. *
  12233. * @extends Component
  12234. */
  12235. class TimeDisplay extends Component {
  12236. /**
  12237. * Creates an instance of this class.
  12238. *
  12239. * @param { import('../../player').default } player
  12240. * The `Player` that this class should be attached to.
  12241. *
  12242. * @param {Object} [options]
  12243. * The key/value store of player options.
  12244. */
  12245. constructor(player, options) {
  12246. super(player, options);
  12247. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  12248. this.updateTextNode_();
  12249. }
  12250. /**
  12251. * Create the `Component`'s DOM element
  12252. *
  12253. * @return {Element}
  12254. * The element that was created.
  12255. */
  12256. createEl() {
  12257. const className = this.buildCSSClass();
  12258. const el = super.createEl('div', {
  12259. className: `${className} vjs-time-control vjs-control`
  12260. });
  12261. const span = createEl('span', {
  12262. className: 'vjs-control-text',
  12263. textContent: `${this.localize(this.labelText_)}\u00a0`
  12264. }, {
  12265. role: 'presentation'
  12266. });
  12267. el.appendChild(span);
  12268. this.contentEl_ = createEl('span', {
  12269. className: `${className}-display`
  12270. }, {
  12271. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  12272. // treat them as a break between items in the DOM when using arrow keys
  12273. // (or left-to-right swipes on iOS) to read contents of a page. Using
  12274. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  12275. role: 'presentation'
  12276. });
  12277. el.appendChild(this.contentEl_);
  12278. return el;
  12279. }
  12280. dispose() {
  12281. this.contentEl_ = null;
  12282. this.textNode_ = null;
  12283. super.dispose();
  12284. }
  12285. /**
  12286. * Updates the time display text node with a new time
  12287. *
  12288. * @param {number} [time=0] the time to update to
  12289. *
  12290. * @private
  12291. */
  12292. updateTextNode_(time = 0) {
  12293. time = formatTime(time);
  12294. if (this.formattedTime_ === time) {
  12295. return;
  12296. }
  12297. this.formattedTime_ = time;
  12298. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  12299. if (!this.contentEl_) {
  12300. return;
  12301. }
  12302. let oldNode = this.textNode_;
  12303. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  12304. oldNode = null;
  12305. 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.');
  12306. }
  12307. this.textNode_ = document.createTextNode(this.formattedTime_);
  12308. if (!this.textNode_) {
  12309. return;
  12310. }
  12311. if (oldNode) {
  12312. this.contentEl_.replaceChild(this.textNode_, oldNode);
  12313. } else {
  12314. this.contentEl_.appendChild(this.textNode_);
  12315. }
  12316. });
  12317. }
  12318. /**
  12319. * To be filled out in the child class, should update the displayed time
  12320. * in accordance with the fact that the current time has changed.
  12321. *
  12322. * @param {Event} [event]
  12323. * The `timeupdate` event that caused this to run.
  12324. *
  12325. * @listens Player#timeupdate
  12326. */
  12327. updateContent(event) {}
  12328. }
  12329. /**
  12330. * The text that is added to the `TimeDisplay` for screen reader users.
  12331. *
  12332. * @type {string}
  12333. * @private
  12334. */
  12335. TimeDisplay.prototype.labelText_ = 'Time';
  12336. /**
  12337. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  12338. *
  12339. * @type {string}
  12340. * @protected
  12341. *
  12342. * @deprecated in v7; controlText_ is not used in non-active display Components
  12343. */
  12344. TimeDisplay.prototype.controlText_ = 'Time';
  12345. Component.registerComponent('TimeDisplay', TimeDisplay);
  12346. /**
  12347. * @file current-time-display.js
  12348. */
  12349. /**
  12350. * Displays the current time
  12351. *
  12352. * @extends Component
  12353. */
  12354. class CurrentTimeDisplay extends TimeDisplay {
  12355. /**
  12356. * Builds the default DOM `className`.
  12357. *
  12358. * @return {string}
  12359. * The DOM `className` for this object.
  12360. */
  12361. buildCSSClass() {
  12362. return 'vjs-current-time';
  12363. }
  12364. /**
  12365. * Update current time display
  12366. *
  12367. * @param {Event} [event]
  12368. * The `timeupdate` event that caused this function to run.
  12369. *
  12370. * @listens Player#timeupdate
  12371. */
  12372. updateContent(event) {
  12373. // Allows for smooth scrubbing, when player can't keep up.
  12374. let time;
  12375. if (this.player_.ended()) {
  12376. time = this.player_.duration();
  12377. } else {
  12378. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12379. }
  12380. this.updateTextNode_(time);
  12381. }
  12382. }
  12383. /**
  12384. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  12385. *
  12386. * @type {string}
  12387. * @private
  12388. */
  12389. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  12390. /**
  12391. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  12392. *
  12393. * @type {string}
  12394. * @protected
  12395. *
  12396. * @deprecated in v7; controlText_ is not used in non-active display Components
  12397. */
  12398. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  12399. Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  12400. /**
  12401. * @file duration-display.js
  12402. */
  12403. /**
  12404. * Displays the duration
  12405. *
  12406. * @extends Component
  12407. */
  12408. class DurationDisplay extends TimeDisplay {
  12409. /**
  12410. * Creates an instance of this class.
  12411. *
  12412. * @param { import('../../player').default } player
  12413. * The `Player` that this class should be attached to.
  12414. *
  12415. * @param {Object} [options]
  12416. * The key/value store of player options.
  12417. */
  12418. constructor(player, options) {
  12419. super(player, options);
  12420. const updateContent = e => this.updateContent(e);
  12421. // we do not want to/need to throttle duration changes,
  12422. // as they should always display the changed duration as
  12423. // it has changed
  12424. this.on(player, 'durationchange', updateContent);
  12425. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  12426. // but the durationchange on the user agent will not fire.
  12427. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  12428. this.on(player, 'loadstart', updateContent);
  12429. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  12430. // listeners could have broken dependent applications/libraries. These
  12431. // can likely be removed for 7.0.
  12432. this.on(player, 'loadedmetadata', updateContent);
  12433. }
  12434. /**
  12435. * Builds the default DOM `className`.
  12436. *
  12437. * @return {string}
  12438. * The DOM `className` for this object.
  12439. */
  12440. buildCSSClass() {
  12441. return 'vjs-duration';
  12442. }
  12443. /**
  12444. * Update duration time display.
  12445. *
  12446. * @param {Event} [event]
  12447. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  12448. * this function to be called.
  12449. *
  12450. * @listens Player#durationchange
  12451. * @listens Player#timeupdate
  12452. * @listens Player#loadedmetadata
  12453. */
  12454. updateContent(event) {
  12455. const duration = this.player_.duration();
  12456. this.updateTextNode_(duration);
  12457. }
  12458. }
  12459. /**
  12460. * The text that is added to the `DurationDisplay` for screen reader users.
  12461. *
  12462. * @type {string}
  12463. * @private
  12464. */
  12465. DurationDisplay.prototype.labelText_ = 'Duration';
  12466. /**
  12467. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  12468. *
  12469. * @type {string}
  12470. * @protected
  12471. *
  12472. * @deprecated in v7; controlText_ is not used in non-active display Components
  12473. */
  12474. DurationDisplay.prototype.controlText_ = 'Duration';
  12475. Component.registerComponent('DurationDisplay', DurationDisplay);
  12476. /**
  12477. * @file time-divider.js
  12478. */
  12479. /**
  12480. * The separator between the current time and duration.
  12481. * Can be hidden if it's not needed in the design.
  12482. *
  12483. * @extends Component
  12484. */
  12485. class TimeDivider extends Component {
  12486. /**
  12487. * Create the component's DOM element
  12488. *
  12489. * @return {Element}
  12490. * The element that was created.
  12491. */
  12492. createEl() {
  12493. const el = super.createEl('div', {
  12494. className: 'vjs-time-control vjs-time-divider'
  12495. }, {
  12496. // this element and its contents can be hidden from assistive techs since
  12497. // it is made extraneous by the announcement of the control text
  12498. // for the current time and duration displays
  12499. 'aria-hidden': true
  12500. });
  12501. const div = super.createEl('div');
  12502. const span = super.createEl('span', {
  12503. textContent: '/'
  12504. });
  12505. div.appendChild(span);
  12506. el.appendChild(div);
  12507. return el;
  12508. }
  12509. }
  12510. Component.registerComponent('TimeDivider', TimeDivider);
  12511. /**
  12512. * @file remaining-time-display.js
  12513. */
  12514. /**
  12515. * Displays the time left in the video
  12516. *
  12517. * @extends Component
  12518. */
  12519. class RemainingTimeDisplay extends TimeDisplay {
  12520. /**
  12521. * Creates an instance of this class.
  12522. *
  12523. * @param { import('../../player').default } player
  12524. * The `Player` that this class should be attached to.
  12525. *
  12526. * @param {Object} [options]
  12527. * The key/value store of player options.
  12528. */
  12529. constructor(player, options) {
  12530. super(player, options);
  12531. this.on(player, 'durationchange', e => this.updateContent(e));
  12532. }
  12533. /**
  12534. * Builds the default DOM `className`.
  12535. *
  12536. * @return {string}
  12537. * The DOM `className` for this object.
  12538. */
  12539. buildCSSClass() {
  12540. return 'vjs-remaining-time';
  12541. }
  12542. /**
  12543. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  12544. *
  12545. * @return {Element}
  12546. * The element that was created.
  12547. */
  12548. createEl() {
  12549. const el = super.createEl();
  12550. if (this.options_.displayNegative !== false) {
  12551. el.insertBefore(createEl('span', {}, {
  12552. 'aria-hidden': true
  12553. }, '-'), this.contentEl_);
  12554. }
  12555. return el;
  12556. }
  12557. /**
  12558. * Update remaining time display.
  12559. *
  12560. * @param {Event} [event]
  12561. * The `timeupdate` or `durationchange` event that caused this to run.
  12562. *
  12563. * @listens Player#timeupdate
  12564. * @listens Player#durationchange
  12565. */
  12566. updateContent(event) {
  12567. if (typeof this.player_.duration() !== 'number') {
  12568. return;
  12569. }
  12570. let time;
  12571. // @deprecated We should only use remainingTimeDisplay
  12572. // as of video.js 7
  12573. if (this.player_.ended()) {
  12574. time = 0;
  12575. } else if (this.player_.remainingTimeDisplay) {
  12576. time = this.player_.remainingTimeDisplay();
  12577. } else {
  12578. time = this.player_.remainingTime();
  12579. }
  12580. this.updateTextNode_(time);
  12581. }
  12582. }
  12583. /**
  12584. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  12585. *
  12586. * @type {string}
  12587. * @private
  12588. */
  12589. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  12590. /**
  12591. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  12592. *
  12593. * @type {string}
  12594. * @protected
  12595. *
  12596. * @deprecated in v7; controlText_ is not used in non-active display Components
  12597. */
  12598. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  12599. Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  12600. /**
  12601. * @file live-display.js
  12602. */
  12603. // TODO - Future make it click to snap to live
  12604. /**
  12605. * Displays the live indicator when duration is Infinity.
  12606. *
  12607. * @extends Component
  12608. */
  12609. class LiveDisplay extends Component {
  12610. /**
  12611. * Creates an instance of this class.
  12612. *
  12613. * @param { import('./player').default } player
  12614. * The `Player` that this class should be attached to.
  12615. *
  12616. * @param {Object} [options]
  12617. * The key/value store of player options.
  12618. */
  12619. constructor(player, options) {
  12620. super(player, options);
  12621. this.updateShowing();
  12622. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  12623. }
  12624. /**
  12625. * Create the `Component`'s DOM element
  12626. *
  12627. * @return {Element}
  12628. * The element that was created.
  12629. */
  12630. createEl() {
  12631. const el = super.createEl('div', {
  12632. className: 'vjs-live-control vjs-control'
  12633. });
  12634. this.contentEl_ = createEl('div', {
  12635. className: 'vjs-live-display'
  12636. }, {
  12637. 'aria-live': 'off'
  12638. });
  12639. this.contentEl_.appendChild(createEl('span', {
  12640. className: 'vjs-control-text',
  12641. textContent: `${this.localize('Stream Type')}\u00a0`
  12642. }));
  12643. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  12644. el.appendChild(this.contentEl_);
  12645. return el;
  12646. }
  12647. dispose() {
  12648. this.contentEl_ = null;
  12649. super.dispose();
  12650. }
  12651. /**
  12652. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  12653. * it accordingly
  12654. *
  12655. * @param {Event} [event]
  12656. * The {@link Player#durationchange} event that caused this function to run.
  12657. *
  12658. * @listens Player#durationchange
  12659. */
  12660. updateShowing(event) {
  12661. if (this.player().duration() === Infinity) {
  12662. this.show();
  12663. } else {
  12664. this.hide();
  12665. }
  12666. }
  12667. }
  12668. Component.registerComponent('LiveDisplay', LiveDisplay);
  12669. /**
  12670. * @file seek-to-live.js
  12671. */
  12672. /**
  12673. * Displays the live indicator when duration is Infinity.
  12674. *
  12675. * @extends Component
  12676. */
  12677. class SeekToLive extends Button {
  12678. /**
  12679. * Creates an instance of this class.
  12680. *
  12681. * @param { import('./player').default } player
  12682. * The `Player` that this class should be attached to.
  12683. *
  12684. * @param {Object} [options]
  12685. * The key/value store of player options.
  12686. */
  12687. constructor(player, options) {
  12688. super(player, options);
  12689. this.updateLiveEdgeStatus();
  12690. if (this.player_.liveTracker) {
  12691. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  12692. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12693. }
  12694. }
  12695. /**
  12696. * Create the `Component`'s DOM element
  12697. *
  12698. * @return {Element}
  12699. * The element that was created.
  12700. */
  12701. createEl() {
  12702. const el = super.createEl('button', {
  12703. className: 'vjs-seek-to-live-control vjs-control'
  12704. });
  12705. this.textEl_ = createEl('span', {
  12706. className: 'vjs-seek-to-live-text',
  12707. textContent: this.localize('LIVE')
  12708. }, {
  12709. 'aria-hidden': 'true'
  12710. });
  12711. el.appendChild(this.textEl_);
  12712. return el;
  12713. }
  12714. /**
  12715. * Update the state of this button if we are at the live edge
  12716. * or not
  12717. */
  12718. updateLiveEdgeStatus() {
  12719. // default to live edge
  12720. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  12721. this.setAttribute('aria-disabled', true);
  12722. this.addClass('vjs-at-live-edge');
  12723. this.controlText('Seek to live, currently playing live');
  12724. } else {
  12725. this.setAttribute('aria-disabled', false);
  12726. this.removeClass('vjs-at-live-edge');
  12727. this.controlText('Seek to live, currently behind live');
  12728. }
  12729. }
  12730. /**
  12731. * On click bring us as near to the live point as possible.
  12732. * This requires that we wait for the next `live-seekable-change`
  12733. * event which will happen every segment length seconds.
  12734. */
  12735. handleClick() {
  12736. this.player_.liveTracker.seekToLiveEdge();
  12737. }
  12738. /**
  12739. * Dispose of the element and stop tracking
  12740. */
  12741. dispose() {
  12742. if (this.player_.liveTracker) {
  12743. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12744. }
  12745. this.textEl_ = null;
  12746. super.dispose();
  12747. }
  12748. }
  12749. /**
  12750. * The text that should display over the `SeekToLive`s control. Added for localization.
  12751. *
  12752. * @type {string}
  12753. * @protected
  12754. */
  12755. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  12756. Component.registerComponent('SeekToLive', SeekToLive);
  12757. /**
  12758. * @file num.js
  12759. * @module num
  12760. */
  12761. /**
  12762. * Keep a number between a min and a max value
  12763. *
  12764. * @param {number} number
  12765. * The number to clamp
  12766. *
  12767. * @param {number} min
  12768. * The minimum value
  12769. * @param {number} max
  12770. * The maximum value
  12771. *
  12772. * @return {number}
  12773. * the clamped number
  12774. */
  12775. function clamp(number, min, max) {
  12776. number = Number(number);
  12777. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  12778. }
  12779. var Num = /*#__PURE__*/Object.freeze({
  12780. __proto__: null,
  12781. clamp: clamp
  12782. });
  12783. /**
  12784. * @file slider.js
  12785. */
  12786. /**
  12787. * The base functionality for a slider. Can be vertical or horizontal.
  12788. * For instance the volume bar or the seek bar on a video is a slider.
  12789. *
  12790. * @extends Component
  12791. */
  12792. class Slider extends Component {
  12793. /**
  12794. * Create an instance of this class
  12795. *
  12796. * @param { import('../player').default } player
  12797. * The `Player` that this class should be attached to.
  12798. *
  12799. * @param {Object} [options]
  12800. * The key/value store of player options.
  12801. */
  12802. constructor(player, options) {
  12803. super(player, options);
  12804. this.handleMouseDown_ = e => this.handleMouseDown(e);
  12805. this.handleMouseUp_ = e => this.handleMouseUp(e);
  12806. this.handleKeyDown_ = e => this.handleKeyDown(e);
  12807. this.handleClick_ = e => this.handleClick(e);
  12808. this.handleMouseMove_ = e => this.handleMouseMove(e);
  12809. this.update_ = e => this.update(e);
  12810. // Set property names to bar to match with the child Slider class is looking for
  12811. this.bar = this.getChild(this.options_.barName);
  12812. // Set a horizontal or vertical class on the slider depending on the slider type
  12813. this.vertical(!!this.options_.vertical);
  12814. this.enable();
  12815. }
  12816. /**
  12817. * Are controls are currently enabled for this slider or not.
  12818. *
  12819. * @return {boolean}
  12820. * true if controls are enabled, false otherwise
  12821. */
  12822. enabled() {
  12823. return this.enabled_;
  12824. }
  12825. /**
  12826. * Enable controls for this slider if they are disabled
  12827. */
  12828. enable() {
  12829. if (this.enabled()) {
  12830. return;
  12831. }
  12832. this.on('mousedown', this.handleMouseDown_);
  12833. this.on('touchstart', this.handleMouseDown_);
  12834. this.on('keydown', this.handleKeyDown_);
  12835. this.on('click', this.handleClick_);
  12836. // TODO: deprecated, controlsvisible does not seem to be fired
  12837. this.on(this.player_, 'controlsvisible', this.update);
  12838. if (this.playerEvent) {
  12839. this.on(this.player_, this.playerEvent, this.update);
  12840. }
  12841. this.removeClass('disabled');
  12842. this.setAttribute('tabindex', 0);
  12843. this.enabled_ = true;
  12844. }
  12845. /**
  12846. * Disable controls for this slider if they are enabled
  12847. */
  12848. disable() {
  12849. if (!this.enabled()) {
  12850. return;
  12851. }
  12852. const doc = this.bar.el_.ownerDocument;
  12853. this.off('mousedown', this.handleMouseDown_);
  12854. this.off('touchstart', this.handleMouseDown_);
  12855. this.off('keydown', this.handleKeyDown_);
  12856. this.off('click', this.handleClick_);
  12857. this.off(this.player_, 'controlsvisible', this.update_);
  12858. this.off(doc, 'mousemove', this.handleMouseMove_);
  12859. this.off(doc, 'mouseup', this.handleMouseUp_);
  12860. this.off(doc, 'touchmove', this.handleMouseMove_);
  12861. this.off(doc, 'touchend', this.handleMouseUp_);
  12862. this.removeAttribute('tabindex');
  12863. this.addClass('disabled');
  12864. if (this.playerEvent) {
  12865. this.off(this.player_, this.playerEvent, this.update);
  12866. }
  12867. this.enabled_ = false;
  12868. }
  12869. /**
  12870. * Create the `Slider`s DOM element.
  12871. *
  12872. * @param {string} type
  12873. * Type of element to create.
  12874. *
  12875. * @param {Object} [props={}]
  12876. * List of properties in Object form.
  12877. *
  12878. * @param {Object} [attributes={}]
  12879. * list of attributes in Object form.
  12880. *
  12881. * @return {Element}
  12882. * The element that gets created.
  12883. */
  12884. createEl(type, props = {}, attributes = {}) {
  12885. // Add the slider element class to all sub classes
  12886. props.className = props.className + ' vjs-slider';
  12887. props = Object.assign({
  12888. tabIndex: 0
  12889. }, props);
  12890. attributes = Object.assign({
  12891. 'role': 'slider',
  12892. 'aria-valuenow': 0,
  12893. 'aria-valuemin': 0,
  12894. 'aria-valuemax': 100
  12895. }, attributes);
  12896. return super.createEl(type, props, attributes);
  12897. }
  12898. /**
  12899. * Handle `mousedown` or `touchstart` events on the `Slider`.
  12900. *
  12901. * @param {MouseEvent} event
  12902. * `mousedown` or `touchstart` event that triggered this function
  12903. *
  12904. * @listens mousedown
  12905. * @listens touchstart
  12906. * @fires Slider#slideractive
  12907. */
  12908. handleMouseDown(event) {
  12909. const doc = this.bar.el_.ownerDocument;
  12910. if (event.type === 'mousedown') {
  12911. event.preventDefault();
  12912. }
  12913. // Do not call preventDefault() on touchstart in Chrome
  12914. // to avoid console warnings. Use a 'touch-action: none' style
  12915. // instead to prevent unintended scrolling.
  12916. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  12917. if (event.type === 'touchstart' && !IS_CHROME) {
  12918. event.preventDefault();
  12919. }
  12920. blockTextSelection();
  12921. this.addClass('vjs-sliding');
  12922. /**
  12923. * Triggered when the slider is in an active state
  12924. *
  12925. * @event Slider#slideractive
  12926. * @type {MouseEvent}
  12927. */
  12928. this.trigger('slideractive');
  12929. this.on(doc, 'mousemove', this.handleMouseMove_);
  12930. this.on(doc, 'mouseup', this.handleMouseUp_);
  12931. this.on(doc, 'touchmove', this.handleMouseMove_);
  12932. this.on(doc, 'touchend', this.handleMouseUp_);
  12933. this.handleMouseMove(event, true);
  12934. }
  12935. /**
  12936. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  12937. * The `mousemove` and `touchmove` events will only only trigger this function during
  12938. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  12939. * {@link Slider#handleMouseUp}.
  12940. *
  12941. * @param {MouseEvent} event
  12942. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  12943. * this function
  12944. * @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.
  12945. *
  12946. * @listens mousemove
  12947. * @listens touchmove
  12948. */
  12949. handleMouseMove(event) {}
  12950. /**
  12951. * Handle `mouseup` or `touchend` events on the `Slider`.
  12952. *
  12953. * @param {MouseEvent} event
  12954. * `mouseup` or `touchend` event that triggered this function.
  12955. *
  12956. * @listens touchend
  12957. * @listens mouseup
  12958. * @fires Slider#sliderinactive
  12959. */
  12960. handleMouseUp(event) {
  12961. const doc = this.bar.el_.ownerDocument;
  12962. unblockTextSelection();
  12963. this.removeClass('vjs-sliding');
  12964. /**
  12965. * Triggered when the slider is no longer in an active state.
  12966. *
  12967. * @event Slider#sliderinactive
  12968. * @type {Event}
  12969. */
  12970. this.trigger('sliderinactive');
  12971. this.off(doc, 'mousemove', this.handleMouseMove_);
  12972. this.off(doc, 'mouseup', this.handleMouseUp_);
  12973. this.off(doc, 'touchmove', this.handleMouseMove_);
  12974. this.off(doc, 'touchend', this.handleMouseUp_);
  12975. this.update();
  12976. }
  12977. /**
  12978. * Update the progress bar of the `Slider`.
  12979. *
  12980. * @return {number}
  12981. * The percentage of progress the progress bar represents as a
  12982. * number from 0 to 1.
  12983. */
  12984. update() {
  12985. // In VolumeBar init we have a setTimeout for update that pops and update
  12986. // to the end of the execution stack. The player is destroyed before then
  12987. // update will cause an error
  12988. // If there's no bar...
  12989. if (!this.el_ || !this.bar) {
  12990. return;
  12991. }
  12992. // clamp progress between 0 and 1
  12993. // and only round to four decimal places, as we round to two below
  12994. const progress = this.getProgress();
  12995. if (progress === this.progress_) {
  12996. return progress;
  12997. }
  12998. this.progress_ = progress;
  12999. this.requestNamedAnimationFrame('Slider#update', () => {
  13000. // Set the new bar width or height
  13001. const sizeKey = this.vertical() ? 'height' : 'width';
  13002. // Convert to a percentage for css value
  13003. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  13004. });
  13005. return progress;
  13006. }
  13007. /**
  13008. * Get the percentage of the bar that should be filled
  13009. * but clamped and rounded.
  13010. *
  13011. * @return {number}
  13012. * percentage filled that the slider is
  13013. */
  13014. getProgress() {
  13015. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  13016. }
  13017. /**
  13018. * Calculate distance for slider
  13019. *
  13020. * @param {Event} event
  13021. * The event that caused this function to run.
  13022. *
  13023. * @return {number}
  13024. * The current position of the Slider.
  13025. * - position.x for vertical `Slider`s
  13026. * - position.y for horizontal `Slider`s
  13027. */
  13028. calculateDistance(event) {
  13029. const position = getPointerPosition(this.el_, event);
  13030. if (this.vertical()) {
  13031. return position.y;
  13032. }
  13033. return position.x;
  13034. }
  13035. /**
  13036. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  13037. * arrow keys. This function will only be called when the slider has focus. See
  13038. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  13039. *
  13040. * @param {KeyboardEvent} event
  13041. * the `keydown` event that caused this function to run.
  13042. *
  13043. * @listens keydown
  13044. */
  13045. handleKeyDown(event) {
  13046. // Left and Down Arrows
  13047. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13048. event.preventDefault();
  13049. event.stopPropagation();
  13050. this.stepBack();
  13051. // Up and Right Arrows
  13052. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13053. event.preventDefault();
  13054. event.stopPropagation();
  13055. this.stepForward();
  13056. } else {
  13057. // Pass keydown handling up for unsupported keys
  13058. super.handleKeyDown(event);
  13059. }
  13060. }
  13061. /**
  13062. * Listener for click events on slider, used to prevent clicks
  13063. * from bubbling up to parent elements like button menus.
  13064. *
  13065. * @param {Object} event
  13066. * Event that caused this object to run
  13067. */
  13068. handleClick(event) {
  13069. event.stopPropagation();
  13070. event.preventDefault();
  13071. }
  13072. /**
  13073. * Get/set if slider is horizontal for vertical
  13074. *
  13075. * @param {boolean} [bool]
  13076. * - true if slider is vertical,
  13077. * - false is horizontal
  13078. *
  13079. * @return {boolean}
  13080. * - true if slider is vertical, and getting
  13081. * - false if the slider is horizontal, and getting
  13082. */
  13083. vertical(bool) {
  13084. if (bool === undefined) {
  13085. return this.vertical_ || false;
  13086. }
  13087. this.vertical_ = !!bool;
  13088. if (this.vertical_) {
  13089. this.addClass('vjs-slider-vertical');
  13090. } else {
  13091. this.addClass('vjs-slider-horizontal');
  13092. }
  13093. }
  13094. }
  13095. Component.registerComponent('Slider', Slider);
  13096. /**
  13097. * @file load-progress-bar.js
  13098. */
  13099. // get the percent width of a time compared to the total end
  13100. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  13101. /**
  13102. * Shows loading progress
  13103. *
  13104. * @extends Component
  13105. */
  13106. class LoadProgressBar extends Component {
  13107. /**
  13108. * Creates an instance of this class.
  13109. *
  13110. * @param { import('../../player').default } player
  13111. * The `Player` that this class should be attached to.
  13112. *
  13113. * @param {Object} [options]
  13114. * The key/value store of player options.
  13115. */
  13116. constructor(player, options) {
  13117. super(player, options);
  13118. this.partEls_ = [];
  13119. this.on(player, 'progress', e => this.update(e));
  13120. }
  13121. /**
  13122. * Create the `Component`'s DOM element
  13123. *
  13124. * @return {Element}
  13125. * The element that was created.
  13126. */
  13127. createEl() {
  13128. const el = super.createEl('div', {
  13129. className: 'vjs-load-progress'
  13130. });
  13131. const wrapper = createEl('span', {
  13132. className: 'vjs-control-text'
  13133. });
  13134. const loadedText = createEl('span', {
  13135. textContent: this.localize('Loaded')
  13136. });
  13137. const separator = document.createTextNode(': ');
  13138. this.percentageEl_ = createEl('span', {
  13139. className: 'vjs-control-text-loaded-percentage',
  13140. textContent: '0%'
  13141. });
  13142. el.appendChild(wrapper);
  13143. wrapper.appendChild(loadedText);
  13144. wrapper.appendChild(separator);
  13145. wrapper.appendChild(this.percentageEl_);
  13146. return el;
  13147. }
  13148. dispose() {
  13149. this.partEls_ = null;
  13150. this.percentageEl_ = null;
  13151. super.dispose();
  13152. }
  13153. /**
  13154. * Update progress bar
  13155. *
  13156. * @param {Event} [event]
  13157. * The `progress` event that caused this function to run.
  13158. *
  13159. * @listens Player#progress
  13160. */
  13161. update(event) {
  13162. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  13163. const liveTracker = this.player_.liveTracker;
  13164. const buffered = this.player_.buffered();
  13165. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13166. const bufferedEnd = this.player_.bufferedEnd();
  13167. const children = this.partEls_;
  13168. const percent = percentify(bufferedEnd, duration);
  13169. if (this.percent_ !== percent) {
  13170. // update the width of the progress bar
  13171. this.el_.style.width = percent;
  13172. // update the control-text
  13173. textContent(this.percentageEl_, percent);
  13174. this.percent_ = percent;
  13175. }
  13176. // add child elements to represent the individual buffered time ranges
  13177. for (let i = 0; i < buffered.length; i++) {
  13178. const start = buffered.start(i);
  13179. const end = buffered.end(i);
  13180. let part = children[i];
  13181. if (!part) {
  13182. part = this.el_.appendChild(createEl());
  13183. children[i] = part;
  13184. }
  13185. // only update if changed
  13186. if (part.dataset.start === start && part.dataset.end === end) {
  13187. continue;
  13188. }
  13189. part.dataset.start = start;
  13190. part.dataset.end = end;
  13191. // set the percent based on the width of the progress bar (bufferedEnd)
  13192. part.style.left = percentify(start, bufferedEnd);
  13193. part.style.width = percentify(end - start, bufferedEnd);
  13194. }
  13195. // remove unused buffered range elements
  13196. for (let i = children.length; i > buffered.length; i--) {
  13197. this.el_.removeChild(children[i - 1]);
  13198. }
  13199. children.length = buffered.length;
  13200. });
  13201. }
  13202. }
  13203. Component.registerComponent('LoadProgressBar', LoadProgressBar);
  13204. /**
  13205. * @file time-tooltip.js
  13206. */
  13207. /**
  13208. * Time tooltips display a time above the progress bar.
  13209. *
  13210. * @extends Component
  13211. */
  13212. class TimeTooltip extends Component {
  13213. /**
  13214. * Creates an instance of this class.
  13215. *
  13216. * @param { import('../../player').default } player
  13217. * The {@link Player} that this class should be attached to.
  13218. *
  13219. * @param {Object} [options]
  13220. * The key/value store of player options.
  13221. */
  13222. constructor(player, options) {
  13223. super(player, options);
  13224. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13225. }
  13226. /**
  13227. * Create the time tooltip DOM element
  13228. *
  13229. * @return {Element}
  13230. * The element that was created.
  13231. */
  13232. createEl() {
  13233. return super.createEl('div', {
  13234. className: 'vjs-time-tooltip'
  13235. }, {
  13236. 'aria-hidden': 'true'
  13237. });
  13238. }
  13239. /**
  13240. * Updates the position of the time tooltip relative to the `SeekBar`.
  13241. *
  13242. * @param {Object} seekBarRect
  13243. * The `ClientRect` for the {@link SeekBar} element.
  13244. *
  13245. * @param {number} seekBarPoint
  13246. * A number from 0 to 1, representing a horizontal reference point
  13247. * from the left edge of the {@link SeekBar}
  13248. */
  13249. update(seekBarRect, seekBarPoint, content) {
  13250. const tooltipRect = findPosition(this.el_);
  13251. const playerRect = getBoundingClientRect(this.player_.el());
  13252. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  13253. // do nothing if either rect isn't available
  13254. // for example, if the player isn't in the DOM for testing
  13255. if (!playerRect || !tooltipRect) {
  13256. return;
  13257. }
  13258. // This is the space left of the `seekBarPoint` available within the bounds
  13259. // of the player. We calculate any gap between the left edge of the player
  13260. // and the left edge of the `SeekBar` and add the number of pixels in the
  13261. // `SeekBar` before hitting the `seekBarPoint`
  13262. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  13263. // This is the space right of the `seekBarPoint` available within the bounds
  13264. // of the player. We calculate the number of pixels from the `seekBarPoint`
  13265. // to the right edge of the `SeekBar` and add to that any gap between the
  13266. // right edge of the `SeekBar` and the player.
  13267. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  13268. // This is the number of pixels by which the tooltip will need to be pulled
  13269. // further to the right to center it over the `seekBarPoint`.
  13270. let pullTooltipBy = tooltipRect.width / 2;
  13271. // Adjust the `pullTooltipBy` distance to the left or right depending on
  13272. // the results of the space calculations above.
  13273. if (spaceLeftOfPoint < pullTooltipBy) {
  13274. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  13275. } else if (spaceRightOfPoint < pullTooltipBy) {
  13276. pullTooltipBy = spaceRightOfPoint;
  13277. }
  13278. // Due to the imprecision of decimal/ratio based calculations and varying
  13279. // rounding behaviors, there are cases where the spacing adjustment is off
  13280. // by a pixel or two. This adds insurance to these calculations.
  13281. if (pullTooltipBy < 0) {
  13282. pullTooltipBy = 0;
  13283. } else if (pullTooltipBy > tooltipRect.width) {
  13284. pullTooltipBy = tooltipRect.width;
  13285. }
  13286. // prevent small width fluctuations within 0.4px from
  13287. // changing the value below.
  13288. // This really helps for live to prevent the play
  13289. // progress time tooltip from jittering
  13290. pullTooltipBy = Math.round(pullTooltipBy);
  13291. this.el_.style.right = `-${pullTooltipBy}px`;
  13292. this.write(content);
  13293. }
  13294. /**
  13295. * Write the time to the tooltip DOM element.
  13296. *
  13297. * @param {string} content
  13298. * The formatted time for the tooltip.
  13299. */
  13300. write(content) {
  13301. textContent(this.el_, content);
  13302. }
  13303. /**
  13304. * Updates the position of the time tooltip relative to the `SeekBar`.
  13305. *
  13306. * @param {Object} seekBarRect
  13307. * The `ClientRect` for the {@link SeekBar} element.
  13308. *
  13309. * @param {number} seekBarPoint
  13310. * A number from 0 to 1, representing a horizontal reference point
  13311. * from the left edge of the {@link SeekBar}
  13312. *
  13313. * @param {number} time
  13314. * The time to update the tooltip to, not used during live playback
  13315. *
  13316. * @param {Function} cb
  13317. * A function that will be called during the request animation frame
  13318. * for tooltips that need to do additional animations from the default
  13319. */
  13320. updateTime(seekBarRect, seekBarPoint, time, cb) {
  13321. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  13322. let content;
  13323. const duration = this.player_.duration();
  13324. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13325. const liveWindow = this.player_.liveTracker.liveWindow();
  13326. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  13327. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  13328. } else {
  13329. content = formatTime(time, duration);
  13330. }
  13331. this.update(seekBarRect, seekBarPoint, content);
  13332. if (cb) {
  13333. cb();
  13334. }
  13335. });
  13336. }
  13337. }
  13338. Component.registerComponent('TimeTooltip', TimeTooltip);
  13339. /**
  13340. * @file play-progress-bar.js
  13341. */
  13342. /**
  13343. * Used by {@link SeekBar} to display media playback progress as part of the
  13344. * {@link ProgressControl}.
  13345. *
  13346. * @extends Component
  13347. */
  13348. class PlayProgressBar extends Component {
  13349. /**
  13350. * Creates an instance of this class.
  13351. *
  13352. * @param { import('../../player').default } player
  13353. * The {@link Player} that this class should be attached to.
  13354. *
  13355. * @param {Object} [options]
  13356. * The key/value store of player options.
  13357. */
  13358. constructor(player, options) {
  13359. super(player, options);
  13360. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13361. }
  13362. /**
  13363. * Create the the DOM element for this class.
  13364. *
  13365. * @return {Element}
  13366. * The element that was created.
  13367. */
  13368. createEl() {
  13369. return super.createEl('div', {
  13370. className: 'vjs-play-progress vjs-slider-bar'
  13371. }, {
  13372. 'aria-hidden': 'true'
  13373. });
  13374. }
  13375. /**
  13376. * Enqueues updates to its own DOM as well as the DOM of its
  13377. * {@link TimeTooltip} child.
  13378. *
  13379. * @param {Object} seekBarRect
  13380. * The `ClientRect` for the {@link SeekBar} element.
  13381. *
  13382. * @param {number} seekBarPoint
  13383. * A number from 0 to 1, representing a horizontal reference point
  13384. * from the left edge of the {@link SeekBar}
  13385. */
  13386. update(seekBarRect, seekBarPoint) {
  13387. const timeTooltip = this.getChild('timeTooltip');
  13388. if (!timeTooltip) {
  13389. return;
  13390. }
  13391. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13392. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  13393. }
  13394. }
  13395. /**
  13396. * Default options for {@link PlayProgressBar}.
  13397. *
  13398. * @type {Object}
  13399. * @private
  13400. */
  13401. PlayProgressBar.prototype.options_ = {
  13402. children: []
  13403. };
  13404. // Time tooltips should not be added to a player on mobile devices
  13405. if (!IS_IOS && !IS_ANDROID) {
  13406. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  13407. }
  13408. Component.registerComponent('PlayProgressBar', PlayProgressBar);
  13409. /**
  13410. * @file mouse-time-display.js
  13411. */
  13412. /**
  13413. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  13414. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  13415. * indicating the time which is represented by a given point in the
  13416. * {@link ProgressControl}.
  13417. *
  13418. * @extends Component
  13419. */
  13420. class MouseTimeDisplay extends Component {
  13421. /**
  13422. * Creates an instance of this class.
  13423. *
  13424. * @param { import('../../player').default } player
  13425. * The {@link Player} that this class should be attached to.
  13426. *
  13427. * @param {Object} [options]
  13428. * The key/value store of player options.
  13429. */
  13430. constructor(player, options) {
  13431. super(player, options);
  13432. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  13433. }
  13434. /**
  13435. * Create the DOM element for this class.
  13436. *
  13437. * @return {Element}
  13438. * The element that was created.
  13439. */
  13440. createEl() {
  13441. return super.createEl('div', {
  13442. className: 'vjs-mouse-display'
  13443. });
  13444. }
  13445. /**
  13446. * Enqueues updates to its own DOM as well as the DOM of its
  13447. * {@link TimeTooltip} child.
  13448. *
  13449. * @param {Object} seekBarRect
  13450. * The `ClientRect` for the {@link SeekBar} element.
  13451. *
  13452. * @param {number} seekBarPoint
  13453. * A number from 0 to 1, representing a horizontal reference point
  13454. * from the left edge of the {@link SeekBar}
  13455. */
  13456. update(seekBarRect, seekBarPoint) {
  13457. const time = seekBarPoint * this.player_.duration();
  13458. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  13459. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  13460. });
  13461. }
  13462. }
  13463. /**
  13464. * Default options for `MouseTimeDisplay`
  13465. *
  13466. * @type {Object}
  13467. * @private
  13468. */
  13469. MouseTimeDisplay.prototype.options_ = {
  13470. children: ['timeTooltip']
  13471. };
  13472. Component.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  13473. /**
  13474. * @file seek-bar.js
  13475. */
  13476. // The number of seconds the `step*` functions move the timeline.
  13477. const STEP_SECONDS = 5;
  13478. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  13479. const PAGE_KEY_MULTIPLIER = 12;
  13480. /**
  13481. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  13482. * as its `bar`.
  13483. *
  13484. * @extends Slider
  13485. */
  13486. class SeekBar extends Slider {
  13487. /**
  13488. * Creates an instance of this class.
  13489. *
  13490. * @param { import('../../player').default } player
  13491. * The `Player` that this class should be attached to.
  13492. *
  13493. * @param {Object} [options]
  13494. * The key/value store of player options.
  13495. */
  13496. constructor(player, options) {
  13497. super(player, options);
  13498. this.setEventHandlers_();
  13499. }
  13500. /**
  13501. * Sets the event handlers
  13502. *
  13503. * @private
  13504. */
  13505. setEventHandlers_() {
  13506. this.update_ = bind_(this, this.update);
  13507. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  13508. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  13509. if (this.player_.liveTracker) {
  13510. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  13511. }
  13512. // when playing, let's ensure we smoothly update the play progress bar
  13513. // via an interval
  13514. this.updateInterval = null;
  13515. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  13516. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  13517. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  13518. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13519. // we don't need to update the play progress if the document is hidden,
  13520. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13521. if ('hidden' in document && 'visibilityState' in document) {
  13522. this.on(document, 'visibilitychange', this.toggleVisibility_);
  13523. }
  13524. }
  13525. toggleVisibility_(e) {
  13526. if (document.visibilityState === 'hidden') {
  13527. this.cancelNamedAnimationFrame('SeekBar#update');
  13528. this.cancelNamedAnimationFrame('Slider#update');
  13529. this.disableInterval_(e);
  13530. } else {
  13531. if (!this.player_.ended() && !this.player_.paused()) {
  13532. this.enableInterval_();
  13533. }
  13534. // we just switched back to the page and someone may be looking, so, update ASAP
  13535. this.update();
  13536. }
  13537. }
  13538. enableInterval_() {
  13539. if (this.updateInterval) {
  13540. return;
  13541. }
  13542. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  13543. }
  13544. disableInterval_(e) {
  13545. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  13546. return;
  13547. }
  13548. if (!this.updateInterval) {
  13549. return;
  13550. }
  13551. this.clearInterval(this.updateInterval);
  13552. this.updateInterval = null;
  13553. }
  13554. /**
  13555. * Create the `Component`'s DOM element
  13556. *
  13557. * @return {Element}
  13558. * The element that was created.
  13559. */
  13560. createEl() {
  13561. return super.createEl('div', {
  13562. className: 'vjs-progress-holder'
  13563. }, {
  13564. 'aria-label': this.localize('Progress Bar')
  13565. });
  13566. }
  13567. /**
  13568. * This function updates the play progress bar and accessibility
  13569. * attributes to whatever is passed in.
  13570. *
  13571. * @param {Event} [event]
  13572. * The `timeupdate` or `ended` event that caused this to run.
  13573. *
  13574. * @listens Player#timeupdate
  13575. *
  13576. * @return {number}
  13577. * The current percent at a number from 0-1
  13578. */
  13579. update(event) {
  13580. // ignore updates while the tab is hidden
  13581. if (document.visibilityState === 'hidden') {
  13582. return;
  13583. }
  13584. const percent = super.update();
  13585. this.requestNamedAnimationFrame('SeekBar#update', () => {
  13586. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  13587. const liveTracker = this.player_.liveTracker;
  13588. let duration = this.player_.duration();
  13589. if (liveTracker && liveTracker.isLive()) {
  13590. duration = this.player_.liveTracker.liveCurrentTime();
  13591. }
  13592. if (this.percent_ !== percent) {
  13593. // machine readable value of progress bar (percentage complete)
  13594. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  13595. this.percent_ = percent;
  13596. }
  13597. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  13598. // human readable value of progress bar (time complete)
  13599. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  13600. this.currentTime_ = currentTime;
  13601. this.duration_ = duration;
  13602. }
  13603. // update the progress bar time tooltip with the current time
  13604. if (this.bar) {
  13605. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  13606. }
  13607. });
  13608. return percent;
  13609. }
  13610. /**
  13611. * Prevent liveThreshold from causing seeks to seem like they
  13612. * are not happening from a user perspective.
  13613. *
  13614. * @param {number} ct
  13615. * current time to seek to
  13616. */
  13617. userSeek_(ct) {
  13618. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13619. this.player_.liveTracker.nextSeekedFromUser();
  13620. }
  13621. this.player_.currentTime(ct);
  13622. }
  13623. /**
  13624. * Get the value of current time but allows for smooth scrubbing,
  13625. * when player can't keep up.
  13626. *
  13627. * @return {number}
  13628. * The current time value to display
  13629. *
  13630. * @private
  13631. */
  13632. getCurrentTime_() {
  13633. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13634. }
  13635. /**
  13636. * Get the percentage of media played so far.
  13637. *
  13638. * @return {number}
  13639. * The percentage of media played so far (0 to 1).
  13640. */
  13641. getPercent() {
  13642. const currentTime = this.getCurrentTime_();
  13643. let percent;
  13644. const liveTracker = this.player_.liveTracker;
  13645. if (liveTracker && liveTracker.isLive()) {
  13646. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  13647. // prevent the percent from changing at the live edge
  13648. if (liveTracker.atLiveEdge()) {
  13649. percent = 1;
  13650. }
  13651. } else {
  13652. percent = currentTime / this.player_.duration();
  13653. }
  13654. return percent;
  13655. }
  13656. /**
  13657. * Handle mouse down on seek bar
  13658. *
  13659. * @param {MouseEvent} event
  13660. * The `mousedown` event that caused this to run.
  13661. *
  13662. * @listens mousedown
  13663. */
  13664. handleMouseDown(event) {
  13665. if (!isSingleLeftClick(event)) {
  13666. return;
  13667. }
  13668. // Stop event propagation to prevent double fire in progress-control.js
  13669. event.stopPropagation();
  13670. this.videoWasPlaying = !this.player_.paused();
  13671. this.player_.pause();
  13672. super.handleMouseDown(event);
  13673. }
  13674. /**
  13675. * Handle mouse move on seek bar
  13676. *
  13677. * @param {MouseEvent} event
  13678. * The `mousemove` event that caused this to run.
  13679. * @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
  13680. *
  13681. * @listens mousemove
  13682. */
  13683. handleMouseMove(event, mouseDown = false) {
  13684. if (!isSingleLeftClick(event)) {
  13685. return;
  13686. }
  13687. if (!mouseDown && !this.player_.scrubbing()) {
  13688. this.player_.scrubbing(true);
  13689. }
  13690. let newTime;
  13691. const distance = this.calculateDistance(event);
  13692. const liveTracker = this.player_.liveTracker;
  13693. if (!liveTracker || !liveTracker.isLive()) {
  13694. newTime = distance * this.player_.duration();
  13695. // Don't let video end while scrubbing.
  13696. if (newTime === this.player_.duration()) {
  13697. newTime = newTime - 0.1;
  13698. }
  13699. } else {
  13700. if (distance >= 0.99) {
  13701. liveTracker.seekToLiveEdge();
  13702. return;
  13703. }
  13704. const seekableStart = liveTracker.seekableStart();
  13705. const seekableEnd = liveTracker.liveCurrentTime();
  13706. newTime = seekableStart + distance * liveTracker.liveWindow();
  13707. // Don't let video end while scrubbing.
  13708. if (newTime >= seekableEnd) {
  13709. newTime = seekableEnd;
  13710. }
  13711. // Compensate for precision differences so that currentTime is not less
  13712. // than seekable start
  13713. if (newTime <= seekableStart) {
  13714. newTime = seekableStart + 0.1;
  13715. }
  13716. // On android seekableEnd can be Infinity sometimes,
  13717. // this will cause newTime to be Infinity, which is
  13718. // not a valid currentTime.
  13719. if (newTime === Infinity) {
  13720. return;
  13721. }
  13722. }
  13723. // Set new time (tell player to seek to new time)
  13724. this.userSeek_(newTime);
  13725. }
  13726. enable() {
  13727. super.enable();
  13728. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13729. if (!mouseTimeDisplay) {
  13730. return;
  13731. }
  13732. mouseTimeDisplay.show();
  13733. }
  13734. disable() {
  13735. super.disable();
  13736. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13737. if (!mouseTimeDisplay) {
  13738. return;
  13739. }
  13740. mouseTimeDisplay.hide();
  13741. }
  13742. /**
  13743. * Handle mouse up on seek bar
  13744. *
  13745. * @param {MouseEvent} event
  13746. * The `mouseup` event that caused this to run.
  13747. *
  13748. * @listens mouseup
  13749. */
  13750. handleMouseUp(event) {
  13751. super.handleMouseUp(event);
  13752. // Stop event propagation to prevent double fire in progress-control.js
  13753. if (event) {
  13754. event.stopPropagation();
  13755. }
  13756. this.player_.scrubbing(false);
  13757. /**
  13758. * Trigger timeupdate because we're done seeking and the time has changed.
  13759. * This is particularly useful for if the player is paused to time the time displays.
  13760. *
  13761. * @event Tech#timeupdate
  13762. * @type {Event}
  13763. */
  13764. this.player_.trigger({
  13765. type: 'timeupdate',
  13766. target: this,
  13767. manuallyTriggered: true
  13768. });
  13769. if (this.videoWasPlaying) {
  13770. silencePromise(this.player_.play());
  13771. } else {
  13772. // We're done seeking and the time has changed.
  13773. // If the player is paused, make sure we display the correct time on the seek bar.
  13774. this.update_();
  13775. }
  13776. }
  13777. /**
  13778. * Move more quickly fast forward for keyboard-only users
  13779. */
  13780. stepForward() {
  13781. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  13782. }
  13783. /**
  13784. * Move more quickly rewind for keyboard-only users
  13785. */
  13786. stepBack() {
  13787. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  13788. }
  13789. /**
  13790. * Toggles the playback state of the player
  13791. * This gets called when enter or space is used on the seekbar
  13792. *
  13793. * @param {KeyboardEvent} event
  13794. * The `keydown` event that caused this function to be called
  13795. *
  13796. */
  13797. handleAction(event) {
  13798. if (this.player_.paused()) {
  13799. this.player_.play();
  13800. } else {
  13801. this.player_.pause();
  13802. }
  13803. }
  13804. /**
  13805. * Called when this SeekBar has focus and a key gets pressed down.
  13806. * Supports the following keys:
  13807. *
  13808. * Space or Enter key fire a click event
  13809. * Home key moves to start of the timeline
  13810. * End key moves to end of the timeline
  13811. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  13812. * PageDown key moves back a larger step than ArrowDown
  13813. * PageUp key moves forward a large step
  13814. *
  13815. * @param {KeyboardEvent} event
  13816. * The `keydown` event that caused this function to be called.
  13817. *
  13818. * @listens keydown
  13819. */
  13820. handleKeyDown(event) {
  13821. const liveTracker = this.player_.liveTracker;
  13822. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  13823. event.preventDefault();
  13824. event.stopPropagation();
  13825. this.handleAction(event);
  13826. } else if (keycode.isEventKey(event, 'Home')) {
  13827. event.preventDefault();
  13828. event.stopPropagation();
  13829. this.userSeek_(0);
  13830. } else if (keycode.isEventKey(event, 'End')) {
  13831. event.preventDefault();
  13832. event.stopPropagation();
  13833. if (liveTracker && liveTracker.isLive()) {
  13834. this.userSeek_(liveTracker.liveCurrentTime());
  13835. } else {
  13836. this.userSeek_(this.player_.duration());
  13837. }
  13838. } else if (/^[0-9]$/.test(keycode(event))) {
  13839. event.preventDefault();
  13840. event.stopPropagation();
  13841. const gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  13842. if (liveTracker && liveTracker.isLive()) {
  13843. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  13844. } else {
  13845. this.userSeek_(this.player_.duration() * gotoFraction);
  13846. }
  13847. } else if (keycode.isEventKey(event, 'PgDn')) {
  13848. event.preventDefault();
  13849. event.stopPropagation();
  13850. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13851. } else if (keycode.isEventKey(event, 'PgUp')) {
  13852. event.preventDefault();
  13853. event.stopPropagation();
  13854. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  13855. } else {
  13856. // Pass keydown handling up for unsupported keys
  13857. super.handleKeyDown(event);
  13858. }
  13859. }
  13860. dispose() {
  13861. this.disableInterval_();
  13862. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  13863. if (this.player_.liveTracker) {
  13864. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  13865. }
  13866. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  13867. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  13868. // we don't need to update the play progress if the document is hidden,
  13869. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13870. if ('hidden' in document && 'visibilityState' in document) {
  13871. this.off(document, 'visibilitychange', this.toggleVisibility_);
  13872. }
  13873. super.dispose();
  13874. }
  13875. }
  13876. /**
  13877. * Default options for the `SeekBar`
  13878. *
  13879. * @type {Object}
  13880. * @private
  13881. */
  13882. SeekBar.prototype.options_ = {
  13883. children: ['loadProgressBar', 'playProgressBar'],
  13884. barName: 'playProgressBar'
  13885. };
  13886. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  13887. if (!IS_IOS && !IS_ANDROID) {
  13888. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  13889. }
  13890. Component.registerComponent('SeekBar', SeekBar);
  13891. /**
  13892. * @file progress-control.js
  13893. */
  13894. /**
  13895. * The Progress Control component contains the seek bar, load progress,
  13896. * and play progress.
  13897. *
  13898. * @extends Component
  13899. */
  13900. class ProgressControl extends Component {
  13901. /**
  13902. * Creates an instance of this class.
  13903. *
  13904. * @param { import('../../player').default } player
  13905. * The `Player` that this class should be attached to.
  13906. *
  13907. * @param {Object} [options]
  13908. * The key/value store of player options.
  13909. */
  13910. constructor(player, options) {
  13911. super(player, options);
  13912. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  13913. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  13914. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  13915. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  13916. this.enable();
  13917. }
  13918. /**
  13919. * Create the `Component`'s DOM element
  13920. *
  13921. * @return {Element}
  13922. * The element that was created.
  13923. */
  13924. createEl() {
  13925. return super.createEl('div', {
  13926. className: 'vjs-progress-control vjs-control'
  13927. });
  13928. }
  13929. /**
  13930. * When the mouse moves over the `ProgressControl`, the pointer position
  13931. * gets passed down to the `MouseTimeDisplay` component.
  13932. *
  13933. * @param {Event} event
  13934. * The `mousemove` event that caused this function to run.
  13935. *
  13936. * @listen mousemove
  13937. */
  13938. handleMouseMove(event) {
  13939. const seekBar = this.getChild('seekBar');
  13940. if (!seekBar) {
  13941. return;
  13942. }
  13943. const playProgressBar = seekBar.getChild('playProgressBar');
  13944. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  13945. if (!playProgressBar && !mouseTimeDisplay) {
  13946. return;
  13947. }
  13948. const seekBarEl = seekBar.el();
  13949. const seekBarRect = findPosition(seekBarEl);
  13950. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  13951. // The default skin has a gap on either side of the `SeekBar`. This means
  13952. // that it's possible to trigger this behavior outside the boundaries of
  13953. // the `SeekBar`. This ensures we stay within it at all times.
  13954. seekBarPoint = clamp(seekBarPoint, 0, 1);
  13955. if (mouseTimeDisplay) {
  13956. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  13957. }
  13958. if (playProgressBar) {
  13959. playProgressBar.update(seekBarRect, seekBar.getProgress());
  13960. }
  13961. }
  13962. /**
  13963. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  13964. *
  13965. * @method ProgressControl#throttledHandleMouseSeek
  13966. * @param {Event} event
  13967. * The `mousemove` event that caused this function to run.
  13968. *
  13969. * @listen mousemove
  13970. * @listen touchmove
  13971. */
  13972. /**
  13973. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  13974. *
  13975. * @param {Event} event
  13976. * `mousedown` or `touchstart` event that triggered this function
  13977. *
  13978. * @listens mousemove
  13979. * @listens touchmove
  13980. */
  13981. handleMouseSeek(event) {
  13982. const seekBar = this.getChild('seekBar');
  13983. if (seekBar) {
  13984. seekBar.handleMouseMove(event);
  13985. }
  13986. }
  13987. /**
  13988. * Are controls are currently enabled for this progress control.
  13989. *
  13990. * @return {boolean}
  13991. * true if controls are enabled, false otherwise
  13992. */
  13993. enabled() {
  13994. return this.enabled_;
  13995. }
  13996. /**
  13997. * Disable all controls on the progress control and its children
  13998. */
  13999. disable() {
  14000. this.children().forEach(child => child.disable && child.disable());
  14001. if (!this.enabled()) {
  14002. return;
  14003. }
  14004. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14005. this.off(this.el_, 'mousemove', this.handleMouseMove);
  14006. this.removeListenersAddedOnMousedownAndTouchstart();
  14007. this.addClass('disabled');
  14008. this.enabled_ = false;
  14009. // Restore normal playback state if controls are disabled while scrubbing
  14010. if (this.player_.scrubbing()) {
  14011. const seekBar = this.getChild('seekBar');
  14012. this.player_.scrubbing(false);
  14013. if (seekBar.videoWasPlaying) {
  14014. silencePromise(this.player_.play());
  14015. }
  14016. }
  14017. }
  14018. /**
  14019. * Enable all controls on the progress control and its children
  14020. */
  14021. enable() {
  14022. this.children().forEach(child => child.enable && child.enable());
  14023. if (this.enabled()) {
  14024. return;
  14025. }
  14026. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14027. this.on(this.el_, 'mousemove', this.handleMouseMove);
  14028. this.removeClass('disabled');
  14029. this.enabled_ = true;
  14030. }
  14031. /**
  14032. * Cleanup listeners after the user finishes interacting with the progress controls
  14033. */
  14034. removeListenersAddedOnMousedownAndTouchstart() {
  14035. const doc = this.el_.ownerDocument;
  14036. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  14037. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  14038. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14039. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14040. }
  14041. /**
  14042. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  14043. *
  14044. * @param {Event} event
  14045. * `mousedown` or `touchstart` event that triggered this function
  14046. *
  14047. * @listens mousedown
  14048. * @listens touchstart
  14049. */
  14050. handleMouseDown(event) {
  14051. const doc = this.el_.ownerDocument;
  14052. const seekBar = this.getChild('seekBar');
  14053. if (seekBar) {
  14054. seekBar.handleMouseDown(event);
  14055. }
  14056. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  14057. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  14058. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14059. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14060. }
  14061. /**
  14062. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  14063. *
  14064. * @param {Event} event
  14065. * `mouseup` or `touchend` event that triggered this function.
  14066. *
  14067. * @listens touchend
  14068. * @listens mouseup
  14069. */
  14070. handleMouseUp(event) {
  14071. const seekBar = this.getChild('seekBar');
  14072. if (seekBar) {
  14073. seekBar.handleMouseUp(event);
  14074. }
  14075. this.removeListenersAddedOnMousedownAndTouchstart();
  14076. }
  14077. }
  14078. /**
  14079. * Default options for `ProgressControl`
  14080. *
  14081. * @type {Object}
  14082. * @private
  14083. */
  14084. ProgressControl.prototype.options_ = {
  14085. children: ['seekBar']
  14086. };
  14087. Component.registerComponent('ProgressControl', ProgressControl);
  14088. /**
  14089. * @file picture-in-picture-toggle.js
  14090. */
  14091. /**
  14092. * Toggle Picture-in-Picture mode
  14093. *
  14094. * @extends Button
  14095. */
  14096. class PictureInPictureToggle extends Button {
  14097. /**
  14098. * Creates an instance of this class.
  14099. *
  14100. * @param { import('./player').default } player
  14101. * The `Player` that this class should be attached to.
  14102. *
  14103. * @param {Object} [options]
  14104. * The key/value store of player options.
  14105. *
  14106. * @listens Player#enterpictureinpicture
  14107. * @listens Player#leavepictureinpicture
  14108. */
  14109. constructor(player, options) {
  14110. super(player, options);
  14111. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  14112. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  14113. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  14114. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  14115. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  14116. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  14117. if (player.isInPictureInPicture()) {
  14118. player.exitPictureInPicture();
  14119. }
  14120. this.hide();
  14121. } else {
  14122. this.show();
  14123. }
  14124. });
  14125. // TODO: Deactivate button on player emptied event.
  14126. this.disable();
  14127. }
  14128. /**
  14129. * Builds the default DOM `className`.
  14130. *
  14131. * @return {string}
  14132. * The DOM `className` for this object.
  14133. */
  14134. buildCSSClass() {
  14135. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  14136. }
  14137. /**
  14138. * Enables or disables button based on availability of a Picture-In-Picture mode.
  14139. *
  14140. * Enabled if
  14141. * - `player.options().enableDocumentPictureInPicture` is true and
  14142. * window.documentPictureInPicture is available; or
  14143. * - `player.disablePictureInPicture()` is false and
  14144. * element.requestPictureInPicture is available
  14145. */
  14146. handlePictureInPictureEnabledChange() {
  14147. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window) {
  14148. this.enable();
  14149. } else {
  14150. this.disable();
  14151. }
  14152. }
  14153. /**
  14154. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  14155. *
  14156. * @param {Event} [event]
  14157. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  14158. * called.
  14159. *
  14160. * @listens Player#enterpictureinpicture
  14161. * @listens Player#leavepictureinpicture
  14162. */
  14163. handlePictureInPictureChange(event) {
  14164. if (this.player_.isInPictureInPicture()) {
  14165. this.controlText('Exit Picture-in-Picture');
  14166. } else {
  14167. this.controlText('Picture-in-Picture');
  14168. }
  14169. this.handlePictureInPictureEnabledChange();
  14170. }
  14171. /**
  14172. * This gets called when an `PictureInPictureToggle` is "clicked". See
  14173. * {@link ClickableComponent} for more detailed information on what a click can be.
  14174. *
  14175. * @param {Event} [event]
  14176. * The `keydown`, `tap`, or `click` event that caused this function to be
  14177. * called.
  14178. *
  14179. * @listens tap
  14180. * @listens click
  14181. */
  14182. handleClick(event) {
  14183. if (!this.player_.isInPictureInPicture()) {
  14184. this.player_.requestPictureInPicture();
  14185. } else {
  14186. this.player_.exitPictureInPicture();
  14187. }
  14188. }
  14189. }
  14190. /**
  14191. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  14192. *
  14193. * @type {string}
  14194. * @protected
  14195. */
  14196. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  14197. Component.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  14198. /**
  14199. * @file fullscreen-toggle.js
  14200. */
  14201. /**
  14202. * Toggle fullscreen video
  14203. *
  14204. * @extends Button
  14205. */
  14206. class FullscreenToggle extends Button {
  14207. /**
  14208. * Creates an instance of this class.
  14209. *
  14210. * @param { import('./player').default } player
  14211. * The `Player` that this class should be attached to.
  14212. *
  14213. * @param {Object} [options]
  14214. * The key/value store of player options.
  14215. */
  14216. constructor(player, options) {
  14217. super(player, options);
  14218. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  14219. if (document[player.fsApi_.fullscreenEnabled] === false) {
  14220. this.disable();
  14221. }
  14222. }
  14223. /**
  14224. * Builds the default DOM `className`.
  14225. *
  14226. * @return {string}
  14227. * The DOM `className` for this object.
  14228. */
  14229. buildCSSClass() {
  14230. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  14231. }
  14232. /**
  14233. * Handles fullscreenchange on the player and change control text accordingly.
  14234. *
  14235. * @param {Event} [event]
  14236. * The {@link Player#fullscreenchange} event that caused this function to be
  14237. * called.
  14238. *
  14239. * @listens Player#fullscreenchange
  14240. */
  14241. handleFullscreenChange(event) {
  14242. if (this.player_.isFullscreen()) {
  14243. this.controlText('Exit Fullscreen');
  14244. } else {
  14245. this.controlText('Fullscreen');
  14246. }
  14247. }
  14248. /**
  14249. * This gets called when an `FullscreenToggle` is "clicked". See
  14250. * {@link ClickableComponent} for more detailed information on what a click can be.
  14251. *
  14252. * @param {Event} [event]
  14253. * The `keydown`, `tap`, or `click` event that caused this function to be
  14254. * called.
  14255. *
  14256. * @listens tap
  14257. * @listens click
  14258. */
  14259. handleClick(event) {
  14260. if (!this.player_.isFullscreen()) {
  14261. this.player_.requestFullscreen();
  14262. } else {
  14263. this.player_.exitFullscreen();
  14264. }
  14265. }
  14266. }
  14267. /**
  14268. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  14269. *
  14270. * @type {string}
  14271. * @protected
  14272. */
  14273. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  14274. Component.registerComponent('FullscreenToggle', FullscreenToggle);
  14275. /**
  14276. * Check if volume control is supported and if it isn't hide the
  14277. * `Component` that was passed using the `vjs-hidden` class.
  14278. *
  14279. * @param { import('../../component').default } self
  14280. * The component that should be hidden if volume is unsupported
  14281. *
  14282. * @param { import('../../player').default } player
  14283. * A reference to the player
  14284. *
  14285. * @private
  14286. */
  14287. const checkVolumeSupport = function (self, player) {
  14288. // hide volume controls when they're not supported by the current tech
  14289. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  14290. self.addClass('vjs-hidden');
  14291. }
  14292. self.on(player, 'loadstart', function () {
  14293. if (!player.tech_.featuresVolumeControl) {
  14294. self.addClass('vjs-hidden');
  14295. } else {
  14296. self.removeClass('vjs-hidden');
  14297. }
  14298. });
  14299. };
  14300. /**
  14301. * @file volume-level.js
  14302. */
  14303. /**
  14304. * Shows volume level
  14305. *
  14306. * @extends Component
  14307. */
  14308. class VolumeLevel extends Component {
  14309. /**
  14310. * Create the `Component`'s DOM element
  14311. *
  14312. * @return {Element}
  14313. * The element that was created.
  14314. */
  14315. createEl() {
  14316. const el = super.createEl('div', {
  14317. className: 'vjs-volume-level'
  14318. });
  14319. el.appendChild(super.createEl('span', {
  14320. className: 'vjs-control-text'
  14321. }));
  14322. return el;
  14323. }
  14324. }
  14325. Component.registerComponent('VolumeLevel', VolumeLevel);
  14326. /**
  14327. * @file volume-level-tooltip.js
  14328. */
  14329. /**
  14330. * Volume level tooltips display a volume above or side by side the volume bar.
  14331. *
  14332. * @extends Component
  14333. */
  14334. class VolumeLevelTooltip extends Component {
  14335. /**
  14336. * Creates an instance of this class.
  14337. *
  14338. * @param { import('../../player').default } player
  14339. * The {@link Player} that this class should be attached to.
  14340. *
  14341. * @param {Object} [options]
  14342. * The key/value store of player options.
  14343. */
  14344. constructor(player, options) {
  14345. super(player, options);
  14346. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14347. }
  14348. /**
  14349. * Create the volume tooltip DOM element
  14350. *
  14351. * @return {Element}
  14352. * The element that was created.
  14353. */
  14354. createEl() {
  14355. return super.createEl('div', {
  14356. className: 'vjs-volume-tooltip'
  14357. }, {
  14358. 'aria-hidden': 'true'
  14359. });
  14360. }
  14361. /**
  14362. * Updates the position of the tooltip relative to the `VolumeBar` and
  14363. * its content text.
  14364. *
  14365. * @param {Object} rangeBarRect
  14366. * The `ClientRect` for the {@link VolumeBar} element.
  14367. *
  14368. * @param {number} rangeBarPoint
  14369. * A number from 0 to 1, representing a horizontal/vertical reference point
  14370. * from the left edge of the {@link VolumeBar}
  14371. *
  14372. * @param {boolean} vertical
  14373. * Referees to the Volume control position
  14374. * in the control bar{@link VolumeControl}
  14375. *
  14376. */
  14377. update(rangeBarRect, rangeBarPoint, vertical, content) {
  14378. if (!vertical) {
  14379. const tooltipRect = getBoundingClientRect(this.el_);
  14380. const playerRect = getBoundingClientRect(this.player_.el());
  14381. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  14382. if (!playerRect || !tooltipRect) {
  14383. return;
  14384. }
  14385. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  14386. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  14387. let pullTooltipBy = tooltipRect.width / 2;
  14388. if (spaceLeftOfPoint < pullTooltipBy) {
  14389. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  14390. } else if (spaceRightOfPoint < pullTooltipBy) {
  14391. pullTooltipBy = spaceRightOfPoint;
  14392. }
  14393. if (pullTooltipBy < 0) {
  14394. pullTooltipBy = 0;
  14395. } else if (pullTooltipBy > tooltipRect.width) {
  14396. pullTooltipBy = tooltipRect.width;
  14397. }
  14398. this.el_.style.right = `-${pullTooltipBy}px`;
  14399. }
  14400. this.write(`${content}%`);
  14401. }
  14402. /**
  14403. * Write the volume to the tooltip DOM element.
  14404. *
  14405. * @param {string} content
  14406. * The formatted volume for the tooltip.
  14407. */
  14408. write(content) {
  14409. textContent(this.el_, content);
  14410. }
  14411. /**
  14412. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  14413. *
  14414. * @param {Object} rangeBarRect
  14415. * The `ClientRect` for the {@link VolumeBar} element.
  14416. *
  14417. * @param {number} rangeBarPoint
  14418. * A number from 0 to 1, representing a horizontal/vertical reference point
  14419. * from the left edge of the {@link VolumeBar}
  14420. *
  14421. * @param {boolean} vertical
  14422. * Referees to the Volume control position
  14423. * in the control bar{@link VolumeControl}
  14424. *
  14425. * @param {number} volume
  14426. * The volume level to update the tooltip to
  14427. *
  14428. * @param {Function} cb
  14429. * A function that will be called during the request animation frame
  14430. * for tooltips that need to do additional animations from the default
  14431. */
  14432. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  14433. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  14434. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  14435. if (cb) {
  14436. cb();
  14437. }
  14438. });
  14439. }
  14440. }
  14441. Component.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  14442. /**
  14443. * @file mouse-volume-level-display.js
  14444. */
  14445. /**
  14446. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  14447. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  14448. * indicating the volume level which is represented by a given point in the
  14449. * {@link VolumeBar}.
  14450. *
  14451. * @extends Component
  14452. */
  14453. class MouseVolumeLevelDisplay extends Component {
  14454. /**
  14455. * Creates an instance of this class.
  14456. *
  14457. * @param { import('../../player').default } player
  14458. * The {@link Player} that this class should be attached to.
  14459. *
  14460. * @param {Object} [options]
  14461. * The key/value store of player options.
  14462. */
  14463. constructor(player, options) {
  14464. super(player, options);
  14465. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  14466. }
  14467. /**
  14468. * Create the DOM element for this class.
  14469. *
  14470. * @return {Element}
  14471. * The element that was created.
  14472. */
  14473. createEl() {
  14474. return super.createEl('div', {
  14475. className: 'vjs-mouse-display'
  14476. });
  14477. }
  14478. /**
  14479. * Enquires updates to its own DOM as well as the DOM of its
  14480. * {@link VolumeLevelTooltip} child.
  14481. *
  14482. * @param {Object} rangeBarRect
  14483. * The `ClientRect` for the {@link VolumeBar} element.
  14484. *
  14485. * @param {number} rangeBarPoint
  14486. * A number from 0 to 1, representing a horizontal/vertical reference point
  14487. * from the left edge of the {@link VolumeBar}
  14488. *
  14489. * @param {boolean} vertical
  14490. * Referees to the Volume control position
  14491. * in the control bar{@link VolumeControl}
  14492. *
  14493. */
  14494. update(rangeBarRect, rangeBarPoint, vertical) {
  14495. const volume = 100 * rangeBarPoint;
  14496. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  14497. if (vertical) {
  14498. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  14499. } else {
  14500. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  14501. }
  14502. });
  14503. }
  14504. }
  14505. /**
  14506. * Default options for `MouseVolumeLevelDisplay`
  14507. *
  14508. * @type {Object}
  14509. * @private
  14510. */
  14511. MouseVolumeLevelDisplay.prototype.options_ = {
  14512. children: ['volumeLevelTooltip']
  14513. };
  14514. Component.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  14515. /**
  14516. * @file volume-bar.js
  14517. */
  14518. /**
  14519. * The bar that contains the volume level and can be clicked on to adjust the level
  14520. *
  14521. * @extends Slider
  14522. */
  14523. class VolumeBar extends Slider {
  14524. /**
  14525. * Creates an instance of this class.
  14526. *
  14527. * @param { import('../../player').default } player
  14528. * The `Player` that this class should be attached to.
  14529. *
  14530. * @param {Object} [options]
  14531. * The key/value store of player options.
  14532. */
  14533. constructor(player, options) {
  14534. super(player, options);
  14535. this.on('slideractive', e => this.updateLastVolume_(e));
  14536. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  14537. player.ready(() => this.updateARIAAttributes());
  14538. }
  14539. /**
  14540. * Create the `Component`'s DOM element
  14541. *
  14542. * @return {Element}
  14543. * The element that was created.
  14544. */
  14545. createEl() {
  14546. return super.createEl('div', {
  14547. className: 'vjs-volume-bar vjs-slider-bar'
  14548. }, {
  14549. 'aria-label': this.localize('Volume Level'),
  14550. 'aria-live': 'polite'
  14551. });
  14552. }
  14553. /**
  14554. * Handle mouse down on volume bar
  14555. *
  14556. * @param {Event} event
  14557. * The `mousedown` event that caused this to run.
  14558. *
  14559. * @listens mousedown
  14560. */
  14561. handleMouseDown(event) {
  14562. if (!isSingleLeftClick(event)) {
  14563. return;
  14564. }
  14565. super.handleMouseDown(event);
  14566. }
  14567. /**
  14568. * Handle movement events on the {@link VolumeMenuButton}.
  14569. *
  14570. * @param {Event} event
  14571. * The event that caused this function to run.
  14572. *
  14573. * @listens mousemove
  14574. */
  14575. handleMouseMove(event) {
  14576. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  14577. if (mouseVolumeLevelDisplay) {
  14578. const volumeBarEl = this.el();
  14579. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  14580. const vertical = this.vertical();
  14581. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  14582. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  14583. // The default skin has a gap on either side of the `VolumeBar`. This means
  14584. // that it's possible to trigger this behavior outside the boundaries of
  14585. // the `VolumeBar`. This ensures we stay within it at all times.
  14586. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  14587. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  14588. }
  14589. if (!isSingleLeftClick(event)) {
  14590. return;
  14591. }
  14592. this.checkMuted();
  14593. this.player_.volume(this.calculateDistance(event));
  14594. }
  14595. /**
  14596. * If the player is muted unmute it.
  14597. */
  14598. checkMuted() {
  14599. if (this.player_.muted()) {
  14600. this.player_.muted(false);
  14601. }
  14602. }
  14603. /**
  14604. * Get percent of volume level
  14605. *
  14606. * @return {number}
  14607. * Volume level percent as a decimal number.
  14608. */
  14609. getPercent() {
  14610. if (this.player_.muted()) {
  14611. return 0;
  14612. }
  14613. return this.player_.volume();
  14614. }
  14615. /**
  14616. * Increase volume level for keyboard users
  14617. */
  14618. stepForward() {
  14619. this.checkMuted();
  14620. this.player_.volume(this.player_.volume() + 0.1);
  14621. }
  14622. /**
  14623. * Decrease volume level for keyboard users
  14624. */
  14625. stepBack() {
  14626. this.checkMuted();
  14627. this.player_.volume(this.player_.volume() - 0.1);
  14628. }
  14629. /**
  14630. * Update ARIA accessibility attributes
  14631. *
  14632. * @param {Event} [event]
  14633. * The `volumechange` event that caused this function to run.
  14634. *
  14635. * @listens Player#volumechange
  14636. */
  14637. updateARIAAttributes(event) {
  14638. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  14639. this.el_.setAttribute('aria-valuenow', ariaValue);
  14640. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  14641. }
  14642. /**
  14643. * Returns the current value of the player volume as a percentage
  14644. *
  14645. * @private
  14646. */
  14647. volumeAsPercentage_() {
  14648. return Math.round(this.player_.volume() * 100);
  14649. }
  14650. /**
  14651. * When user starts dragging the VolumeBar, store the volume and listen for
  14652. * the end of the drag. When the drag ends, if the volume was set to zero,
  14653. * set lastVolume to the stored volume.
  14654. *
  14655. * @listens slideractive
  14656. * @private
  14657. */
  14658. updateLastVolume_() {
  14659. const volumeBeforeDrag = this.player_.volume();
  14660. this.one('sliderinactive', () => {
  14661. if (this.player_.volume() === 0) {
  14662. this.player_.lastVolume_(volumeBeforeDrag);
  14663. }
  14664. });
  14665. }
  14666. }
  14667. /**
  14668. * Default options for the `VolumeBar`
  14669. *
  14670. * @type {Object}
  14671. * @private
  14672. */
  14673. VolumeBar.prototype.options_ = {
  14674. children: ['volumeLevel'],
  14675. barName: 'volumeLevel'
  14676. };
  14677. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  14678. if (!IS_IOS && !IS_ANDROID) {
  14679. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  14680. }
  14681. /**
  14682. * Call the update event for this Slider when this event happens on the player.
  14683. *
  14684. * @type {string}
  14685. */
  14686. VolumeBar.prototype.playerEvent = 'volumechange';
  14687. Component.registerComponent('VolumeBar', VolumeBar);
  14688. /**
  14689. * @file volume-control.js
  14690. */
  14691. /**
  14692. * The component for controlling the volume level
  14693. *
  14694. * @extends Component
  14695. */
  14696. class VolumeControl extends Component {
  14697. /**
  14698. * Creates an instance of this class.
  14699. *
  14700. * @param { import('../../player').default } player
  14701. * The `Player` that this class should be attached to.
  14702. *
  14703. * @param {Object} [options={}]
  14704. * The key/value store of player options.
  14705. */
  14706. constructor(player, options = {}) {
  14707. options.vertical = options.vertical || false;
  14708. // Pass the vertical option down to the VolumeBar if
  14709. // the VolumeBar is turned on.
  14710. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  14711. options.volumeBar = options.volumeBar || {};
  14712. options.volumeBar.vertical = options.vertical;
  14713. }
  14714. super(player, options);
  14715. // hide this control if volume support is missing
  14716. checkVolumeSupport(this, player);
  14717. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  14718. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  14719. this.on('mousedown', e => this.handleMouseDown(e));
  14720. this.on('touchstart', e => this.handleMouseDown(e));
  14721. this.on('mousemove', e => this.handleMouseMove(e));
  14722. // while the slider is active (the mouse has been pressed down and
  14723. // is dragging) or in focus we do not want to hide the VolumeBar
  14724. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  14725. this.volumeBar.addClass('vjs-slider-active');
  14726. this.addClass('vjs-slider-active');
  14727. this.trigger('slideractive');
  14728. });
  14729. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  14730. this.volumeBar.removeClass('vjs-slider-active');
  14731. this.removeClass('vjs-slider-active');
  14732. this.trigger('sliderinactive');
  14733. });
  14734. }
  14735. /**
  14736. * Create the `Component`'s DOM element
  14737. *
  14738. * @return {Element}
  14739. * The element that was created.
  14740. */
  14741. createEl() {
  14742. let orientationClass = 'vjs-volume-horizontal';
  14743. if (this.options_.vertical) {
  14744. orientationClass = 'vjs-volume-vertical';
  14745. }
  14746. return super.createEl('div', {
  14747. className: `vjs-volume-control vjs-control ${orientationClass}`
  14748. });
  14749. }
  14750. /**
  14751. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14752. *
  14753. * @param {Event} event
  14754. * `mousedown` or `touchstart` event that triggered this function
  14755. *
  14756. * @listens mousedown
  14757. * @listens touchstart
  14758. */
  14759. handleMouseDown(event) {
  14760. const doc = this.el_.ownerDocument;
  14761. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  14762. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  14763. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14764. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14765. }
  14766. /**
  14767. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  14768. *
  14769. * @param {Event} event
  14770. * `mouseup` or `touchend` event that triggered this function.
  14771. *
  14772. * @listens touchend
  14773. * @listens mouseup
  14774. */
  14775. handleMouseUp(event) {
  14776. const doc = this.el_.ownerDocument;
  14777. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  14778. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  14779. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14780. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14781. }
  14782. /**
  14783. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  14784. *
  14785. * @param {Event} event
  14786. * `mousedown` or `touchstart` event that triggered this function
  14787. *
  14788. * @listens mousedown
  14789. * @listens touchstart
  14790. */
  14791. handleMouseMove(event) {
  14792. this.volumeBar.handleMouseMove(event);
  14793. }
  14794. }
  14795. /**
  14796. * Default options for the `VolumeControl`
  14797. *
  14798. * @type {Object}
  14799. * @private
  14800. */
  14801. VolumeControl.prototype.options_ = {
  14802. children: ['volumeBar']
  14803. };
  14804. Component.registerComponent('VolumeControl', VolumeControl);
  14805. /**
  14806. * Check if muting volume is supported and if it isn't hide the mute toggle
  14807. * button.
  14808. *
  14809. * @param { import('../../component').default } self
  14810. * A reference to the mute toggle button
  14811. *
  14812. * @param { import('../../player').default } player
  14813. * A reference to the player
  14814. *
  14815. * @private
  14816. */
  14817. const checkMuteSupport = function (self, player) {
  14818. // hide mute toggle button if it's not supported by the current tech
  14819. if (player.tech_ && !player.tech_.featuresMuteControl) {
  14820. self.addClass('vjs-hidden');
  14821. }
  14822. self.on(player, 'loadstart', function () {
  14823. if (!player.tech_.featuresMuteControl) {
  14824. self.addClass('vjs-hidden');
  14825. } else {
  14826. self.removeClass('vjs-hidden');
  14827. }
  14828. });
  14829. };
  14830. /**
  14831. * @file mute-toggle.js
  14832. */
  14833. /**
  14834. * A button component for muting the audio.
  14835. *
  14836. * @extends Button
  14837. */
  14838. class MuteToggle extends Button {
  14839. /**
  14840. * Creates an instance of this class.
  14841. *
  14842. * @param { import('./player').default } player
  14843. * The `Player` that this class should be attached to.
  14844. *
  14845. * @param {Object} [options]
  14846. * The key/value store of player options.
  14847. */
  14848. constructor(player, options) {
  14849. super(player, options);
  14850. // hide this control if volume support is missing
  14851. checkMuteSupport(this, player);
  14852. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  14853. }
  14854. /**
  14855. * Builds the default DOM `className`.
  14856. *
  14857. * @return {string}
  14858. * The DOM `className` for this object.
  14859. */
  14860. buildCSSClass() {
  14861. return `vjs-mute-control ${super.buildCSSClass()}`;
  14862. }
  14863. /**
  14864. * This gets called when an `MuteToggle` is "clicked". See
  14865. * {@link ClickableComponent} for more detailed information on what a click can be.
  14866. *
  14867. * @param {Event} [event]
  14868. * The `keydown`, `tap`, or `click` event that caused this function to be
  14869. * called.
  14870. *
  14871. * @listens tap
  14872. * @listens click
  14873. */
  14874. handleClick(event) {
  14875. const vol = this.player_.volume();
  14876. const lastVolume = this.player_.lastVolume_();
  14877. if (vol === 0) {
  14878. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  14879. this.player_.volume(volumeToSet);
  14880. this.player_.muted(false);
  14881. } else {
  14882. this.player_.muted(this.player_.muted() ? false : true);
  14883. }
  14884. }
  14885. /**
  14886. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  14887. * on the player.
  14888. *
  14889. * @param {Event} [event]
  14890. * The {@link Player#loadstart} event if this function was called
  14891. * through an event.
  14892. *
  14893. * @listens Player#loadstart
  14894. * @listens Player#volumechange
  14895. */
  14896. update(event) {
  14897. this.updateIcon_();
  14898. this.updateControlText_();
  14899. }
  14900. /**
  14901. * Update the appearance of the `MuteToggle` icon.
  14902. *
  14903. * Possible states (given `level` variable below):
  14904. * - 0: crossed out
  14905. * - 1: zero bars of volume
  14906. * - 2: one bar of volume
  14907. * - 3: two bars of volume
  14908. *
  14909. * @private
  14910. */
  14911. updateIcon_() {
  14912. const vol = this.player_.volume();
  14913. let level = 3;
  14914. // in iOS when a player is loaded with muted attribute
  14915. // and volume is changed with a native mute button
  14916. // we want to make sure muted state is updated
  14917. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  14918. this.player_.muted(this.player_.tech_.el_.muted);
  14919. }
  14920. if (vol === 0 || this.player_.muted()) {
  14921. level = 0;
  14922. } else if (vol < 0.33) {
  14923. level = 1;
  14924. } else if (vol < 0.67) {
  14925. level = 2;
  14926. }
  14927. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  14928. addClass(this.el_, `vjs-vol-${level}`);
  14929. }
  14930. /**
  14931. * If `muted` has changed on the player, update the control text
  14932. * (`title` attribute on `vjs-mute-control` element and content of
  14933. * `vjs-control-text` element).
  14934. *
  14935. * @private
  14936. */
  14937. updateControlText_() {
  14938. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  14939. const text = soundOff ? 'Unmute' : 'Mute';
  14940. if (this.controlText() !== text) {
  14941. this.controlText(text);
  14942. }
  14943. }
  14944. }
  14945. /**
  14946. * The text that should display over the `MuteToggle`s controls. Added for localization.
  14947. *
  14948. * @type {string}
  14949. * @protected
  14950. */
  14951. MuteToggle.prototype.controlText_ = 'Mute';
  14952. Component.registerComponent('MuteToggle', MuteToggle);
  14953. /**
  14954. * @file volume-control.js
  14955. */
  14956. /**
  14957. * A Component to contain the MuteToggle and VolumeControl so that
  14958. * they can work together.
  14959. *
  14960. * @extends Component
  14961. */
  14962. class VolumePanel extends Component {
  14963. /**
  14964. * Creates an instance of this class.
  14965. *
  14966. * @param { import('./player').default } player
  14967. * The `Player` that this class should be attached to.
  14968. *
  14969. * @param {Object} [options={}]
  14970. * The key/value store of player options.
  14971. */
  14972. constructor(player, options = {}) {
  14973. if (typeof options.inline !== 'undefined') {
  14974. options.inline = options.inline;
  14975. } else {
  14976. options.inline = true;
  14977. }
  14978. // pass the inline option down to the VolumeControl as vertical if
  14979. // the VolumeControl is on.
  14980. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  14981. options.volumeControl = options.volumeControl || {};
  14982. options.volumeControl.vertical = !options.inline;
  14983. }
  14984. super(player, options);
  14985. // this handler is used by mouse handler methods below
  14986. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  14987. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  14988. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  14989. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  14990. this.on('keydown', e => this.handleKeyPress(e));
  14991. this.on('mouseover', e => this.handleMouseOver(e));
  14992. this.on('mouseout', e => this.handleMouseOut(e));
  14993. // while the slider is active (the mouse has been pressed down and
  14994. // is dragging) we do not want to hide the VolumeBar
  14995. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  14996. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  14997. }
  14998. /**
  14999. * Add vjs-slider-active class to the VolumePanel
  15000. *
  15001. * @listens VolumeControl#slideractive
  15002. * @private
  15003. */
  15004. sliderActive_() {
  15005. this.addClass('vjs-slider-active');
  15006. }
  15007. /**
  15008. * Removes vjs-slider-active class to the VolumePanel
  15009. *
  15010. * @listens VolumeControl#sliderinactive
  15011. * @private
  15012. */
  15013. sliderInactive_() {
  15014. this.removeClass('vjs-slider-active');
  15015. }
  15016. /**
  15017. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  15018. * depending on MuteToggle and VolumeControl state
  15019. *
  15020. * @listens Player#loadstart
  15021. * @private
  15022. */
  15023. volumePanelState_() {
  15024. // hide volume panel if neither volume control or mute toggle
  15025. // are displayed
  15026. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  15027. this.addClass('vjs-hidden');
  15028. }
  15029. // if only mute toggle is visible we don't want
  15030. // volume panel expanding when hovered or active
  15031. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  15032. this.addClass('vjs-mute-toggle-only');
  15033. }
  15034. }
  15035. /**
  15036. * Create the `Component`'s DOM element
  15037. *
  15038. * @return {Element}
  15039. * The element that was created.
  15040. */
  15041. createEl() {
  15042. let orientationClass = 'vjs-volume-panel-horizontal';
  15043. if (!this.options_.inline) {
  15044. orientationClass = 'vjs-volume-panel-vertical';
  15045. }
  15046. return super.createEl('div', {
  15047. className: `vjs-volume-panel vjs-control ${orientationClass}`
  15048. });
  15049. }
  15050. /**
  15051. * Dispose of the `volume-panel` and all child components.
  15052. */
  15053. dispose() {
  15054. this.handleMouseOut();
  15055. super.dispose();
  15056. }
  15057. /**
  15058. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  15059. * the volume panel and sets focus on `MuteToggle`.
  15060. *
  15061. * @param {Event} event
  15062. * The `keyup` event that caused this function to be called.
  15063. *
  15064. * @listens keyup
  15065. */
  15066. handleVolumeControlKeyUp(event) {
  15067. if (keycode.isEventKey(event, 'Esc')) {
  15068. this.muteToggle.focus();
  15069. }
  15070. }
  15071. /**
  15072. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  15073. * Turns on listening for `mouseover` event. When they happen it
  15074. * calls `this.handleMouseOver`.
  15075. *
  15076. * @param {Event} event
  15077. * The `mouseover` event that caused this function to be called.
  15078. *
  15079. * @listens mouseover
  15080. */
  15081. handleMouseOver(event) {
  15082. this.addClass('vjs-hover');
  15083. on(document, 'keyup', this.handleKeyPressHandler_);
  15084. }
  15085. /**
  15086. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  15087. * Turns on listening for `mouseout` event. When they happen it
  15088. * calls `this.handleMouseOut`.
  15089. *
  15090. * @param {Event} event
  15091. * The `mouseout` event that caused this function to be called.
  15092. *
  15093. * @listens mouseout
  15094. */
  15095. handleMouseOut(event) {
  15096. this.removeClass('vjs-hover');
  15097. off(document, 'keyup', this.handleKeyPressHandler_);
  15098. }
  15099. /**
  15100. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  15101. * looking for ESC, which hides the `VolumeControl`.
  15102. *
  15103. * @param {Event} event
  15104. * The keypress that triggered this event.
  15105. *
  15106. * @listens keydown | keyup
  15107. */
  15108. handleKeyPress(event) {
  15109. if (keycode.isEventKey(event, 'Esc')) {
  15110. this.handleMouseOut();
  15111. }
  15112. }
  15113. }
  15114. /**
  15115. * Default options for the `VolumeControl`
  15116. *
  15117. * @type {Object}
  15118. * @private
  15119. */
  15120. VolumePanel.prototype.options_ = {
  15121. children: ['muteToggle', 'volumeControl']
  15122. };
  15123. Component.registerComponent('VolumePanel', VolumePanel);
  15124. /**
  15125. * Button to skip forward a configurable amount of time
  15126. * through a video. Renders in the control bar.
  15127. *
  15128. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  15129. *
  15130. * @extends Button
  15131. */
  15132. class SkipForward extends Button {
  15133. constructor(player, options) {
  15134. super(player, options);
  15135. this.validOptions = [5, 10, 30];
  15136. this.skipTime = this.getSkipForwardTime();
  15137. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  15138. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  15139. this.show();
  15140. } else {
  15141. this.hide();
  15142. }
  15143. }
  15144. getSkipForwardTime() {
  15145. const playerOptions = this.options_.playerOptions;
  15146. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  15147. }
  15148. buildCSSClass() {
  15149. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  15150. }
  15151. /**
  15152. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  15153. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  15154. * skips to end of duration/seekable range.
  15155. *
  15156. * Handle a click on a `SkipForward` button
  15157. *
  15158. * @param {EventTarget~Event} event
  15159. * The `click` event that caused this function
  15160. * to be called
  15161. */
  15162. handleClick(event) {
  15163. const currentVideoTime = this.player_.currentTime();
  15164. const liveTracker = this.player_.liveTracker;
  15165. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  15166. let newTime;
  15167. if (currentVideoTime + this.skipTime <= duration) {
  15168. newTime = currentVideoTime + this.skipTime;
  15169. } else {
  15170. newTime = duration;
  15171. }
  15172. this.player_.currentTime(newTime);
  15173. }
  15174. /**
  15175. * Update control text on languagechange
  15176. */
  15177. handleLanguagechange() {
  15178. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  15179. }
  15180. }
  15181. Component.registerComponent('SkipForward', SkipForward);
  15182. /**
  15183. * Button to skip backward a configurable amount of time
  15184. * through a video. Renders in the control bar.
  15185. *
  15186. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  15187. *
  15188. * @extends Button
  15189. */
  15190. class SkipBackward extends Button {
  15191. constructor(player, options) {
  15192. super(player, options);
  15193. this.validOptions = [5, 10, 30];
  15194. this.skipTime = this.getSkipBackwardTime();
  15195. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  15196. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  15197. this.show();
  15198. } else {
  15199. this.hide();
  15200. }
  15201. }
  15202. getSkipBackwardTime() {
  15203. const playerOptions = this.options_.playerOptions;
  15204. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  15205. }
  15206. buildCSSClass() {
  15207. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  15208. }
  15209. /**
  15210. * On click, skips backward in the video by a configurable amount of seconds.
  15211. * If the current time in the video is less than the configured 'skip backward' time,
  15212. * skips to beginning of video or seekable range.
  15213. *
  15214. * Handle a click on a `SkipBackward` button
  15215. *
  15216. * @param {EventTarget~Event} event
  15217. * The `click` event that caused this function
  15218. * to be called
  15219. */
  15220. handleClick(event) {
  15221. const currentVideoTime = this.player_.currentTime();
  15222. const liveTracker = this.player_.liveTracker;
  15223. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  15224. let newTime;
  15225. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  15226. newTime = seekableStart;
  15227. } else if (currentVideoTime >= this.skipTime) {
  15228. newTime = currentVideoTime - this.skipTime;
  15229. } else {
  15230. newTime = 0;
  15231. }
  15232. this.player_.currentTime(newTime);
  15233. }
  15234. /**
  15235. * Update control text on languagechange
  15236. */
  15237. handleLanguagechange() {
  15238. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  15239. }
  15240. }
  15241. SkipBackward.prototype.controlText_ = 'Skip Backward';
  15242. Component.registerComponent('SkipBackward', SkipBackward);
  15243. /**
  15244. * @file menu.js
  15245. */
  15246. /**
  15247. * The Menu component is used to build popup menus, including subtitle and
  15248. * captions selection menus.
  15249. *
  15250. * @extends Component
  15251. */
  15252. class Menu extends Component {
  15253. /**
  15254. * Create an instance of this class.
  15255. *
  15256. * @param { import('../player').default } player
  15257. * the player that this component should attach to
  15258. *
  15259. * @param {Object} [options]
  15260. * Object of option names and values
  15261. *
  15262. */
  15263. constructor(player, options) {
  15264. super(player, options);
  15265. if (options) {
  15266. this.menuButton_ = options.menuButton;
  15267. }
  15268. this.focusedChild_ = -1;
  15269. this.on('keydown', e => this.handleKeyDown(e));
  15270. // All the menu item instances share the same blur handler provided by the menu container.
  15271. this.boundHandleBlur_ = e => this.handleBlur(e);
  15272. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  15273. }
  15274. /**
  15275. * Add event listeners to the {@link MenuItem}.
  15276. *
  15277. * @param {Object} component
  15278. * The instance of the `MenuItem` to add listeners to.
  15279. *
  15280. */
  15281. addEventListenerForItem(component) {
  15282. if (!(component instanceof Component)) {
  15283. return;
  15284. }
  15285. this.on(component, 'blur', this.boundHandleBlur_);
  15286. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  15287. }
  15288. /**
  15289. * Remove event listeners from the {@link MenuItem}.
  15290. *
  15291. * @param {Object} component
  15292. * The instance of the `MenuItem` to remove listeners.
  15293. *
  15294. */
  15295. removeEventListenerForItem(component) {
  15296. if (!(component instanceof Component)) {
  15297. return;
  15298. }
  15299. this.off(component, 'blur', this.boundHandleBlur_);
  15300. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  15301. }
  15302. /**
  15303. * This method will be called indirectly when the component has been added
  15304. * before the component adds to the new menu instance by `addItem`.
  15305. * In this case, the original menu instance will remove the component
  15306. * by calling `removeChild`.
  15307. *
  15308. * @param {Object} component
  15309. * The instance of the `MenuItem`
  15310. */
  15311. removeChild(component) {
  15312. if (typeof component === 'string') {
  15313. component = this.getChild(component);
  15314. }
  15315. this.removeEventListenerForItem(component);
  15316. super.removeChild(component);
  15317. }
  15318. /**
  15319. * Add a {@link MenuItem} to the menu.
  15320. *
  15321. * @param {Object|string} component
  15322. * The name or instance of the `MenuItem` to add.
  15323. *
  15324. */
  15325. addItem(component) {
  15326. const childComponent = this.addChild(component);
  15327. if (childComponent) {
  15328. this.addEventListenerForItem(childComponent);
  15329. }
  15330. }
  15331. /**
  15332. * Create the `Menu`s DOM element.
  15333. *
  15334. * @return {Element}
  15335. * the element that was created
  15336. */
  15337. createEl() {
  15338. const contentElType = this.options_.contentElType || 'ul';
  15339. this.contentEl_ = createEl(contentElType, {
  15340. className: 'vjs-menu-content'
  15341. });
  15342. this.contentEl_.setAttribute('role', 'menu');
  15343. const el = super.createEl('div', {
  15344. append: this.contentEl_,
  15345. className: 'vjs-menu'
  15346. });
  15347. el.appendChild(this.contentEl_);
  15348. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  15349. // where a click on the parent is significant
  15350. on(el, 'click', function (event) {
  15351. event.preventDefault();
  15352. event.stopImmediatePropagation();
  15353. });
  15354. return el;
  15355. }
  15356. dispose() {
  15357. this.contentEl_ = null;
  15358. this.boundHandleBlur_ = null;
  15359. this.boundHandleTapClick_ = null;
  15360. super.dispose();
  15361. }
  15362. /**
  15363. * Called when a `MenuItem` loses focus.
  15364. *
  15365. * @param {Event} event
  15366. * The `blur` event that caused this function to be called.
  15367. *
  15368. * @listens blur
  15369. */
  15370. handleBlur(event) {
  15371. const relatedTarget = event.relatedTarget || document.activeElement;
  15372. // Close menu popup when a user clicks outside the menu
  15373. if (!this.children().some(element => {
  15374. return element.el() === relatedTarget;
  15375. })) {
  15376. const btn = this.menuButton_;
  15377. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  15378. btn.unpressButton();
  15379. }
  15380. }
  15381. }
  15382. /**
  15383. * Called when a `MenuItem` gets clicked or tapped.
  15384. *
  15385. * @param {Event} event
  15386. * The `click` or `tap` event that caused this function to be called.
  15387. *
  15388. * @listens click,tap
  15389. */
  15390. handleTapClick(event) {
  15391. // Unpress the associated MenuButton, and move focus back to it
  15392. if (this.menuButton_) {
  15393. this.menuButton_.unpressButton();
  15394. const childComponents = this.children();
  15395. if (!Array.isArray(childComponents)) {
  15396. return;
  15397. }
  15398. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  15399. if (!foundComponent) {
  15400. return;
  15401. }
  15402. // don't focus menu button if item is a caption settings item
  15403. // because focus will move elsewhere
  15404. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  15405. this.menuButton_.focus();
  15406. }
  15407. }
  15408. }
  15409. /**
  15410. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  15411. *
  15412. * @param {Event} event
  15413. * A `keydown` event that happened on the menu.
  15414. *
  15415. * @listens keydown
  15416. */
  15417. handleKeyDown(event) {
  15418. // Left and Down Arrows
  15419. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  15420. event.preventDefault();
  15421. event.stopPropagation();
  15422. this.stepForward();
  15423. // Up and Right Arrows
  15424. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  15425. event.preventDefault();
  15426. event.stopPropagation();
  15427. this.stepBack();
  15428. }
  15429. }
  15430. /**
  15431. * Move to next (lower) menu item for keyboard users.
  15432. */
  15433. stepForward() {
  15434. let stepChild = 0;
  15435. if (this.focusedChild_ !== undefined) {
  15436. stepChild = this.focusedChild_ + 1;
  15437. }
  15438. this.focus(stepChild);
  15439. }
  15440. /**
  15441. * Move to previous (higher) menu item for keyboard users.
  15442. */
  15443. stepBack() {
  15444. let stepChild = 0;
  15445. if (this.focusedChild_ !== undefined) {
  15446. stepChild = this.focusedChild_ - 1;
  15447. }
  15448. this.focus(stepChild);
  15449. }
  15450. /**
  15451. * Set focus on a {@link MenuItem} in the `Menu`.
  15452. *
  15453. * @param {Object|string} [item=0]
  15454. * Index of child item set focus on.
  15455. */
  15456. focus(item = 0) {
  15457. const children = this.children().slice();
  15458. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  15459. if (haveTitle) {
  15460. children.shift();
  15461. }
  15462. if (children.length > 0) {
  15463. if (item < 0) {
  15464. item = 0;
  15465. } else if (item >= children.length) {
  15466. item = children.length - 1;
  15467. }
  15468. this.focusedChild_ = item;
  15469. children[item].el_.focus();
  15470. }
  15471. }
  15472. }
  15473. Component.registerComponent('Menu', Menu);
  15474. /**
  15475. * @file menu-button.js
  15476. */
  15477. /**
  15478. * A `MenuButton` class for any popup {@link Menu}.
  15479. *
  15480. * @extends Component
  15481. */
  15482. class MenuButton extends Component {
  15483. /**
  15484. * Creates an instance of this class.
  15485. *
  15486. * @param { import('../player').default } player
  15487. * The `Player` that this class should be attached to.
  15488. *
  15489. * @param {Object} [options={}]
  15490. * The key/value store of player options.
  15491. */
  15492. constructor(player, options = {}) {
  15493. super(player, options);
  15494. this.menuButton_ = new Button(player, options);
  15495. this.menuButton_.controlText(this.controlText_);
  15496. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  15497. // Add buildCSSClass values to the button, not the wrapper
  15498. const buttonClass = Button.prototype.buildCSSClass();
  15499. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  15500. this.menuButton_.removeClass('vjs-control');
  15501. this.addChild(this.menuButton_);
  15502. this.update();
  15503. this.enabled_ = true;
  15504. const handleClick = e => this.handleClick(e);
  15505. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  15506. this.on(this.menuButton_, 'tap', handleClick);
  15507. this.on(this.menuButton_, 'click', handleClick);
  15508. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  15509. this.on(this.menuButton_, 'mouseenter', () => {
  15510. this.addClass('vjs-hover');
  15511. this.menu.show();
  15512. on(document, 'keyup', this.handleMenuKeyUp_);
  15513. });
  15514. this.on('mouseleave', e => this.handleMouseLeave(e));
  15515. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  15516. }
  15517. /**
  15518. * Update the menu based on the current state of its items.
  15519. */
  15520. update() {
  15521. const menu = this.createMenu();
  15522. if (this.menu) {
  15523. this.menu.dispose();
  15524. this.removeChild(this.menu);
  15525. }
  15526. this.menu = menu;
  15527. this.addChild(menu);
  15528. /**
  15529. * Track the state of the menu button
  15530. *
  15531. * @type {Boolean}
  15532. * @private
  15533. */
  15534. this.buttonPressed_ = false;
  15535. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15536. if (this.items && this.items.length <= this.hideThreshold_) {
  15537. this.hide();
  15538. this.menu.contentEl_.removeAttribute('role');
  15539. } else {
  15540. this.show();
  15541. this.menu.contentEl_.setAttribute('role', 'menu');
  15542. }
  15543. }
  15544. /**
  15545. * Create the menu and add all items to it.
  15546. *
  15547. * @return {Menu}
  15548. * The constructed menu
  15549. */
  15550. createMenu() {
  15551. const menu = new Menu(this.player_, {
  15552. menuButton: this
  15553. });
  15554. /**
  15555. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  15556. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  15557. * it here because every time we run `createMenu` we need to reset the value.
  15558. *
  15559. * @protected
  15560. * @type {Number}
  15561. */
  15562. this.hideThreshold_ = 0;
  15563. // Add a title list item to the top
  15564. if (this.options_.title) {
  15565. const titleEl = createEl('li', {
  15566. className: 'vjs-menu-title',
  15567. textContent: toTitleCase(this.options_.title),
  15568. tabIndex: -1
  15569. });
  15570. const titleComponent = new Component(this.player_, {
  15571. el: titleEl
  15572. });
  15573. menu.addItem(titleComponent);
  15574. }
  15575. this.items = this.createItems();
  15576. if (this.items) {
  15577. // Add menu items to the menu
  15578. for (let i = 0; i < this.items.length; i++) {
  15579. menu.addItem(this.items[i]);
  15580. }
  15581. }
  15582. return menu;
  15583. }
  15584. /**
  15585. * Create the list of menu items. Specific to each subclass.
  15586. *
  15587. * @abstract
  15588. */
  15589. createItems() {}
  15590. /**
  15591. * Create the `MenuButtons`s DOM element.
  15592. *
  15593. * @return {Element}
  15594. * The element that gets created.
  15595. */
  15596. createEl() {
  15597. return super.createEl('div', {
  15598. className: this.buildWrapperCSSClass()
  15599. }, {});
  15600. }
  15601. /**
  15602. * Allow sub components to stack CSS class names for the wrapper element
  15603. *
  15604. * @return {string}
  15605. * The constructed wrapper DOM `className`
  15606. */
  15607. buildWrapperCSSClass() {
  15608. let menuButtonClass = 'vjs-menu-button';
  15609. // If the inline option is passed, we want to use different styles altogether.
  15610. if (this.options_.inline === true) {
  15611. menuButtonClass += '-inline';
  15612. } else {
  15613. menuButtonClass += '-popup';
  15614. }
  15615. // TODO: Fix the CSS so that this isn't necessary
  15616. const buttonClass = Button.prototype.buildCSSClass();
  15617. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  15618. }
  15619. /**
  15620. * Builds the default DOM `className`.
  15621. *
  15622. * @return {string}
  15623. * The DOM `className` for this object.
  15624. */
  15625. buildCSSClass() {
  15626. let menuButtonClass = 'vjs-menu-button';
  15627. // If the inline option is passed, we want to use different styles altogether.
  15628. if (this.options_.inline === true) {
  15629. menuButtonClass += '-inline';
  15630. } else {
  15631. menuButtonClass += '-popup';
  15632. }
  15633. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  15634. }
  15635. /**
  15636. * Get or set the localized control text that will be used for accessibility.
  15637. *
  15638. * > NOTE: This will come from the internal `menuButton_` element.
  15639. *
  15640. * @param {string} [text]
  15641. * Control text for element.
  15642. *
  15643. * @param {Element} [el=this.menuButton_.el()]
  15644. * Element to set the title on.
  15645. *
  15646. * @return {string}
  15647. * - The control text when getting
  15648. */
  15649. controlText(text, el = this.menuButton_.el()) {
  15650. return this.menuButton_.controlText(text, el);
  15651. }
  15652. /**
  15653. * Dispose of the `menu-button` and all child components.
  15654. */
  15655. dispose() {
  15656. this.handleMouseLeave();
  15657. super.dispose();
  15658. }
  15659. /**
  15660. * Handle a click on a `MenuButton`.
  15661. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15662. *
  15663. * @param {Event} event
  15664. * The `keydown`, `tap`, or `click` event that caused this function to be
  15665. * called.
  15666. *
  15667. * @listens tap
  15668. * @listens click
  15669. */
  15670. handleClick(event) {
  15671. if (this.buttonPressed_) {
  15672. this.unpressButton();
  15673. } else {
  15674. this.pressButton();
  15675. }
  15676. }
  15677. /**
  15678. * Handle `mouseleave` for `MenuButton`.
  15679. *
  15680. * @param {Event} event
  15681. * The `mouseleave` event that caused this function to be called.
  15682. *
  15683. * @listens mouseleave
  15684. */
  15685. handleMouseLeave(event) {
  15686. this.removeClass('vjs-hover');
  15687. off(document, 'keyup', this.handleMenuKeyUp_);
  15688. }
  15689. /**
  15690. * Set the focus to the actual button, not to this element
  15691. */
  15692. focus() {
  15693. this.menuButton_.focus();
  15694. }
  15695. /**
  15696. * Remove the focus from the actual button, not this element
  15697. */
  15698. blur() {
  15699. this.menuButton_.blur();
  15700. }
  15701. /**
  15702. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  15703. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15704. *
  15705. * @param {Event} event
  15706. * The `keydown` event that caused this function to be called.
  15707. *
  15708. * @listens keydown
  15709. */
  15710. handleKeyDown(event) {
  15711. // Escape or Tab unpress the 'button'
  15712. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15713. if (this.buttonPressed_) {
  15714. this.unpressButton();
  15715. }
  15716. // Don't preventDefault for Tab key - we still want to lose focus
  15717. if (!keycode.isEventKey(event, 'Tab')) {
  15718. event.preventDefault();
  15719. // Set focus back to the menu button's button
  15720. this.menuButton_.focus();
  15721. }
  15722. // Up Arrow or Down Arrow also 'press' the button to open the menu
  15723. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  15724. if (!this.buttonPressed_) {
  15725. event.preventDefault();
  15726. this.pressButton();
  15727. }
  15728. }
  15729. }
  15730. /**
  15731. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  15732. * the constructor.
  15733. *
  15734. * @param {Event} event
  15735. * Key press event
  15736. *
  15737. * @listens keyup
  15738. */
  15739. handleMenuKeyUp(event) {
  15740. // Escape hides popup menu
  15741. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15742. this.removeClass('vjs-hover');
  15743. }
  15744. }
  15745. /**
  15746. * This method name now delegates to `handleSubmenuKeyDown`. This means
  15747. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  15748. * stop working.
  15749. *
  15750. * @param {Event} event
  15751. * The event that caused this function to be called.
  15752. */
  15753. handleSubmenuKeyPress(event) {
  15754. this.handleSubmenuKeyDown(event);
  15755. }
  15756. /**
  15757. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  15758. * the constructor.
  15759. *
  15760. * @param {Event} event
  15761. * Key press event
  15762. *
  15763. * @listens keydown
  15764. */
  15765. handleSubmenuKeyDown(event) {
  15766. // Escape or Tab unpress the 'button'
  15767. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15768. if (this.buttonPressed_) {
  15769. this.unpressButton();
  15770. }
  15771. // Don't preventDefault for Tab key - we still want to lose focus
  15772. if (!keycode.isEventKey(event, 'Tab')) {
  15773. event.preventDefault();
  15774. // Set focus back to the menu button's button
  15775. this.menuButton_.focus();
  15776. }
  15777. }
  15778. }
  15779. /**
  15780. * Put the current `MenuButton` into a pressed state.
  15781. */
  15782. pressButton() {
  15783. if (this.enabled_) {
  15784. this.buttonPressed_ = true;
  15785. this.menu.show();
  15786. this.menu.lockShowing();
  15787. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  15788. // set the focus into the submenu, except on iOS where it is resulting in
  15789. // undesired scrolling behavior when the player is in an iframe
  15790. if (IS_IOS && isInFrame()) {
  15791. // Return early so that the menu isn't focused
  15792. return;
  15793. }
  15794. this.menu.focus();
  15795. }
  15796. }
  15797. /**
  15798. * Take the current `MenuButton` out of a pressed state.
  15799. */
  15800. unpressButton() {
  15801. if (this.enabled_) {
  15802. this.buttonPressed_ = false;
  15803. this.menu.unlockShowing();
  15804. this.menu.hide();
  15805. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15806. }
  15807. }
  15808. /**
  15809. * Disable the `MenuButton`. Don't allow it to be clicked.
  15810. */
  15811. disable() {
  15812. this.unpressButton();
  15813. this.enabled_ = false;
  15814. this.addClass('vjs-disabled');
  15815. this.menuButton_.disable();
  15816. }
  15817. /**
  15818. * Enable the `MenuButton`. Allow it to be clicked.
  15819. */
  15820. enable() {
  15821. this.enabled_ = true;
  15822. this.removeClass('vjs-disabled');
  15823. this.menuButton_.enable();
  15824. }
  15825. }
  15826. Component.registerComponent('MenuButton', MenuButton);
  15827. /**
  15828. * @file track-button.js
  15829. */
  15830. /**
  15831. * The base class for buttons that toggle specific track types (e.g. subtitles).
  15832. *
  15833. * @extends MenuButton
  15834. */
  15835. class TrackButton extends MenuButton {
  15836. /**
  15837. * Creates an instance of this class.
  15838. *
  15839. * @param { import('./player').default } player
  15840. * The `Player` that this class should be attached to.
  15841. *
  15842. * @param {Object} [options]
  15843. * The key/value store of player options.
  15844. */
  15845. constructor(player, options) {
  15846. const tracks = options.tracks;
  15847. super(player, options);
  15848. if (this.items.length <= 1) {
  15849. this.hide();
  15850. }
  15851. if (!tracks) {
  15852. return;
  15853. }
  15854. const updateHandler = bind_(this, this.update);
  15855. tracks.addEventListener('removetrack', updateHandler);
  15856. tracks.addEventListener('addtrack', updateHandler);
  15857. tracks.addEventListener('labelchange', updateHandler);
  15858. this.player_.on('ready', updateHandler);
  15859. this.player_.on('dispose', function () {
  15860. tracks.removeEventListener('removetrack', updateHandler);
  15861. tracks.removeEventListener('addtrack', updateHandler);
  15862. tracks.removeEventListener('labelchange', updateHandler);
  15863. });
  15864. }
  15865. }
  15866. Component.registerComponent('TrackButton', TrackButton);
  15867. /**
  15868. * @file menu-keys.js
  15869. */
  15870. /**
  15871. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  15872. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  15873. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  15874. *
  15875. * @typedef MenuKeys
  15876. * @array
  15877. */
  15878. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  15879. /**
  15880. * @file menu-item.js
  15881. */
  15882. /**
  15883. * The component for a menu item. `<li>`
  15884. *
  15885. * @extends ClickableComponent
  15886. */
  15887. class MenuItem extends ClickableComponent {
  15888. /**
  15889. * Creates an instance of the this class.
  15890. *
  15891. * @param { import('../player').default } player
  15892. * The `Player` that this class should be attached to.
  15893. *
  15894. * @param {Object} [options={}]
  15895. * The key/value store of player options.
  15896. *
  15897. */
  15898. constructor(player, options) {
  15899. super(player, options);
  15900. this.selectable = options.selectable;
  15901. this.isSelected_ = options.selected || false;
  15902. this.multiSelectable = options.multiSelectable;
  15903. this.selected(this.isSelected_);
  15904. if (this.selectable) {
  15905. if (this.multiSelectable) {
  15906. this.el_.setAttribute('role', 'menuitemcheckbox');
  15907. } else {
  15908. this.el_.setAttribute('role', 'menuitemradio');
  15909. }
  15910. } else {
  15911. this.el_.setAttribute('role', 'menuitem');
  15912. }
  15913. }
  15914. /**
  15915. * Create the `MenuItem's DOM element
  15916. *
  15917. * @param {string} [type=li]
  15918. * Element's node type, not actually used, always set to `li`.
  15919. *
  15920. * @param {Object} [props={}]
  15921. * An object of properties that should be set on the element
  15922. *
  15923. * @param {Object} [attrs={}]
  15924. * An object of attributes that should be set on the element
  15925. *
  15926. * @return {Element}
  15927. * The element that gets created.
  15928. */
  15929. createEl(type, props, attrs) {
  15930. // The control is textual, not just an icon
  15931. this.nonIconControl = true;
  15932. const el = super.createEl('li', Object.assign({
  15933. className: 'vjs-menu-item',
  15934. tabIndex: -1
  15935. }, props), attrs);
  15936. // swap icon with menu item text.
  15937. el.replaceChild(createEl('span', {
  15938. className: 'vjs-menu-item-text',
  15939. textContent: this.localize(this.options_.label)
  15940. }), el.querySelector('.vjs-icon-placeholder'));
  15941. return el;
  15942. }
  15943. /**
  15944. * Ignore keys which are used by the menu, but pass any other ones up. See
  15945. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15946. *
  15947. * @param {Event} event
  15948. * The `keydown` event that caused this function to be called.
  15949. *
  15950. * @listens keydown
  15951. */
  15952. handleKeyDown(event) {
  15953. if (!MenuKeys.some(key => keycode.isEventKey(event, key))) {
  15954. // Pass keydown handling up for unused keys
  15955. super.handleKeyDown(event);
  15956. }
  15957. }
  15958. /**
  15959. * Any click on a `MenuItem` puts it into the selected state.
  15960. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15961. *
  15962. * @param {Event} event
  15963. * The `keydown`, `tap`, or `click` event that caused this function to be
  15964. * called.
  15965. *
  15966. * @listens tap
  15967. * @listens click
  15968. */
  15969. handleClick(event) {
  15970. this.selected(true);
  15971. }
  15972. /**
  15973. * Set the state for this menu item as selected or not.
  15974. *
  15975. * @param {boolean} selected
  15976. * if the menu item is selected or not
  15977. */
  15978. selected(selected) {
  15979. if (this.selectable) {
  15980. if (selected) {
  15981. this.addClass('vjs-selected');
  15982. this.el_.setAttribute('aria-checked', 'true');
  15983. // aria-checked isn't fully supported by browsers/screen readers,
  15984. // so indicate selected state to screen reader in the control text.
  15985. this.controlText(', selected');
  15986. this.isSelected_ = true;
  15987. } else {
  15988. this.removeClass('vjs-selected');
  15989. this.el_.setAttribute('aria-checked', 'false');
  15990. // Indicate un-selected state to screen reader
  15991. this.controlText('');
  15992. this.isSelected_ = false;
  15993. }
  15994. }
  15995. }
  15996. }
  15997. Component.registerComponent('MenuItem', MenuItem);
  15998. /**
  15999. * @file text-track-menu-item.js
  16000. */
  16001. /**
  16002. * The specific menu item type for selecting a language within a text track kind
  16003. *
  16004. * @extends MenuItem
  16005. */
  16006. class TextTrackMenuItem extends MenuItem {
  16007. /**
  16008. * Creates an instance of this class.
  16009. *
  16010. * @param { import('../../player').default } player
  16011. * The `Player` that this class should be attached to.
  16012. *
  16013. * @param {Object} [options]
  16014. * The key/value store of player options.
  16015. */
  16016. constructor(player, options) {
  16017. const track = options.track;
  16018. const tracks = player.textTracks();
  16019. // Modify options for parent MenuItem class's init.
  16020. options.label = track.label || track.language || 'Unknown';
  16021. options.selected = track.mode === 'showing';
  16022. super(player, options);
  16023. this.track = track;
  16024. // Determine the relevant kind(s) of tracks for this component and filter
  16025. // out empty kinds.
  16026. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  16027. const changeHandler = (...args) => {
  16028. this.handleTracksChange.apply(this, args);
  16029. };
  16030. const selectedLanguageChangeHandler = (...args) => {
  16031. this.handleSelectedLanguageChange.apply(this, args);
  16032. };
  16033. player.on(['loadstart', 'texttrackchange'], changeHandler);
  16034. tracks.addEventListener('change', changeHandler);
  16035. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16036. this.on('dispose', function () {
  16037. player.off(['loadstart', 'texttrackchange'], changeHandler);
  16038. tracks.removeEventListener('change', changeHandler);
  16039. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16040. });
  16041. // iOS7 doesn't dispatch change events to TextTrackLists when an
  16042. // associated track's mode changes. Without something like
  16043. // Object.observe() (also not present on iOS7), it's not
  16044. // possible to detect changes to the mode attribute and polyfill
  16045. // the change event. As a poor substitute, we manually dispatch
  16046. // change events whenever the controls modify the mode.
  16047. if (tracks.onchange === undefined) {
  16048. let event;
  16049. this.on(['tap', 'click'], function () {
  16050. if (typeof window.Event !== 'object') {
  16051. // Android 2.3 throws an Illegal Constructor error for window.Event
  16052. try {
  16053. event = new window.Event('change');
  16054. } catch (err) {
  16055. // continue regardless of error
  16056. }
  16057. }
  16058. if (!event) {
  16059. event = document.createEvent('Event');
  16060. event.initEvent('change', true, true);
  16061. }
  16062. tracks.dispatchEvent(event);
  16063. });
  16064. }
  16065. // set the default state based on current tracks
  16066. this.handleTracksChange();
  16067. }
  16068. /**
  16069. * This gets called when an `TextTrackMenuItem` is "clicked". See
  16070. * {@link ClickableComponent} for more detailed information on what a click can be.
  16071. *
  16072. * @param {Event} event
  16073. * The `keydown`, `tap`, or `click` event that caused this function to be
  16074. * called.
  16075. *
  16076. * @listens tap
  16077. * @listens click
  16078. */
  16079. handleClick(event) {
  16080. const referenceTrack = this.track;
  16081. const tracks = this.player_.textTracks();
  16082. super.handleClick(event);
  16083. if (!tracks) {
  16084. return;
  16085. }
  16086. for (let i = 0; i < tracks.length; i++) {
  16087. const track = tracks[i];
  16088. // If the track from the text tracks list is not of the right kind,
  16089. // skip it. We do not want to affect tracks of incompatible kind(s).
  16090. if (this.kinds.indexOf(track.kind) === -1) {
  16091. continue;
  16092. }
  16093. // If this text track is the component's track and it is not showing,
  16094. // set it to showing.
  16095. if (track === referenceTrack) {
  16096. if (track.mode !== 'showing') {
  16097. track.mode = 'showing';
  16098. }
  16099. // If this text track is not the component's track and it is not
  16100. // disabled, set it to disabled.
  16101. } else if (track.mode !== 'disabled') {
  16102. track.mode = 'disabled';
  16103. }
  16104. }
  16105. }
  16106. /**
  16107. * Handle text track list change
  16108. *
  16109. * @param {Event} event
  16110. * The `change` event that caused this function to be called.
  16111. *
  16112. * @listens TextTrackList#change
  16113. */
  16114. handleTracksChange(event) {
  16115. const shouldBeSelected = this.track.mode === 'showing';
  16116. // Prevent redundant selected() calls because they may cause
  16117. // screen readers to read the appended control text unnecessarily
  16118. if (shouldBeSelected !== this.isSelected_) {
  16119. this.selected(shouldBeSelected);
  16120. }
  16121. }
  16122. handleSelectedLanguageChange(event) {
  16123. if (this.track.mode === 'showing') {
  16124. const selectedLanguage = this.player_.cache_.selectedLanguage;
  16125. // Don't replace the kind of track across the same language
  16126. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  16127. return;
  16128. }
  16129. this.player_.cache_.selectedLanguage = {
  16130. enabled: true,
  16131. language: this.track.language,
  16132. kind: this.track.kind
  16133. };
  16134. }
  16135. }
  16136. dispose() {
  16137. // remove reference to track object on dispose
  16138. this.track = null;
  16139. super.dispose();
  16140. }
  16141. }
  16142. Component.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  16143. /**
  16144. * @file off-text-track-menu-item.js
  16145. */
  16146. /**
  16147. * A special menu item for turning of a specific type of text track
  16148. *
  16149. * @extends TextTrackMenuItem
  16150. */
  16151. class OffTextTrackMenuItem extends TextTrackMenuItem {
  16152. /**
  16153. * Creates an instance of this class.
  16154. *
  16155. * @param { import('../../player').default } player
  16156. * The `Player` that this class should be attached to.
  16157. *
  16158. * @param {Object} [options]
  16159. * The key/value store of player options.
  16160. */
  16161. constructor(player, options) {
  16162. // Create pseudo track info
  16163. // Requires options['kind']
  16164. options.track = {
  16165. player,
  16166. // it is no longer necessary to store `kind` or `kinds` on the track itself
  16167. // since they are now stored in the `kinds` property of all instances of
  16168. // TextTrackMenuItem, but this will remain for backwards compatibility
  16169. kind: options.kind,
  16170. kinds: options.kinds,
  16171. default: false,
  16172. mode: 'disabled'
  16173. };
  16174. if (!options.kinds) {
  16175. options.kinds = [options.kind];
  16176. }
  16177. if (options.label) {
  16178. options.track.label = options.label;
  16179. } else {
  16180. options.track.label = options.kinds.join(' and ') + ' off';
  16181. }
  16182. // MenuItem is selectable
  16183. options.selectable = true;
  16184. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16185. options.multiSelectable = false;
  16186. super(player, options);
  16187. }
  16188. /**
  16189. * Handle text track change
  16190. *
  16191. * @param {Event} event
  16192. * The event that caused this function to run
  16193. */
  16194. handleTracksChange(event) {
  16195. const tracks = this.player().textTracks();
  16196. let shouldBeSelected = true;
  16197. for (let i = 0, l = tracks.length; i < l; i++) {
  16198. const track = tracks[i];
  16199. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  16200. shouldBeSelected = false;
  16201. break;
  16202. }
  16203. }
  16204. // Prevent redundant selected() calls because they may cause
  16205. // screen readers to read the appended control text unnecessarily
  16206. if (shouldBeSelected !== this.isSelected_) {
  16207. this.selected(shouldBeSelected);
  16208. }
  16209. }
  16210. handleSelectedLanguageChange(event) {
  16211. const tracks = this.player().textTracks();
  16212. let allHidden = true;
  16213. for (let i = 0, l = tracks.length; i < l; i++) {
  16214. const track = tracks[i];
  16215. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  16216. allHidden = false;
  16217. break;
  16218. }
  16219. }
  16220. if (allHidden) {
  16221. this.player_.cache_.selectedLanguage = {
  16222. enabled: false
  16223. };
  16224. }
  16225. }
  16226. /**
  16227. * Update control text and label on languagechange
  16228. */
  16229. handleLanguagechange() {
  16230. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  16231. super.handleLanguagechange();
  16232. }
  16233. }
  16234. Component.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  16235. /**
  16236. * @file text-track-button.js
  16237. */
  16238. /**
  16239. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  16240. *
  16241. * @extends MenuButton
  16242. */
  16243. class TextTrackButton extends TrackButton {
  16244. /**
  16245. * Creates an instance of this class.
  16246. *
  16247. * @param { import('../../player').default } player
  16248. * The `Player` that this class should be attached to.
  16249. *
  16250. * @param {Object} [options={}]
  16251. * The key/value store of player options.
  16252. */
  16253. constructor(player, options = {}) {
  16254. options.tracks = player.textTracks();
  16255. super(player, options);
  16256. }
  16257. /**
  16258. * Create a menu item for each text track
  16259. *
  16260. * @param {TextTrackMenuItem[]} [items=[]]
  16261. * Existing array of items to use during creation
  16262. *
  16263. * @return {TextTrackMenuItem[]}
  16264. * Array of menu items that were created
  16265. */
  16266. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  16267. // Label is an override for the [track] off label
  16268. // USed to localise captions/subtitles
  16269. let label;
  16270. if (this.label_) {
  16271. label = `${this.label_} off`;
  16272. }
  16273. // Add an OFF menu item to turn all tracks off
  16274. items.push(new OffTextTrackMenuItem(this.player_, {
  16275. kinds: this.kinds_,
  16276. kind: this.kind_,
  16277. label
  16278. }));
  16279. this.hideThreshold_ += 1;
  16280. const tracks = this.player_.textTracks();
  16281. if (!Array.isArray(this.kinds_)) {
  16282. this.kinds_ = [this.kind_];
  16283. }
  16284. for (let i = 0; i < tracks.length; i++) {
  16285. const track = tracks[i];
  16286. // only add tracks that are of an appropriate kind and have a label
  16287. if (this.kinds_.indexOf(track.kind) > -1) {
  16288. const item = new TrackMenuItem(this.player_, {
  16289. track,
  16290. kinds: this.kinds_,
  16291. kind: this.kind_,
  16292. // MenuItem is selectable
  16293. selectable: true,
  16294. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16295. multiSelectable: false
  16296. });
  16297. item.addClass(`vjs-${track.kind}-menu-item`);
  16298. items.push(item);
  16299. }
  16300. }
  16301. return items;
  16302. }
  16303. }
  16304. Component.registerComponent('TextTrackButton', TextTrackButton);
  16305. /**
  16306. * @file chapters-track-menu-item.js
  16307. */
  16308. /**
  16309. * The chapter track menu item
  16310. *
  16311. * @extends MenuItem
  16312. */
  16313. class ChaptersTrackMenuItem extends MenuItem {
  16314. /**
  16315. * Creates an instance of this class.
  16316. *
  16317. * @param { import('../../player').default } player
  16318. * The `Player` that this class should be attached to.
  16319. *
  16320. * @param {Object} [options]
  16321. * The key/value store of player options.
  16322. */
  16323. constructor(player, options) {
  16324. const track = options.track;
  16325. const cue = options.cue;
  16326. const currentTime = player.currentTime();
  16327. // Modify options for parent MenuItem class's init.
  16328. options.selectable = true;
  16329. options.multiSelectable = false;
  16330. options.label = cue.text;
  16331. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  16332. super(player, options);
  16333. this.track = track;
  16334. this.cue = cue;
  16335. }
  16336. /**
  16337. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  16338. * {@link ClickableComponent} for more detailed information on what a click can be.
  16339. *
  16340. * @param {Event} [event]
  16341. * The `keydown`, `tap`, or `click` event that caused this function to be
  16342. * called.
  16343. *
  16344. * @listens tap
  16345. * @listens click
  16346. */
  16347. handleClick(event) {
  16348. super.handleClick();
  16349. this.player_.currentTime(this.cue.startTime);
  16350. }
  16351. }
  16352. Component.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  16353. /**
  16354. * @file chapters-button.js
  16355. */
  16356. /**
  16357. * The button component for toggling and selecting chapters
  16358. * Chapters act much differently than other text tracks
  16359. * Cues are navigation vs. other tracks of alternative languages
  16360. *
  16361. * @extends TextTrackButton
  16362. */
  16363. class ChaptersButton extends TextTrackButton {
  16364. /**
  16365. * Creates an instance of this class.
  16366. *
  16367. * @param { import('../../player').default } player
  16368. * The `Player` that this class should be attached to.
  16369. *
  16370. * @param {Object} [options]
  16371. * The key/value store of player options.
  16372. *
  16373. * @param {Function} [ready]
  16374. * The function to call when this function is ready.
  16375. */
  16376. constructor(player, options, ready) {
  16377. super(player, options, ready);
  16378. this.selectCurrentItem_ = () => {
  16379. this.items.forEach(item => {
  16380. item.selected(this.track_.activeCues[0] === item.cue);
  16381. });
  16382. };
  16383. }
  16384. /**
  16385. * Builds the default DOM `className`.
  16386. *
  16387. * @return {string}
  16388. * The DOM `className` for this object.
  16389. */
  16390. buildCSSClass() {
  16391. return `vjs-chapters-button ${super.buildCSSClass()}`;
  16392. }
  16393. buildWrapperCSSClass() {
  16394. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  16395. }
  16396. /**
  16397. * Update the menu based on the current state of its items.
  16398. *
  16399. * @param {Event} [event]
  16400. * An event that triggered this function to run.
  16401. *
  16402. * @listens TextTrackList#addtrack
  16403. * @listens TextTrackList#removetrack
  16404. * @listens TextTrackList#change
  16405. */
  16406. update(event) {
  16407. if (event && event.track && event.track.kind !== 'chapters') {
  16408. return;
  16409. }
  16410. const track = this.findChaptersTrack();
  16411. if (track !== this.track_) {
  16412. this.setTrack(track);
  16413. super.update();
  16414. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  16415. // Update the menu initially or if the number of cues has changed since set
  16416. super.update();
  16417. }
  16418. }
  16419. /**
  16420. * Set the currently selected track for the chapters button.
  16421. *
  16422. * @param {TextTrack} track
  16423. * The new track to select. Nothing will change if this is the currently selected
  16424. * track.
  16425. */
  16426. setTrack(track) {
  16427. if (this.track_ === track) {
  16428. return;
  16429. }
  16430. if (!this.updateHandler_) {
  16431. this.updateHandler_ = this.update.bind(this);
  16432. }
  16433. // here this.track_ refers to the old track instance
  16434. if (this.track_) {
  16435. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16436. if (remoteTextTrackEl) {
  16437. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  16438. }
  16439. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  16440. this.track_ = null;
  16441. }
  16442. this.track_ = track;
  16443. // here this.track_ refers to the new track instance
  16444. if (this.track_) {
  16445. this.track_.mode = 'hidden';
  16446. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16447. if (remoteTextTrackEl) {
  16448. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  16449. }
  16450. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  16451. }
  16452. }
  16453. /**
  16454. * Find the track object that is currently in use by this ChaptersButton
  16455. *
  16456. * @return {TextTrack|undefined}
  16457. * The current track or undefined if none was found.
  16458. */
  16459. findChaptersTrack() {
  16460. const tracks = this.player_.textTracks() || [];
  16461. for (let i = tracks.length - 1; i >= 0; i--) {
  16462. // We will always choose the last track as our chaptersTrack
  16463. const track = tracks[i];
  16464. if (track.kind === this.kind_) {
  16465. return track;
  16466. }
  16467. }
  16468. }
  16469. /**
  16470. * Get the caption for the ChaptersButton based on the track label. This will also
  16471. * use the current tracks localized kind as a fallback if a label does not exist.
  16472. *
  16473. * @return {string}
  16474. * The tracks current label or the localized track kind.
  16475. */
  16476. getMenuCaption() {
  16477. if (this.track_ && this.track_.label) {
  16478. return this.track_.label;
  16479. }
  16480. return this.localize(toTitleCase(this.kind_));
  16481. }
  16482. /**
  16483. * Create menu from chapter track
  16484. *
  16485. * @return { import('../../menu/menu').default }
  16486. * New menu for the chapter buttons
  16487. */
  16488. createMenu() {
  16489. this.options_.title = this.getMenuCaption();
  16490. return super.createMenu();
  16491. }
  16492. /**
  16493. * Create a menu item for each text track
  16494. *
  16495. * @return { import('./text-track-menu-item').default[] }
  16496. * Array of menu items
  16497. */
  16498. createItems() {
  16499. const items = [];
  16500. if (!this.track_) {
  16501. return items;
  16502. }
  16503. const cues = this.track_.cues;
  16504. if (!cues) {
  16505. return items;
  16506. }
  16507. for (let i = 0, l = cues.length; i < l; i++) {
  16508. const cue = cues[i];
  16509. const mi = new ChaptersTrackMenuItem(this.player_, {
  16510. track: this.track_,
  16511. cue
  16512. });
  16513. items.push(mi);
  16514. }
  16515. return items;
  16516. }
  16517. }
  16518. /**
  16519. * `kind` of TextTrack to look for to associate it with this menu.
  16520. *
  16521. * @type {string}
  16522. * @private
  16523. */
  16524. ChaptersButton.prototype.kind_ = 'chapters';
  16525. /**
  16526. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  16527. *
  16528. * @type {string}
  16529. * @protected
  16530. */
  16531. ChaptersButton.prototype.controlText_ = 'Chapters';
  16532. Component.registerComponent('ChaptersButton', ChaptersButton);
  16533. /**
  16534. * @file descriptions-button.js
  16535. */
  16536. /**
  16537. * The button component for toggling and selecting descriptions
  16538. *
  16539. * @extends TextTrackButton
  16540. */
  16541. class DescriptionsButton extends TextTrackButton {
  16542. /**
  16543. * Creates an instance of this class.
  16544. *
  16545. * @param { import('../../player').default } player
  16546. * The `Player` that this class should be attached to.
  16547. *
  16548. * @param {Object} [options]
  16549. * The key/value store of player options.
  16550. *
  16551. * @param {Function} [ready]
  16552. * The function to call when this component is ready.
  16553. */
  16554. constructor(player, options, ready) {
  16555. super(player, options, ready);
  16556. const tracks = player.textTracks();
  16557. const changeHandler = bind_(this, this.handleTracksChange);
  16558. tracks.addEventListener('change', changeHandler);
  16559. this.on('dispose', function () {
  16560. tracks.removeEventListener('change', changeHandler);
  16561. });
  16562. }
  16563. /**
  16564. * Handle text track change
  16565. *
  16566. * @param {Event} event
  16567. * The event that caused this function to run
  16568. *
  16569. * @listens TextTrackList#change
  16570. */
  16571. handleTracksChange(event) {
  16572. const tracks = this.player().textTracks();
  16573. let disabled = false;
  16574. // Check whether a track of a different kind is showing
  16575. for (let i = 0, l = tracks.length; i < l; i++) {
  16576. const track = tracks[i];
  16577. if (track.kind !== this.kind_ && track.mode === 'showing') {
  16578. disabled = true;
  16579. break;
  16580. }
  16581. }
  16582. // If another track is showing, disable this menu button
  16583. if (disabled) {
  16584. this.disable();
  16585. } else {
  16586. this.enable();
  16587. }
  16588. }
  16589. /**
  16590. * Builds the default DOM `className`.
  16591. *
  16592. * @return {string}
  16593. * The DOM `className` for this object.
  16594. */
  16595. buildCSSClass() {
  16596. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  16597. }
  16598. buildWrapperCSSClass() {
  16599. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  16600. }
  16601. }
  16602. /**
  16603. * `kind` of TextTrack to look for to associate it with this menu.
  16604. *
  16605. * @type {string}
  16606. * @private
  16607. */
  16608. DescriptionsButton.prototype.kind_ = 'descriptions';
  16609. /**
  16610. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  16611. *
  16612. * @type {string}
  16613. * @protected
  16614. */
  16615. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  16616. Component.registerComponent('DescriptionsButton', DescriptionsButton);
  16617. /**
  16618. * @file subtitles-button.js
  16619. */
  16620. /**
  16621. * The button component for toggling and selecting subtitles
  16622. *
  16623. * @extends TextTrackButton
  16624. */
  16625. class SubtitlesButton extends TextTrackButton {
  16626. /**
  16627. * Creates an instance of this class.
  16628. *
  16629. * @param { import('../../player').default } player
  16630. * The `Player` that this class should be attached to.
  16631. *
  16632. * @param {Object} [options]
  16633. * The key/value store of player options.
  16634. *
  16635. * @param {Function} [ready]
  16636. * The function to call when this component is ready.
  16637. */
  16638. constructor(player, options, ready) {
  16639. super(player, options, ready);
  16640. }
  16641. /**
  16642. * Builds the default DOM `className`.
  16643. *
  16644. * @return {string}
  16645. * The DOM `className` for this object.
  16646. */
  16647. buildCSSClass() {
  16648. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  16649. }
  16650. buildWrapperCSSClass() {
  16651. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  16652. }
  16653. }
  16654. /**
  16655. * `kind` of TextTrack to look for to associate it with this menu.
  16656. *
  16657. * @type {string}
  16658. * @private
  16659. */
  16660. SubtitlesButton.prototype.kind_ = 'subtitles';
  16661. /**
  16662. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  16663. *
  16664. * @type {string}
  16665. * @protected
  16666. */
  16667. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  16668. Component.registerComponent('SubtitlesButton', SubtitlesButton);
  16669. /**
  16670. * @file caption-settings-menu-item.js
  16671. */
  16672. /**
  16673. * The menu item for caption track settings menu
  16674. *
  16675. * @extends TextTrackMenuItem
  16676. */
  16677. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  16678. /**
  16679. * Creates an instance of this class.
  16680. *
  16681. * @param { import('../../player').default } player
  16682. * The `Player` that this class should be attached to.
  16683. *
  16684. * @param {Object} [options]
  16685. * The key/value store of player options.
  16686. */
  16687. constructor(player, options) {
  16688. options.track = {
  16689. player,
  16690. kind: options.kind,
  16691. label: options.kind + ' settings',
  16692. selectable: false,
  16693. default: false,
  16694. mode: 'disabled'
  16695. };
  16696. // CaptionSettingsMenuItem has no concept of 'selected'
  16697. options.selectable = false;
  16698. options.name = 'CaptionSettingsMenuItem';
  16699. super(player, options);
  16700. this.addClass('vjs-texttrack-settings');
  16701. this.controlText(', opens ' + options.kind + ' settings dialog');
  16702. }
  16703. /**
  16704. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  16705. * {@link ClickableComponent} for more detailed information on what a click can be.
  16706. *
  16707. * @param {Event} [event]
  16708. * The `keydown`, `tap`, or `click` event that caused this function to be
  16709. * called.
  16710. *
  16711. * @listens tap
  16712. * @listens click
  16713. */
  16714. handleClick(event) {
  16715. this.player().getChild('textTrackSettings').open();
  16716. }
  16717. /**
  16718. * Update control text and label on languagechange
  16719. */
  16720. handleLanguagechange() {
  16721. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  16722. super.handleLanguagechange();
  16723. }
  16724. }
  16725. Component.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  16726. /**
  16727. * @file captions-button.js
  16728. */
  16729. /**
  16730. * The button component for toggling and selecting captions
  16731. *
  16732. * @extends TextTrackButton
  16733. */
  16734. class CaptionsButton extends TextTrackButton {
  16735. /**
  16736. * Creates an instance of this class.
  16737. *
  16738. * @param { import('../../player').default } player
  16739. * The `Player` that this class should be attached to.
  16740. *
  16741. * @param {Object} [options]
  16742. * The key/value store of player options.
  16743. *
  16744. * @param {Function} [ready]
  16745. * The function to call when this component is ready.
  16746. */
  16747. constructor(player, options, ready) {
  16748. super(player, options, ready);
  16749. }
  16750. /**
  16751. * Builds the default DOM `className`.
  16752. *
  16753. * @return {string}
  16754. * The DOM `className` for this object.
  16755. */
  16756. buildCSSClass() {
  16757. return `vjs-captions-button ${super.buildCSSClass()}`;
  16758. }
  16759. buildWrapperCSSClass() {
  16760. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  16761. }
  16762. /**
  16763. * Create caption menu items
  16764. *
  16765. * @return {CaptionSettingsMenuItem[]}
  16766. * The array of current menu items.
  16767. */
  16768. createItems() {
  16769. const items = [];
  16770. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16771. items.push(new CaptionSettingsMenuItem(this.player_, {
  16772. kind: this.kind_
  16773. }));
  16774. this.hideThreshold_ += 1;
  16775. }
  16776. return super.createItems(items);
  16777. }
  16778. }
  16779. /**
  16780. * `kind` of TextTrack to look for to associate it with this menu.
  16781. *
  16782. * @type {string}
  16783. * @private
  16784. */
  16785. CaptionsButton.prototype.kind_ = 'captions';
  16786. /**
  16787. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  16788. *
  16789. * @type {string}
  16790. * @protected
  16791. */
  16792. CaptionsButton.prototype.controlText_ = 'Captions';
  16793. Component.registerComponent('CaptionsButton', CaptionsButton);
  16794. /**
  16795. * @file subs-caps-menu-item.js
  16796. */
  16797. /**
  16798. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  16799. * in the SubsCapsMenu.
  16800. *
  16801. * @extends TextTrackMenuItem
  16802. */
  16803. class SubsCapsMenuItem extends TextTrackMenuItem {
  16804. createEl(type, props, attrs) {
  16805. const el = super.createEl(type, props, attrs);
  16806. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16807. if (this.options_.track.kind === 'captions') {
  16808. parentSpan.appendChild(createEl('span', {
  16809. className: 'vjs-icon-placeholder'
  16810. }, {
  16811. 'aria-hidden': true
  16812. }));
  16813. parentSpan.appendChild(createEl('span', {
  16814. className: 'vjs-control-text',
  16815. // space added as the text will visually flow with the
  16816. // label
  16817. textContent: ` ${this.localize('Captions')}`
  16818. }));
  16819. }
  16820. return el;
  16821. }
  16822. }
  16823. Component.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  16824. /**
  16825. * @file sub-caps-button.js
  16826. */
  16827. /**
  16828. * The button component for toggling and selecting captions and/or subtitles
  16829. *
  16830. * @extends TextTrackButton
  16831. */
  16832. class SubsCapsButton extends TextTrackButton {
  16833. /**
  16834. * Creates an instance of this class.
  16835. *
  16836. * @param { import('../../player').default } player
  16837. * The `Player` that this class should be attached to.
  16838. *
  16839. * @param {Object} [options]
  16840. * The key/value store of player options.
  16841. *
  16842. * @param {Function} [ready]
  16843. * The function to call when this component is ready.
  16844. */
  16845. constructor(player, options = {}) {
  16846. super(player, options);
  16847. // Although North America uses "captions" in most cases for
  16848. // "captions and subtitles" other locales use "subtitles"
  16849. this.label_ = 'subtitles';
  16850. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  16851. this.label_ = 'captions';
  16852. }
  16853. this.menuButton_.controlText(toTitleCase(this.label_));
  16854. }
  16855. /**
  16856. * Builds the default DOM `className`.
  16857. *
  16858. * @return {string}
  16859. * The DOM `className` for this object.
  16860. */
  16861. buildCSSClass() {
  16862. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  16863. }
  16864. buildWrapperCSSClass() {
  16865. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  16866. }
  16867. /**
  16868. * Create caption/subtitles menu items
  16869. *
  16870. * @return {CaptionSettingsMenuItem[]}
  16871. * The array of current menu items.
  16872. */
  16873. createItems() {
  16874. let items = [];
  16875. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  16876. items.push(new CaptionSettingsMenuItem(this.player_, {
  16877. kind: this.label_
  16878. }));
  16879. this.hideThreshold_ += 1;
  16880. }
  16881. items = super.createItems(items, SubsCapsMenuItem);
  16882. return items;
  16883. }
  16884. }
  16885. /**
  16886. * `kind`s of TextTrack to look for to associate it with this menu.
  16887. *
  16888. * @type {array}
  16889. * @private
  16890. */
  16891. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  16892. /**
  16893. * The text that should display over the `SubsCapsButton`s controls.
  16894. *
  16895. *
  16896. * @type {string}
  16897. * @protected
  16898. */
  16899. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  16900. Component.registerComponent('SubsCapsButton', SubsCapsButton);
  16901. /**
  16902. * @file audio-track-menu-item.js
  16903. */
  16904. /**
  16905. * An {@link AudioTrack} {@link MenuItem}
  16906. *
  16907. * @extends MenuItem
  16908. */
  16909. class AudioTrackMenuItem extends MenuItem {
  16910. /**
  16911. * Creates an instance of this class.
  16912. *
  16913. * @param { import('../../player').default } player
  16914. * The `Player` that this class should be attached to.
  16915. *
  16916. * @param {Object} [options]
  16917. * The key/value store of player options.
  16918. */
  16919. constructor(player, options) {
  16920. const track = options.track;
  16921. const tracks = player.audioTracks();
  16922. // Modify options for parent MenuItem class's init.
  16923. options.label = track.label || track.language || 'Unknown';
  16924. options.selected = track.enabled;
  16925. super(player, options);
  16926. this.track = track;
  16927. this.addClass(`vjs-${track.kind}-menu-item`);
  16928. const changeHandler = (...args) => {
  16929. this.handleTracksChange.apply(this, args);
  16930. };
  16931. tracks.addEventListener('change', changeHandler);
  16932. this.on('dispose', () => {
  16933. tracks.removeEventListener('change', changeHandler);
  16934. });
  16935. }
  16936. createEl(type, props, attrs) {
  16937. const el = super.createEl(type, props, attrs);
  16938. const parentSpan = el.querySelector('.vjs-menu-item-text');
  16939. if (this.options_.track.kind === 'main-desc') {
  16940. parentSpan.appendChild(createEl('span', {
  16941. className: 'vjs-icon-placeholder'
  16942. }, {
  16943. 'aria-hidden': true
  16944. }));
  16945. parentSpan.appendChild(createEl('span', {
  16946. className: 'vjs-control-text',
  16947. textContent: ' ' + this.localize('Descriptions')
  16948. }));
  16949. }
  16950. return el;
  16951. }
  16952. /**
  16953. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  16954. * for more detailed information on what a click can be.
  16955. *
  16956. * @param {Event} [event]
  16957. * The `keydown`, `tap`, or `click` event that caused this function to be
  16958. * called.
  16959. *
  16960. * @listens tap
  16961. * @listens click
  16962. */
  16963. handleClick(event) {
  16964. super.handleClick(event);
  16965. // the audio track list will automatically toggle other tracks
  16966. // off for us.
  16967. this.track.enabled = true;
  16968. // when native audio tracks are used, we want to make sure that other tracks are turned off
  16969. if (this.player_.tech_.featuresNativeAudioTracks) {
  16970. const tracks = this.player_.audioTracks();
  16971. for (let i = 0; i < tracks.length; i++) {
  16972. const track = tracks[i];
  16973. // skip the current track since we enabled it above
  16974. if (track === this.track) {
  16975. continue;
  16976. }
  16977. track.enabled = track === this.track;
  16978. }
  16979. }
  16980. }
  16981. /**
  16982. * Handle any {@link AudioTrack} change.
  16983. *
  16984. * @param {Event} [event]
  16985. * The {@link AudioTrackList#change} event that caused this to run.
  16986. *
  16987. * @listens AudioTrackList#change
  16988. */
  16989. handleTracksChange(event) {
  16990. this.selected(this.track.enabled);
  16991. }
  16992. }
  16993. Component.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  16994. /**
  16995. * @file audio-track-button.js
  16996. */
  16997. /**
  16998. * The base class for buttons that toggle specific {@link AudioTrack} types.
  16999. *
  17000. * @extends TrackButton
  17001. */
  17002. class AudioTrackButton extends TrackButton {
  17003. /**
  17004. * Creates an instance of this class.
  17005. *
  17006. * @param {Player} player
  17007. * The `Player` that this class should be attached to.
  17008. *
  17009. * @param {Object} [options={}]
  17010. * The key/value store of player options.
  17011. */
  17012. constructor(player, options = {}) {
  17013. options.tracks = player.audioTracks();
  17014. super(player, options);
  17015. }
  17016. /**
  17017. * Builds the default DOM `className`.
  17018. *
  17019. * @return {string}
  17020. * The DOM `className` for this object.
  17021. */
  17022. buildCSSClass() {
  17023. return `vjs-audio-button ${super.buildCSSClass()}`;
  17024. }
  17025. buildWrapperCSSClass() {
  17026. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  17027. }
  17028. /**
  17029. * Create a menu item for each audio track
  17030. *
  17031. * @param {AudioTrackMenuItem[]} [items=[]]
  17032. * An array of existing menu items to use.
  17033. *
  17034. * @return {AudioTrackMenuItem[]}
  17035. * An array of menu items
  17036. */
  17037. createItems(items = []) {
  17038. // if there's only one audio track, there no point in showing it
  17039. this.hideThreshold_ = 1;
  17040. const tracks = this.player_.audioTracks();
  17041. for (let i = 0; i < tracks.length; i++) {
  17042. const track = tracks[i];
  17043. items.push(new AudioTrackMenuItem(this.player_, {
  17044. track,
  17045. // MenuItem is selectable
  17046. selectable: true,
  17047. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  17048. multiSelectable: false
  17049. }));
  17050. }
  17051. return items;
  17052. }
  17053. }
  17054. /**
  17055. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  17056. *
  17057. * @type {string}
  17058. * @protected
  17059. */
  17060. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  17061. Component.registerComponent('AudioTrackButton', AudioTrackButton);
  17062. /**
  17063. * @file playback-rate-menu-item.js
  17064. */
  17065. /**
  17066. * The specific menu item type for selecting a playback rate.
  17067. *
  17068. * @extends MenuItem
  17069. */
  17070. class PlaybackRateMenuItem extends MenuItem {
  17071. /**
  17072. * Creates an instance of this class.
  17073. *
  17074. * @param { import('../../player').default } player
  17075. * The `Player` that this class should be attached to.
  17076. *
  17077. * @param {Object} [options]
  17078. * The key/value store of player options.
  17079. */
  17080. constructor(player, options) {
  17081. const label = options.rate;
  17082. const rate = parseFloat(label, 10);
  17083. // Modify options for parent MenuItem class's init.
  17084. options.label = label;
  17085. options.selected = rate === player.playbackRate();
  17086. options.selectable = true;
  17087. options.multiSelectable = false;
  17088. super(player, options);
  17089. this.label = label;
  17090. this.rate = rate;
  17091. this.on(player, 'ratechange', e => this.update(e));
  17092. }
  17093. /**
  17094. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  17095. * {@link ClickableComponent} for more detailed information on what a click can be.
  17096. *
  17097. * @param {Event} [event]
  17098. * The `keydown`, `tap`, or `click` event that caused this function to be
  17099. * called.
  17100. *
  17101. * @listens tap
  17102. * @listens click
  17103. */
  17104. handleClick(event) {
  17105. super.handleClick();
  17106. this.player().playbackRate(this.rate);
  17107. }
  17108. /**
  17109. * Update the PlaybackRateMenuItem when the playbackrate changes.
  17110. *
  17111. * @param {Event} [event]
  17112. * The `ratechange` event that caused this function to run.
  17113. *
  17114. * @listens Player#ratechange
  17115. */
  17116. update(event) {
  17117. this.selected(this.player().playbackRate() === this.rate);
  17118. }
  17119. }
  17120. /**
  17121. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  17122. *
  17123. * @type {string}
  17124. * @private
  17125. */
  17126. PlaybackRateMenuItem.prototype.contentElType = 'button';
  17127. Component.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  17128. /**
  17129. * @file playback-rate-menu-button.js
  17130. */
  17131. /**
  17132. * The component for controlling the playback rate.
  17133. *
  17134. * @extends MenuButton
  17135. */
  17136. class PlaybackRateMenuButton extends MenuButton {
  17137. /**
  17138. * Creates an instance of this class.
  17139. *
  17140. * @param { import('../../player').default } player
  17141. * The `Player` that this class should be attached to.
  17142. *
  17143. * @param {Object} [options]
  17144. * The key/value store of player options.
  17145. */
  17146. constructor(player, options) {
  17147. super(player, options);
  17148. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  17149. this.updateVisibility();
  17150. this.updateLabel();
  17151. this.on(player, 'loadstart', e => this.updateVisibility(e));
  17152. this.on(player, 'ratechange', e => this.updateLabel(e));
  17153. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  17154. }
  17155. /**
  17156. * Create the `Component`'s DOM element
  17157. *
  17158. * @return {Element}
  17159. * The element that was created.
  17160. */
  17161. createEl() {
  17162. const el = super.createEl();
  17163. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  17164. this.labelEl_ = createEl('div', {
  17165. className: 'vjs-playback-rate-value',
  17166. id: this.labelElId_,
  17167. textContent: '1x'
  17168. });
  17169. el.appendChild(this.labelEl_);
  17170. return el;
  17171. }
  17172. dispose() {
  17173. this.labelEl_ = null;
  17174. super.dispose();
  17175. }
  17176. /**
  17177. * Builds the default DOM `className`.
  17178. *
  17179. * @return {string}
  17180. * The DOM `className` for this object.
  17181. */
  17182. buildCSSClass() {
  17183. return `vjs-playback-rate ${super.buildCSSClass()}`;
  17184. }
  17185. buildWrapperCSSClass() {
  17186. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  17187. }
  17188. /**
  17189. * Create the list of menu items. Specific to each subclass.
  17190. *
  17191. */
  17192. createItems() {
  17193. const rates = this.playbackRates();
  17194. const items = [];
  17195. for (let i = rates.length - 1; i >= 0; i--) {
  17196. items.push(new PlaybackRateMenuItem(this.player(), {
  17197. rate: rates[i] + 'x'
  17198. }));
  17199. }
  17200. return items;
  17201. }
  17202. /**
  17203. * On playbackrateschange, update the menu to account for the new items.
  17204. *
  17205. * @listens Player#playbackrateschange
  17206. */
  17207. handlePlaybackRateschange(event) {
  17208. this.update();
  17209. }
  17210. /**
  17211. * Get possible playback rates
  17212. *
  17213. * @return {Array}
  17214. * All possible playback rates
  17215. */
  17216. playbackRates() {
  17217. const player = this.player();
  17218. return player.playbackRates && player.playbackRates() || [];
  17219. }
  17220. /**
  17221. * Get whether playback rates is supported by the tech
  17222. * and an array of playback rates exists
  17223. *
  17224. * @return {boolean}
  17225. * Whether changing playback rate is supported
  17226. */
  17227. playbackRateSupported() {
  17228. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  17229. }
  17230. /**
  17231. * Hide playback rate controls when they're no playback rate options to select
  17232. *
  17233. * @param {Event} [event]
  17234. * The event that caused this function to run.
  17235. *
  17236. * @listens Player#loadstart
  17237. */
  17238. updateVisibility(event) {
  17239. if (this.playbackRateSupported()) {
  17240. this.removeClass('vjs-hidden');
  17241. } else {
  17242. this.addClass('vjs-hidden');
  17243. }
  17244. }
  17245. /**
  17246. * Update button label when rate changed
  17247. *
  17248. * @param {Event} [event]
  17249. * The event that caused this function to run.
  17250. *
  17251. * @listens Player#ratechange
  17252. */
  17253. updateLabel(event) {
  17254. if (this.playbackRateSupported()) {
  17255. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  17256. }
  17257. }
  17258. }
  17259. /**
  17260. * The text that should display over the `PlaybackRateMenuButton`s controls.
  17261. *
  17262. * Added for localization.
  17263. *
  17264. * @type {string}
  17265. * @protected
  17266. */
  17267. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  17268. Component.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  17269. /**
  17270. * @file spacer.js
  17271. */
  17272. /**
  17273. * Just an empty spacer element that can be used as an append point for plugins, etc.
  17274. * Also can be used to create space between elements when necessary.
  17275. *
  17276. * @extends Component
  17277. */
  17278. class Spacer extends Component {
  17279. /**
  17280. * Builds the default DOM `className`.
  17281. *
  17282. * @return {string}
  17283. * The DOM `className` for this object.
  17284. */
  17285. buildCSSClass() {
  17286. return `vjs-spacer ${super.buildCSSClass()}`;
  17287. }
  17288. /**
  17289. * Create the `Component`'s DOM element
  17290. *
  17291. * @return {Element}
  17292. * The element that was created.
  17293. */
  17294. createEl(tag = 'div', props = {}, attributes = {}) {
  17295. if (!props.className) {
  17296. props.className = this.buildCSSClass();
  17297. }
  17298. return super.createEl(tag, props, attributes);
  17299. }
  17300. }
  17301. Component.registerComponent('Spacer', Spacer);
  17302. /**
  17303. * @file custom-control-spacer.js
  17304. */
  17305. /**
  17306. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  17307. *
  17308. * @extends Spacer
  17309. */
  17310. class CustomControlSpacer extends Spacer {
  17311. /**
  17312. * Builds the default DOM `className`.
  17313. *
  17314. * @return {string}
  17315. * The DOM `className` for this object.
  17316. */
  17317. buildCSSClass() {
  17318. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  17319. }
  17320. /**
  17321. * Create the `Component`'s DOM element
  17322. *
  17323. * @return {Element}
  17324. * The element that was created.
  17325. */
  17326. createEl() {
  17327. return super.createEl('div', {
  17328. className: this.buildCSSClass(),
  17329. // No-flex/table-cell mode requires there be some content
  17330. // in the cell to fill the remaining space of the table.
  17331. textContent: '\u00a0'
  17332. });
  17333. }
  17334. }
  17335. Component.registerComponent('CustomControlSpacer', CustomControlSpacer);
  17336. /**
  17337. * @file control-bar.js
  17338. */
  17339. /**
  17340. * Container of main controls.
  17341. *
  17342. * @extends Component
  17343. */
  17344. class ControlBar extends Component {
  17345. /**
  17346. * Create the `Component`'s DOM element
  17347. *
  17348. * @return {Element}
  17349. * The element that was created.
  17350. */
  17351. createEl() {
  17352. return super.createEl('div', {
  17353. className: 'vjs-control-bar',
  17354. dir: 'ltr'
  17355. });
  17356. }
  17357. }
  17358. /**
  17359. * Default options for `ControlBar`
  17360. *
  17361. * @type {Object}
  17362. * @private
  17363. */
  17364. ControlBar.prototype.options_ = {
  17365. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  17366. };
  17367. if ('exitPictureInPicture' in document) {
  17368. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  17369. }
  17370. Component.registerComponent('ControlBar', ControlBar);
  17371. /**
  17372. * @file error-display.js
  17373. */
  17374. /**
  17375. * A display that indicates an error has occurred. This means that the video
  17376. * is unplayable.
  17377. *
  17378. * @extends ModalDialog
  17379. */
  17380. class ErrorDisplay extends ModalDialog {
  17381. /**
  17382. * Creates an instance of this class.
  17383. *
  17384. * @param { import('./player').default } player
  17385. * The `Player` that this class should be attached to.
  17386. *
  17387. * @param {Object} [options]
  17388. * The key/value store of player options.
  17389. */
  17390. constructor(player, options) {
  17391. super(player, options);
  17392. this.on(player, 'error', e => this.open(e));
  17393. }
  17394. /**
  17395. * Builds the default DOM `className`.
  17396. *
  17397. * @return {string}
  17398. * The DOM `className` for this object.
  17399. *
  17400. * @deprecated Since version 5.
  17401. */
  17402. buildCSSClass() {
  17403. return `vjs-error-display ${super.buildCSSClass()}`;
  17404. }
  17405. /**
  17406. * Gets the localized error message based on the `Player`s error.
  17407. *
  17408. * @return {string}
  17409. * The `Player`s error message localized or an empty string.
  17410. */
  17411. content() {
  17412. const error = this.player().error();
  17413. return error ? this.localize(error.message) : '';
  17414. }
  17415. }
  17416. /**
  17417. * The default options for an `ErrorDisplay`.
  17418. *
  17419. * @private
  17420. */
  17421. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  17422. pauseOnOpen: false,
  17423. fillAlways: true,
  17424. temporary: false,
  17425. uncloseable: true
  17426. });
  17427. Component.registerComponent('ErrorDisplay', ErrorDisplay);
  17428. /**
  17429. * @file text-track-settings.js
  17430. */
  17431. const LOCAL_STORAGE_KEY = 'vjs-text-track-settings';
  17432. const COLOR_BLACK = ['#000', 'Black'];
  17433. const COLOR_BLUE = ['#00F', 'Blue'];
  17434. const COLOR_CYAN = ['#0FF', 'Cyan'];
  17435. const COLOR_GREEN = ['#0F0', 'Green'];
  17436. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  17437. const COLOR_RED = ['#F00', 'Red'];
  17438. const COLOR_WHITE = ['#FFF', 'White'];
  17439. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  17440. const OPACITY_OPAQUE = ['1', 'Opaque'];
  17441. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  17442. const OPACITY_TRANS = ['0', 'Transparent'];
  17443. // Configuration for the various <select> elements in the DOM of this component.
  17444. //
  17445. // Possible keys include:
  17446. //
  17447. // `default`:
  17448. // The default option index. Only needs to be provided if not zero.
  17449. // `parser`:
  17450. // A function which is used to parse the value from the selected option in
  17451. // a customized way.
  17452. // `selector`:
  17453. // The selector used to find the associated <select> element.
  17454. const selectConfigs = {
  17455. backgroundColor: {
  17456. selector: '.vjs-bg-color > select',
  17457. id: 'captions-background-color-%s',
  17458. label: 'Color',
  17459. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17460. },
  17461. backgroundOpacity: {
  17462. selector: '.vjs-bg-opacity > select',
  17463. id: 'captions-background-opacity-%s',
  17464. label: 'Opacity',
  17465. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  17466. },
  17467. color: {
  17468. selector: '.vjs-text-color > select',
  17469. id: 'captions-foreground-color-%s',
  17470. label: 'Color',
  17471. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17472. },
  17473. edgeStyle: {
  17474. selector: '.vjs-edge-style > select',
  17475. id: '%s',
  17476. label: 'Text Edge Style',
  17477. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  17478. },
  17479. fontFamily: {
  17480. selector: '.vjs-font-family > select',
  17481. id: 'captions-font-family-%s',
  17482. label: 'Font Family',
  17483. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  17484. },
  17485. fontPercent: {
  17486. selector: '.vjs-font-percent > select',
  17487. id: 'captions-font-size-%s',
  17488. label: 'Font Size',
  17489. 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%']],
  17490. default: 2,
  17491. parser: v => v === '1.00' ? null : Number(v)
  17492. },
  17493. textOpacity: {
  17494. selector: '.vjs-text-opacity > select',
  17495. id: 'captions-foreground-opacity-%s',
  17496. label: 'Opacity',
  17497. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  17498. },
  17499. // Options for this object are defined below.
  17500. windowColor: {
  17501. selector: '.vjs-window-color > select',
  17502. id: 'captions-window-color-%s',
  17503. label: 'Color'
  17504. },
  17505. // Options for this object are defined below.
  17506. windowOpacity: {
  17507. selector: '.vjs-window-opacity > select',
  17508. id: 'captions-window-opacity-%s',
  17509. label: 'Opacity',
  17510. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  17511. }
  17512. };
  17513. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  17514. /**
  17515. * Get the actual value of an option.
  17516. *
  17517. * @param {string} value
  17518. * The value to get
  17519. *
  17520. * @param {Function} [parser]
  17521. * Optional function to adjust the value.
  17522. *
  17523. * @return {*}
  17524. * - Will be `undefined` if no value exists
  17525. * - Will be `undefined` if the given value is "none".
  17526. * - Will be the actual value otherwise.
  17527. *
  17528. * @private
  17529. */
  17530. function parseOptionValue(value, parser) {
  17531. if (parser) {
  17532. value = parser(value);
  17533. }
  17534. if (value && value !== 'none') {
  17535. return value;
  17536. }
  17537. }
  17538. /**
  17539. * Gets the value of the selected <option> element within a <select> element.
  17540. *
  17541. * @param {Element} el
  17542. * the element to look in
  17543. *
  17544. * @param {Function} [parser]
  17545. * Optional function to adjust the value.
  17546. *
  17547. * @return {*}
  17548. * - Will be `undefined` if no value exists
  17549. * - Will be `undefined` if the given value is "none".
  17550. * - Will be the actual value otherwise.
  17551. *
  17552. * @private
  17553. */
  17554. function getSelectedOptionValue(el, parser) {
  17555. const value = el.options[el.options.selectedIndex].value;
  17556. return parseOptionValue(value, parser);
  17557. }
  17558. /**
  17559. * Sets the selected <option> element within a <select> element based on a
  17560. * given value.
  17561. *
  17562. * @param {Element} el
  17563. * The element to look in.
  17564. *
  17565. * @param {string} value
  17566. * the property to look on.
  17567. *
  17568. * @param {Function} [parser]
  17569. * Optional function to adjust the value before comparing.
  17570. *
  17571. * @private
  17572. */
  17573. function setSelectedOption(el, value, parser) {
  17574. if (!value) {
  17575. return;
  17576. }
  17577. for (let i = 0; i < el.options.length; i++) {
  17578. if (parseOptionValue(el.options[i].value, parser) === value) {
  17579. el.selectedIndex = i;
  17580. break;
  17581. }
  17582. }
  17583. }
  17584. /**
  17585. * Manipulate Text Tracks settings.
  17586. *
  17587. * @extends ModalDialog
  17588. */
  17589. class TextTrackSettings extends ModalDialog {
  17590. /**
  17591. * Creates an instance of this class.
  17592. *
  17593. * @param { import('../player').default } player
  17594. * The `Player` that this class should be attached to.
  17595. *
  17596. * @param {Object} [options]
  17597. * The key/value store of player options.
  17598. */
  17599. constructor(player, options) {
  17600. options.temporary = false;
  17601. super(player, options);
  17602. this.updateDisplay = this.updateDisplay.bind(this);
  17603. // fill the modal and pretend we have opened it
  17604. this.fill();
  17605. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  17606. this.endDialog = createEl('p', {
  17607. className: 'vjs-control-text',
  17608. textContent: this.localize('End of dialog window.')
  17609. });
  17610. this.el().appendChild(this.endDialog);
  17611. this.setDefaults();
  17612. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  17613. if (options.persistTextTrackSettings === undefined) {
  17614. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  17615. }
  17616. this.on(this.$('.vjs-done-button'), 'click', () => {
  17617. this.saveSettings();
  17618. this.close();
  17619. });
  17620. this.on(this.$('.vjs-default-button'), 'click', () => {
  17621. this.setDefaults();
  17622. this.updateDisplay();
  17623. });
  17624. each(selectConfigs, config => {
  17625. this.on(this.$(config.selector), 'change', this.updateDisplay);
  17626. });
  17627. if (this.options_.persistTextTrackSettings) {
  17628. this.restoreSettings();
  17629. }
  17630. }
  17631. dispose() {
  17632. this.endDialog = null;
  17633. super.dispose();
  17634. }
  17635. /**
  17636. * Create a <select> element with configured options.
  17637. *
  17638. * @param {string} key
  17639. * Configuration key to use during creation.
  17640. *
  17641. * @return {string}
  17642. * An HTML string.
  17643. *
  17644. * @private
  17645. */
  17646. createElSelect_(key, legendId = '', type = 'label') {
  17647. const config = selectConfigs[key];
  17648. const id = config.id.replace('%s', this.id_);
  17649. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  17650. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  17651. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  17652. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  17653. })).concat('</select>').join('');
  17654. }
  17655. /**
  17656. * Create foreground color element for the component
  17657. *
  17658. * @return {string}
  17659. * An HTML string.
  17660. *
  17661. * @private
  17662. */
  17663. createElFgColor_() {
  17664. const legendId = `captions-text-legend-${this.id_}`;
  17665. 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('');
  17666. }
  17667. /**
  17668. * Create background color element for the component
  17669. *
  17670. * @return {string}
  17671. * An HTML string.
  17672. *
  17673. * @private
  17674. */
  17675. createElBgColor_() {
  17676. const legendId = `captions-background-${this.id_}`;
  17677. 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('');
  17678. }
  17679. /**
  17680. * Create window color element for the component
  17681. *
  17682. * @return {string}
  17683. * An HTML string.
  17684. *
  17685. * @private
  17686. */
  17687. createElWinColor_() {
  17688. const legendId = `captions-window-${this.id_}`;
  17689. 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('');
  17690. }
  17691. /**
  17692. * Create color elements for the component
  17693. *
  17694. * @return {Element}
  17695. * The element that was created
  17696. *
  17697. * @private
  17698. */
  17699. createElColors_() {
  17700. return createEl('div', {
  17701. className: 'vjs-track-settings-colors',
  17702. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  17703. });
  17704. }
  17705. /**
  17706. * Create font elements for the component
  17707. *
  17708. * @return {Element}
  17709. * The element that was created.
  17710. *
  17711. * @private
  17712. */
  17713. createElFont_() {
  17714. return createEl('div', {
  17715. className: 'vjs-track-settings-font',
  17716. 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('')
  17717. });
  17718. }
  17719. /**
  17720. * Create controls for the component
  17721. *
  17722. * @return {Element}
  17723. * The element that was created.
  17724. *
  17725. * @private
  17726. */
  17727. createElControls_() {
  17728. const defaultsDescription = this.localize('restore all settings to the default values');
  17729. return createEl('div', {
  17730. className: 'vjs-track-settings-controls',
  17731. 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('')
  17732. });
  17733. }
  17734. content() {
  17735. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  17736. }
  17737. label() {
  17738. return this.localize('Caption Settings Dialog');
  17739. }
  17740. description() {
  17741. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  17742. }
  17743. buildCSSClass() {
  17744. return super.buildCSSClass() + ' vjs-text-track-settings';
  17745. }
  17746. /**
  17747. * Gets an object of text track settings (or null).
  17748. *
  17749. * @return {Object}
  17750. * An object with config values parsed from the DOM or localStorage.
  17751. */
  17752. getValues() {
  17753. return reduce(selectConfigs, (accum, config, key) => {
  17754. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  17755. if (value !== undefined) {
  17756. accum[key] = value;
  17757. }
  17758. return accum;
  17759. }, {});
  17760. }
  17761. /**
  17762. * Sets text track settings from an object of values.
  17763. *
  17764. * @param {Object} values
  17765. * An object with config values parsed from the DOM or localStorage.
  17766. */
  17767. setValues(values) {
  17768. each(selectConfigs, (config, key) => {
  17769. setSelectedOption(this.$(config.selector), values[key], config.parser);
  17770. });
  17771. }
  17772. /**
  17773. * Sets all `<select>` elements to their default values.
  17774. */
  17775. setDefaults() {
  17776. each(selectConfigs, config => {
  17777. const index = config.hasOwnProperty('default') ? config.default : 0;
  17778. this.$(config.selector).selectedIndex = index;
  17779. });
  17780. }
  17781. /**
  17782. * Restore texttrack settings from localStorage
  17783. */
  17784. restoreSettings() {
  17785. let values;
  17786. try {
  17787. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY));
  17788. } catch (err) {
  17789. log.warn(err);
  17790. }
  17791. if (values) {
  17792. this.setValues(values);
  17793. }
  17794. }
  17795. /**
  17796. * Save text track settings to localStorage
  17797. */
  17798. saveSettings() {
  17799. if (!this.options_.persistTextTrackSettings) {
  17800. return;
  17801. }
  17802. const values = this.getValues();
  17803. try {
  17804. if (Object.keys(values).length) {
  17805. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values));
  17806. } else {
  17807. window.localStorage.removeItem(LOCAL_STORAGE_KEY);
  17808. }
  17809. } catch (err) {
  17810. log.warn(err);
  17811. }
  17812. }
  17813. /**
  17814. * Update display of text track settings
  17815. */
  17816. updateDisplay() {
  17817. const ttDisplay = this.player_.getChild('textTrackDisplay');
  17818. if (ttDisplay) {
  17819. ttDisplay.updateDisplay();
  17820. }
  17821. }
  17822. /**
  17823. * conditionally blur the element and refocus the captions button
  17824. *
  17825. * @private
  17826. */
  17827. conditionalBlur_() {
  17828. this.previouslyActiveEl_ = null;
  17829. const cb = this.player_.controlBar;
  17830. const subsCapsBtn = cb && cb.subsCapsButton;
  17831. const ccBtn = cb && cb.captionsButton;
  17832. if (subsCapsBtn) {
  17833. subsCapsBtn.focus();
  17834. } else if (ccBtn) {
  17835. ccBtn.focus();
  17836. }
  17837. }
  17838. /**
  17839. * Repopulate dialog with new localizations on languagechange
  17840. */
  17841. handleLanguagechange() {
  17842. this.fill();
  17843. }
  17844. }
  17845. Component.registerComponent('TextTrackSettings', TextTrackSettings);
  17846. /**
  17847. * @file resize-manager.js
  17848. */
  17849. /**
  17850. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  17851. *
  17852. * 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}.
  17853. *
  17854. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  17855. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  17856. *
  17857. * @example <caption>How to disable the resize manager</caption>
  17858. * const player = videojs('#vid', {
  17859. * resizeManager: false
  17860. * });
  17861. *
  17862. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  17863. *
  17864. * @extends Component
  17865. */
  17866. class ResizeManager extends Component {
  17867. /**
  17868. * Create the ResizeManager.
  17869. *
  17870. * @param {Object} player
  17871. * The `Player` that this class should be attached to.
  17872. *
  17873. * @param {Object} [options]
  17874. * The key/value store of ResizeManager options.
  17875. *
  17876. * @param {Object} [options.ResizeObserver]
  17877. * A polyfill for ResizeObserver can be passed in here.
  17878. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  17879. */
  17880. constructor(player, options) {
  17881. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver;
  17882. // if `null` was passed, we want to disable the ResizeObserver
  17883. if (options.ResizeObserver === null) {
  17884. RESIZE_OBSERVER_AVAILABLE = false;
  17885. }
  17886. // Only create an element when ResizeObserver isn't available
  17887. const options_ = merge({
  17888. createEl: !RESIZE_OBSERVER_AVAILABLE,
  17889. reportTouchActivity: false
  17890. }, options);
  17891. super(player, options_);
  17892. this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  17893. this.loadListener_ = null;
  17894. this.resizeObserver_ = null;
  17895. this.debouncedHandler_ = debounce(() => {
  17896. this.resizeHandler();
  17897. }, 100, false, this);
  17898. if (RESIZE_OBSERVER_AVAILABLE) {
  17899. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  17900. this.resizeObserver_.observe(player.el());
  17901. } else {
  17902. this.loadListener_ = () => {
  17903. if (!this.el_ || !this.el_.contentWindow) {
  17904. return;
  17905. }
  17906. const debouncedHandler_ = this.debouncedHandler_;
  17907. let unloadListener_ = this.unloadListener_ = function () {
  17908. off(this, 'resize', debouncedHandler_);
  17909. off(this, 'unload', unloadListener_);
  17910. unloadListener_ = null;
  17911. };
  17912. // safari and edge can unload the iframe before resizemanager dispose
  17913. // we have to dispose of event handlers correctly before that happens
  17914. on(this.el_.contentWindow, 'unload', unloadListener_);
  17915. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  17916. };
  17917. this.one('load', this.loadListener_);
  17918. }
  17919. }
  17920. createEl() {
  17921. return super.createEl('iframe', {
  17922. className: 'vjs-resize-manager',
  17923. tabIndex: -1,
  17924. title: this.localize('No content')
  17925. }, {
  17926. 'aria-hidden': 'true'
  17927. });
  17928. }
  17929. /**
  17930. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  17931. *
  17932. * @fires Player#playerresize
  17933. */
  17934. resizeHandler() {
  17935. /**
  17936. * Called when the player size has changed
  17937. *
  17938. * @event Player#playerresize
  17939. * @type {Event}
  17940. */
  17941. // make sure player is still around to trigger
  17942. // prevents this from causing an error after dispose
  17943. if (!this.player_ || !this.player_.trigger) {
  17944. return;
  17945. }
  17946. this.player_.trigger('playerresize');
  17947. }
  17948. dispose() {
  17949. if (this.debouncedHandler_) {
  17950. this.debouncedHandler_.cancel();
  17951. }
  17952. if (this.resizeObserver_) {
  17953. if (this.player_.el()) {
  17954. this.resizeObserver_.unobserve(this.player_.el());
  17955. }
  17956. this.resizeObserver_.disconnect();
  17957. }
  17958. if (this.loadListener_) {
  17959. this.off('load', this.loadListener_);
  17960. }
  17961. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  17962. this.unloadListener_.call(this.el_.contentWindow);
  17963. }
  17964. this.ResizeObserver = null;
  17965. this.resizeObserver = null;
  17966. this.debouncedHandler_ = null;
  17967. this.loadListener_ = null;
  17968. super.dispose();
  17969. }
  17970. }
  17971. Component.registerComponent('ResizeManager', ResizeManager);
  17972. const defaults = {
  17973. trackingThreshold: 20,
  17974. liveTolerance: 15
  17975. };
  17976. /*
  17977. track when we are at the live edge, and other helpers for live playback */
  17978. /**
  17979. * A class for checking live current time and determining when the player
  17980. * is at or behind the live edge.
  17981. */
  17982. class LiveTracker extends Component {
  17983. /**
  17984. * Creates an instance of this class.
  17985. *
  17986. * @param { import('./player').default } player
  17987. * The `Player` that this class should be attached to.
  17988. *
  17989. * @param {Object} [options]
  17990. * The key/value store of player options.
  17991. *
  17992. * @param {number} [options.trackingThreshold=20]
  17993. * Number of seconds of live window (seekableEnd - seekableStart) that
  17994. * media needs to have before the liveui will be shown.
  17995. *
  17996. * @param {number} [options.liveTolerance=15]
  17997. * Number of seconds behind live that we have to be
  17998. * before we will be considered non-live. Note that this will only
  17999. * be used when playing at the live edge. This allows large seekable end
  18000. * changes to not effect whether we are live or not.
  18001. */
  18002. constructor(player, options) {
  18003. // LiveTracker does not need an element
  18004. const options_ = merge(defaults, options, {
  18005. createEl: false
  18006. });
  18007. super(player, options_);
  18008. this.trackLiveHandler_ = () => this.trackLive_();
  18009. this.handlePlay_ = e => this.handlePlay(e);
  18010. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  18011. this.handleSeeked_ = e => this.handleSeeked(e);
  18012. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  18013. this.reset_();
  18014. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  18015. // we should try to toggle tracking on canplay as native playback engines, like Safari
  18016. // may not have the proper values for things like seekableEnd until then
  18017. this.on(this.player_, 'canplay', () => this.toggleTracking());
  18018. }
  18019. /**
  18020. * all the functionality for tracking when seek end changes
  18021. * and for tracking how far past seek end we should be
  18022. */
  18023. trackLive_() {
  18024. const seekable = this.player_.seekable();
  18025. // skip undefined seekable
  18026. if (!seekable || !seekable.length) {
  18027. return;
  18028. }
  18029. const newTime = Number(window.performance.now().toFixed(4));
  18030. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  18031. this.lastTime_ = newTime;
  18032. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  18033. const liveCurrentTime = this.liveCurrentTime();
  18034. const currentTime = this.player_.currentTime();
  18035. // we are behind live if any are true
  18036. // 1. the player is paused
  18037. // 2. the user seeked to a location 2 seconds away from live
  18038. // 3. the difference between live and current time is greater
  18039. // liveTolerance which defaults to 15s
  18040. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  18041. // we cannot be behind if
  18042. // 1. until we have not seen a timeupdate yet
  18043. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  18044. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  18045. isBehind = false;
  18046. }
  18047. if (isBehind !== this.behindLiveEdge_) {
  18048. this.behindLiveEdge_ = isBehind;
  18049. this.trigger('liveedgechange');
  18050. }
  18051. }
  18052. /**
  18053. * handle a durationchange event on the player
  18054. * and start/stop tracking accordingly.
  18055. */
  18056. handleDurationchange() {
  18057. this.toggleTracking();
  18058. }
  18059. /**
  18060. * start/stop tracking
  18061. */
  18062. toggleTracking() {
  18063. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  18064. if (this.player_.options_.liveui) {
  18065. this.player_.addClass('vjs-liveui');
  18066. }
  18067. this.startTracking();
  18068. } else {
  18069. this.player_.removeClass('vjs-liveui');
  18070. this.stopTracking();
  18071. }
  18072. }
  18073. /**
  18074. * start tracking live playback
  18075. */
  18076. startTracking() {
  18077. if (this.isTracking()) {
  18078. return;
  18079. }
  18080. // If we haven't seen a timeupdate, we need to check whether playback
  18081. // began before this component started tracking. This can happen commonly
  18082. // when using autoplay.
  18083. if (!this.timeupdateSeen_) {
  18084. this.timeupdateSeen_ = this.player_.hasStarted();
  18085. }
  18086. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  18087. this.trackLive_();
  18088. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18089. if (!this.timeupdateSeen_) {
  18090. this.one(this.player_, 'play', this.handlePlay_);
  18091. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18092. } else {
  18093. this.on(this.player_, 'seeked', this.handleSeeked_);
  18094. }
  18095. }
  18096. /**
  18097. * handle the first timeupdate on the player if it wasn't already playing
  18098. * when live tracker started tracking.
  18099. */
  18100. handleFirstTimeupdate() {
  18101. this.timeupdateSeen_ = true;
  18102. this.on(this.player_, 'seeked', this.handleSeeked_);
  18103. }
  18104. /**
  18105. * Keep track of what time a seek starts, and listen for seeked
  18106. * to find where a seek ends.
  18107. */
  18108. handleSeeked() {
  18109. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  18110. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  18111. this.nextSeekedFromUser_ = false;
  18112. this.trackLive_();
  18113. }
  18114. /**
  18115. * handle the first play on the player, and make sure that we seek
  18116. * right to the live edge.
  18117. */
  18118. handlePlay() {
  18119. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18120. }
  18121. /**
  18122. * Stop tracking, and set all internal variables to
  18123. * their initial value.
  18124. */
  18125. reset_() {
  18126. this.lastTime_ = -1;
  18127. this.pastSeekEnd_ = 0;
  18128. this.lastSeekEnd_ = -1;
  18129. this.behindLiveEdge_ = true;
  18130. this.timeupdateSeen_ = false;
  18131. this.seekedBehindLive_ = false;
  18132. this.nextSeekedFromUser_ = false;
  18133. this.clearInterval(this.trackingInterval_);
  18134. this.trackingInterval_ = null;
  18135. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18136. this.off(this.player_, 'seeked', this.handleSeeked_);
  18137. this.off(this.player_, 'play', this.handlePlay_);
  18138. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18139. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18140. }
  18141. /**
  18142. * The next seeked event is from the user. Meaning that any seek
  18143. * > 2s behind live will be considered behind live for real and
  18144. * liveTolerance will be ignored.
  18145. */
  18146. nextSeekedFromUser() {
  18147. this.nextSeekedFromUser_ = true;
  18148. }
  18149. /**
  18150. * stop tracking live playback
  18151. */
  18152. stopTracking() {
  18153. if (!this.isTracking()) {
  18154. return;
  18155. }
  18156. this.reset_();
  18157. this.trigger('liveedgechange');
  18158. }
  18159. /**
  18160. * A helper to get the player seekable end
  18161. * so that we don't have to null check everywhere
  18162. *
  18163. * @return {number}
  18164. * The furthest seekable end or Infinity.
  18165. */
  18166. seekableEnd() {
  18167. const seekable = this.player_.seekable();
  18168. const seekableEnds = [];
  18169. let i = seekable ? seekable.length : 0;
  18170. while (i--) {
  18171. seekableEnds.push(seekable.end(i));
  18172. }
  18173. // grab the furthest seekable end after sorting, or if there are none
  18174. // default to Infinity
  18175. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  18176. }
  18177. /**
  18178. * A helper to get the player seekable start
  18179. * so that we don't have to null check everywhere
  18180. *
  18181. * @return {number}
  18182. * The earliest seekable start or 0.
  18183. */
  18184. seekableStart() {
  18185. const seekable = this.player_.seekable();
  18186. const seekableStarts = [];
  18187. let i = seekable ? seekable.length : 0;
  18188. while (i--) {
  18189. seekableStarts.push(seekable.start(i));
  18190. }
  18191. // grab the first seekable start after sorting, or if there are none
  18192. // default to 0
  18193. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  18194. }
  18195. /**
  18196. * Get the live time window aka
  18197. * the amount of time between seekable start and
  18198. * live current time.
  18199. *
  18200. * @return {number}
  18201. * The amount of seconds that are seekable in
  18202. * the live video.
  18203. */
  18204. liveWindow() {
  18205. const liveCurrentTime = this.liveCurrentTime();
  18206. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  18207. if (liveCurrentTime === Infinity) {
  18208. return 0;
  18209. }
  18210. return liveCurrentTime - this.seekableStart();
  18211. }
  18212. /**
  18213. * Determines if the player is live, only checks if this component
  18214. * is tracking live playback or not
  18215. *
  18216. * @return {boolean}
  18217. * Whether liveTracker is tracking
  18218. */
  18219. isLive() {
  18220. return this.isTracking();
  18221. }
  18222. /**
  18223. * Determines if currentTime is at the live edge and won't fall behind
  18224. * on each seekableendchange
  18225. *
  18226. * @return {boolean}
  18227. * Whether playback is at the live edge
  18228. */
  18229. atLiveEdge() {
  18230. return !this.behindLiveEdge();
  18231. }
  18232. /**
  18233. * get what we expect the live current time to be
  18234. *
  18235. * @return {number}
  18236. * The expected live current time
  18237. */
  18238. liveCurrentTime() {
  18239. return this.pastSeekEnd() + this.seekableEnd();
  18240. }
  18241. /**
  18242. * The number of seconds that have occurred after seekable end
  18243. * changed. This will be reset to 0 once seekable end changes.
  18244. *
  18245. * @return {number}
  18246. * Seconds past the current seekable end
  18247. */
  18248. pastSeekEnd() {
  18249. const seekableEnd = this.seekableEnd();
  18250. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  18251. this.pastSeekEnd_ = 0;
  18252. }
  18253. this.lastSeekEnd_ = seekableEnd;
  18254. return this.pastSeekEnd_;
  18255. }
  18256. /**
  18257. * If we are currently behind the live edge, aka currentTime will be
  18258. * behind on a seekableendchange
  18259. *
  18260. * @return {boolean}
  18261. * If we are behind the live edge
  18262. */
  18263. behindLiveEdge() {
  18264. return this.behindLiveEdge_;
  18265. }
  18266. /**
  18267. * Whether live tracker is currently tracking or not.
  18268. */
  18269. isTracking() {
  18270. return typeof this.trackingInterval_ === 'number';
  18271. }
  18272. /**
  18273. * Seek to the live edge if we are behind the live edge
  18274. */
  18275. seekToLiveEdge() {
  18276. this.seekedBehindLive_ = false;
  18277. if (this.atLiveEdge()) {
  18278. return;
  18279. }
  18280. this.nextSeekedFromUser_ = false;
  18281. this.player_.currentTime(this.liveCurrentTime());
  18282. }
  18283. /**
  18284. * Dispose of liveTracker
  18285. */
  18286. dispose() {
  18287. this.stopTracking();
  18288. super.dispose();
  18289. }
  18290. }
  18291. Component.registerComponent('LiveTracker', LiveTracker);
  18292. /**
  18293. * Displays an element over the player which contains an optional title and
  18294. * description for the current content.
  18295. *
  18296. * Much of the code for this component originated in the now obsolete
  18297. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  18298. *
  18299. * @extends Component
  18300. */
  18301. class TitleBar extends Component {
  18302. constructor(player, options) {
  18303. super(player, options);
  18304. this.on('statechanged', e => this.updateDom_());
  18305. this.updateDom_();
  18306. }
  18307. /**
  18308. * Create the `TitleBar`'s DOM element
  18309. *
  18310. * @return {Element}
  18311. * The element that was created.
  18312. */
  18313. createEl() {
  18314. this.els = {
  18315. title: createEl('div', {
  18316. className: 'vjs-title-bar-title',
  18317. id: `vjs-title-bar-title-${newGUID()}`
  18318. }),
  18319. description: createEl('div', {
  18320. className: 'vjs-title-bar-description',
  18321. id: `vjs-title-bar-description-${newGUID()}`
  18322. })
  18323. };
  18324. return createEl('div', {
  18325. className: 'vjs-title-bar'
  18326. }, {}, Object.values(this.els));
  18327. }
  18328. /**
  18329. * Updates the DOM based on the component's state object.
  18330. */
  18331. updateDom_() {
  18332. const tech = this.player_.tech_;
  18333. const techEl = tech && tech.el_;
  18334. const techAriaAttrs = {
  18335. title: 'aria-labelledby',
  18336. description: 'aria-describedby'
  18337. };
  18338. ['title', 'description'].forEach(k => {
  18339. const value = this.state[k];
  18340. const el = this.els[k];
  18341. const techAriaAttr = techAriaAttrs[k];
  18342. emptyEl(el);
  18343. if (value) {
  18344. textContent(el, value);
  18345. }
  18346. // If there is a tech element available, update its ARIA attributes
  18347. // according to whether a title and/or description have been provided.
  18348. if (techEl) {
  18349. techEl.removeAttribute(techAriaAttr);
  18350. if (value) {
  18351. techEl.setAttribute(techAriaAttr, el.id);
  18352. }
  18353. }
  18354. });
  18355. if (this.state.title || this.state.description) {
  18356. this.show();
  18357. } else {
  18358. this.hide();
  18359. }
  18360. }
  18361. /**
  18362. * Update the contents of the title bar component with new title and
  18363. * description text.
  18364. *
  18365. * If both title and description are missing, the title bar will be hidden.
  18366. *
  18367. * If either title or description are present, the title bar will be visible.
  18368. *
  18369. * NOTE: Any previously set value will be preserved. To unset a previously
  18370. * set value, you must pass an empty string or null.
  18371. *
  18372. * For example:
  18373. *
  18374. * ```
  18375. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  18376. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  18377. * update({title: ''}) // title: '', description: 'bar2'
  18378. * update({title: 'foo', description: null}) // title: 'foo', description: null
  18379. * ```
  18380. *
  18381. * @param {Object} [options={}]
  18382. * An options object. When empty, the title bar will be hidden.
  18383. *
  18384. * @param {string} [options.title]
  18385. * A title to display in the title bar.
  18386. *
  18387. * @param {string} [options.description]
  18388. * A description to display in the title bar.
  18389. */
  18390. update(options) {
  18391. this.setState(options);
  18392. }
  18393. /**
  18394. * Dispose the component.
  18395. */
  18396. dispose() {
  18397. const tech = this.player_.tech_;
  18398. const techEl = tech && tech.el_;
  18399. if (techEl) {
  18400. techEl.removeAttribute('aria-labelledby');
  18401. techEl.removeAttribute('aria-describedby');
  18402. }
  18403. super.dispose();
  18404. this.els = null;
  18405. }
  18406. }
  18407. Component.registerComponent('TitleBar', TitleBar);
  18408. /**
  18409. * This function is used to fire a sourceset when there is something
  18410. * similar to `mediaEl.load()` being called. It will try to find the source via
  18411. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  18412. * with the source that was found or empty string if we cannot know. If it cannot
  18413. * find a source then `sourceset` will not be fired.
  18414. *
  18415. * @param { import('./html5').default } tech
  18416. * The tech object that sourceset was setup on
  18417. *
  18418. * @return {boolean}
  18419. * returns false if the sourceset was not fired and true otherwise.
  18420. */
  18421. const sourcesetLoad = tech => {
  18422. const el = tech.el();
  18423. // if `el.src` is set, that source will be loaded.
  18424. if (el.hasAttribute('src')) {
  18425. tech.triggerSourceset(el.src);
  18426. return true;
  18427. }
  18428. /**
  18429. * Since there isn't a src property on the media element, source elements will be used for
  18430. * implementing the source selection algorithm. This happens asynchronously and
  18431. * for most cases were there is more than one source we cannot tell what source will
  18432. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  18433. * going to do that. There are three special cases that we do handle here though:
  18434. *
  18435. * 1. If there are no sources, do not fire `sourceset`.
  18436. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  18437. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  18438. * That will be our src.
  18439. */
  18440. const sources = tech.$$('source');
  18441. const srcUrls = [];
  18442. let src = '';
  18443. // if there are no sources, do not fire sourceset
  18444. if (!sources.length) {
  18445. return false;
  18446. }
  18447. // only count valid/non-duplicate source elements
  18448. for (let i = 0; i < sources.length; i++) {
  18449. const url = sources[i].src;
  18450. if (url && srcUrls.indexOf(url) === -1) {
  18451. srcUrls.push(url);
  18452. }
  18453. }
  18454. // there were no valid sources
  18455. if (!srcUrls.length) {
  18456. return false;
  18457. }
  18458. // there is only one valid source element url
  18459. // use that
  18460. if (srcUrls.length === 1) {
  18461. src = srcUrls[0];
  18462. }
  18463. tech.triggerSourceset(src);
  18464. return true;
  18465. };
  18466. /**
  18467. * our implementation of an `innerHTML` descriptor for browsers
  18468. * that do not have one.
  18469. */
  18470. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  18471. get() {
  18472. return this.cloneNode(true).innerHTML;
  18473. },
  18474. set(v) {
  18475. // make a dummy node to use innerHTML on
  18476. const dummy = document.createElement(this.nodeName.toLowerCase());
  18477. // set innerHTML to the value provided
  18478. dummy.innerHTML = v;
  18479. // make a document fragment to hold the nodes from dummy
  18480. const docFrag = document.createDocumentFragment();
  18481. // copy all of the nodes created by the innerHTML on dummy
  18482. // to the document fragment
  18483. while (dummy.childNodes.length) {
  18484. docFrag.appendChild(dummy.childNodes[0]);
  18485. }
  18486. // remove content
  18487. this.innerText = '';
  18488. // now we add all of that html in one by appending the
  18489. // document fragment. This is how innerHTML does it.
  18490. window.Element.prototype.appendChild.call(this, docFrag);
  18491. // then return the result that innerHTML's setter would
  18492. return this.innerHTML;
  18493. }
  18494. });
  18495. /**
  18496. * Get a property descriptor given a list of priorities and the
  18497. * property to get.
  18498. */
  18499. const getDescriptor = (priority, prop) => {
  18500. let descriptor = {};
  18501. for (let i = 0; i < priority.length; i++) {
  18502. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  18503. if (descriptor && descriptor.set && descriptor.get) {
  18504. break;
  18505. }
  18506. }
  18507. descriptor.enumerable = true;
  18508. descriptor.configurable = true;
  18509. return descriptor;
  18510. };
  18511. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  18512. /**
  18513. * Patches browser internal functions so that we can tell synchronously
  18514. * if a `<source>` was appended to the media element. For some reason this
  18515. * causes a `sourceset` if the the media element is ready and has no source.
  18516. * This happens when:
  18517. * - The page has just loaded and the media element does not have a source.
  18518. * - The media element was emptied of all sources, then `load()` was called.
  18519. *
  18520. * It does this by patching the following functions/properties when they are supported:
  18521. *
  18522. * - `append()` - can be used to add a `<source>` element to the media element
  18523. * - `appendChild()` - can be used to add a `<source>` element to the media element
  18524. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  18525. * - `innerHTML` - can be used to add a `<source>` element to the media element
  18526. *
  18527. * @param {Html5} tech
  18528. * The tech object that sourceset is being setup on.
  18529. */
  18530. const firstSourceWatch = function (tech) {
  18531. const el = tech.el();
  18532. // make sure firstSourceWatch isn't setup twice.
  18533. if (el.resetSourceWatch_) {
  18534. return;
  18535. }
  18536. const old = {};
  18537. const innerDescriptor = getInnerHTMLDescriptor(tech);
  18538. const appendWrapper = appendFn => (...args) => {
  18539. const retval = appendFn.apply(el, args);
  18540. sourcesetLoad(tech);
  18541. return retval;
  18542. };
  18543. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  18544. if (!el[k]) {
  18545. return;
  18546. }
  18547. // store the old function
  18548. old[k] = el[k];
  18549. // call the old function with a sourceset if a source
  18550. // was loaded
  18551. el[k] = appendWrapper(old[k]);
  18552. });
  18553. Object.defineProperty(el, 'innerHTML', merge(innerDescriptor, {
  18554. set: appendWrapper(innerDescriptor.set)
  18555. }));
  18556. el.resetSourceWatch_ = () => {
  18557. el.resetSourceWatch_ = null;
  18558. Object.keys(old).forEach(k => {
  18559. el[k] = old[k];
  18560. });
  18561. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  18562. };
  18563. // on the first sourceset, we need to revert our changes
  18564. tech.one('sourceset', el.resetSourceWatch_);
  18565. };
  18566. /**
  18567. * our implementation of a `src` descriptor for browsers
  18568. * that do not have one
  18569. */
  18570. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  18571. get() {
  18572. if (this.hasAttribute('src')) {
  18573. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  18574. }
  18575. return '';
  18576. },
  18577. set(v) {
  18578. window.Element.prototype.setAttribute.call(this, 'src', v);
  18579. return v;
  18580. }
  18581. });
  18582. const getSrcDescriptor = tech => getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  18583. /**
  18584. * setup `sourceset` handling on the `Html5` tech. This function
  18585. * patches the following element properties/functions:
  18586. *
  18587. * - `src` - to determine when `src` is set
  18588. * - `setAttribute()` - to determine when `src` is set
  18589. * - `load()` - this re-triggers the source selection algorithm, and can
  18590. * cause a sourceset.
  18591. *
  18592. * If there is no source when we are adding `sourceset` support or during a `load()`
  18593. * we also patch the functions listed in `firstSourceWatch`.
  18594. *
  18595. * @param {Html5} tech
  18596. * The tech to patch
  18597. */
  18598. const setupSourceset = function (tech) {
  18599. if (!tech.featuresSourceset) {
  18600. return;
  18601. }
  18602. const el = tech.el();
  18603. // make sure sourceset isn't setup twice.
  18604. if (el.resetSourceset_) {
  18605. return;
  18606. }
  18607. const srcDescriptor = getSrcDescriptor(tech);
  18608. const oldSetAttribute = el.setAttribute;
  18609. const oldLoad = el.load;
  18610. Object.defineProperty(el, 'src', merge(srcDescriptor, {
  18611. set: v => {
  18612. const retval = srcDescriptor.set.call(el, v);
  18613. // we use the getter here to get the actual value set on src
  18614. tech.triggerSourceset(el.src);
  18615. return retval;
  18616. }
  18617. }));
  18618. el.setAttribute = (n, v) => {
  18619. const retval = oldSetAttribute.call(el, n, v);
  18620. if (/src/i.test(n)) {
  18621. tech.triggerSourceset(el.src);
  18622. }
  18623. return retval;
  18624. };
  18625. el.load = () => {
  18626. const retval = oldLoad.call(el);
  18627. // if load was called, but there was no source to fire
  18628. // sourceset on. We have to watch for a source append
  18629. // as that can trigger a `sourceset` when the media element
  18630. // has no source
  18631. if (!sourcesetLoad(tech)) {
  18632. tech.triggerSourceset('');
  18633. firstSourceWatch(tech);
  18634. }
  18635. return retval;
  18636. };
  18637. if (el.currentSrc) {
  18638. tech.triggerSourceset(el.currentSrc);
  18639. } else if (!sourcesetLoad(tech)) {
  18640. firstSourceWatch(tech);
  18641. }
  18642. el.resetSourceset_ = () => {
  18643. el.resetSourceset_ = null;
  18644. el.load = oldLoad;
  18645. el.setAttribute = oldSetAttribute;
  18646. Object.defineProperty(el, 'src', srcDescriptor);
  18647. if (el.resetSourceWatch_) {
  18648. el.resetSourceWatch_();
  18649. }
  18650. };
  18651. };
  18652. /**
  18653. * @file html5.js
  18654. */
  18655. /**
  18656. * HTML5 Media Controller - Wrapper for HTML5 Media API
  18657. *
  18658. * @mixes Tech~SourceHandlerAdditions
  18659. * @extends Tech
  18660. */
  18661. class Html5 extends Tech {
  18662. /**
  18663. * Create an instance of this Tech.
  18664. *
  18665. * @param {Object} [options]
  18666. * The key/value store of player options.
  18667. *
  18668. * @param {Function} [ready]
  18669. * Callback function to call when the `HTML5` Tech is ready.
  18670. */
  18671. constructor(options, ready) {
  18672. super(options, ready);
  18673. const source = options.source;
  18674. let crossoriginTracks = false;
  18675. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  18676. // Set the source if one is provided
  18677. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  18678. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  18679. // anyway so the error gets fired.
  18680. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  18681. this.setSource(source);
  18682. } else {
  18683. this.handleLateInit_(this.el_);
  18684. }
  18685. // setup sourceset after late sourceset/init
  18686. if (options.enableSourceset) {
  18687. this.setupSourcesetHandling_();
  18688. }
  18689. this.isScrubbing_ = false;
  18690. if (this.el_.hasChildNodes()) {
  18691. const nodes = this.el_.childNodes;
  18692. let nodesLength = nodes.length;
  18693. const removeNodes = [];
  18694. while (nodesLength--) {
  18695. const node = nodes[nodesLength];
  18696. const nodeName = node.nodeName.toLowerCase();
  18697. if (nodeName === 'track') {
  18698. if (!this.featuresNativeTextTracks) {
  18699. // Empty video tag tracks so the built-in player doesn't use them also.
  18700. // This may not be fast enough to stop HTML5 browsers from reading the tags
  18701. // so we'll need to turn off any default tracks if we're manually doing
  18702. // captions and subtitles. videoElement.textTracks
  18703. removeNodes.push(node);
  18704. } else {
  18705. // store HTMLTrackElement and TextTrack to remote list
  18706. this.remoteTextTrackEls().addTrackElement_(node);
  18707. this.remoteTextTracks().addTrack(node.track);
  18708. this.textTracks().addTrack(node.track);
  18709. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  18710. crossoriginTracks = true;
  18711. }
  18712. }
  18713. }
  18714. }
  18715. for (let i = 0; i < removeNodes.length; i++) {
  18716. this.el_.removeChild(removeNodes[i]);
  18717. }
  18718. }
  18719. this.proxyNativeTracks_();
  18720. if (this.featuresNativeTextTracks && crossoriginTracks) {
  18721. 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.');
  18722. }
  18723. // prevent iOS Safari from disabling metadata text tracks during native playback
  18724. this.restoreMetadataTracksInIOSNativePlayer_();
  18725. // Determine if native controls should be used
  18726. // Our goal should be to get the custom controls on mobile solid everywhere
  18727. // so we can remove this all together. Right now this will block custom
  18728. // controls on touch enabled laptops like the Chrome Pixel
  18729. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  18730. this.setControls(true);
  18731. }
  18732. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  18733. // into a `fullscreenchange` event
  18734. this.proxyWebkitFullscreen_();
  18735. this.triggerReady();
  18736. }
  18737. /**
  18738. * Dispose of `HTML5` media element and remove all tracks.
  18739. */
  18740. dispose() {
  18741. if (this.el_ && this.el_.resetSourceset_) {
  18742. this.el_.resetSourceset_();
  18743. }
  18744. Html5.disposeMediaElement(this.el_);
  18745. this.options_ = null;
  18746. // tech will handle clearing of the emulated track list
  18747. super.dispose();
  18748. }
  18749. /**
  18750. * Modify the media element so that we can detect when
  18751. * the source is changed. Fires `sourceset` just after the source has changed
  18752. */
  18753. setupSourcesetHandling_() {
  18754. setupSourceset(this);
  18755. }
  18756. /**
  18757. * When a captions track is enabled in the iOS Safari native player, all other
  18758. * tracks are disabled (including metadata tracks), which nulls all of their
  18759. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  18760. * state in those cases so that cue points are not needlessly lost.
  18761. *
  18762. * @private
  18763. */
  18764. restoreMetadataTracksInIOSNativePlayer_() {
  18765. const textTracks = this.textTracks();
  18766. let metadataTracksPreFullscreenState;
  18767. // captures a snapshot of every metadata track's current state
  18768. const takeMetadataTrackSnapshot = () => {
  18769. metadataTracksPreFullscreenState = [];
  18770. for (let i = 0; i < textTracks.length; i++) {
  18771. const track = textTracks[i];
  18772. if (track.kind === 'metadata') {
  18773. metadataTracksPreFullscreenState.push({
  18774. track,
  18775. storedMode: track.mode
  18776. });
  18777. }
  18778. }
  18779. };
  18780. // snapshot each metadata track's initial state, and update the snapshot
  18781. // each time there is a track 'change' event
  18782. takeMetadataTrackSnapshot();
  18783. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18784. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  18785. const restoreTrackMode = () => {
  18786. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  18787. const storedTrack = metadataTracksPreFullscreenState[i];
  18788. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  18789. storedTrack.track.mode = storedTrack.storedMode;
  18790. }
  18791. }
  18792. // we only want this handler to be executed on the first 'change' event
  18793. textTracks.removeEventListener('change', restoreTrackMode);
  18794. };
  18795. // when we enter fullscreen playback, stop updating the snapshot and
  18796. // restore all track modes to their pre-fullscreen state
  18797. this.on('webkitbeginfullscreen', () => {
  18798. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18799. // remove the listener before adding it just in case it wasn't previously removed
  18800. textTracks.removeEventListener('change', restoreTrackMode);
  18801. textTracks.addEventListener('change', restoreTrackMode);
  18802. });
  18803. // start updating the snapshot again after leaving fullscreen
  18804. this.on('webkitendfullscreen', () => {
  18805. // remove the listener before adding it just in case it wasn't previously removed
  18806. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  18807. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  18808. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  18809. textTracks.removeEventListener('change', restoreTrackMode);
  18810. });
  18811. }
  18812. /**
  18813. * Attempt to force override of tracks for the given type
  18814. *
  18815. * @param {string} type - Track type to override, possible values include 'Audio',
  18816. * 'Video', and 'Text'.
  18817. * @param {boolean} override - If set to true native audio/video will be overridden,
  18818. * otherwise native audio/video will potentially be used.
  18819. * @private
  18820. */
  18821. overrideNative_(type, override) {
  18822. // If there is no behavioral change don't add/remove listeners
  18823. if (override !== this[`featuresNative${type}Tracks`]) {
  18824. return;
  18825. }
  18826. const lowerCaseType = type.toLowerCase();
  18827. if (this[`${lowerCaseType}TracksListeners_`]) {
  18828. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  18829. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  18830. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  18831. });
  18832. }
  18833. this[`featuresNative${type}Tracks`] = !override;
  18834. this[`${lowerCaseType}TracksListeners_`] = null;
  18835. this.proxyNativeTracksForType_(lowerCaseType);
  18836. }
  18837. /**
  18838. * Attempt to force override of native audio tracks.
  18839. *
  18840. * @param {boolean} override - If set to true native audio will be overridden,
  18841. * otherwise native audio will potentially be used.
  18842. */
  18843. overrideNativeAudioTracks(override) {
  18844. this.overrideNative_('Audio', override);
  18845. }
  18846. /**
  18847. * Attempt to force override of native video tracks.
  18848. *
  18849. * @param {boolean} override - If set to true native video will be overridden,
  18850. * otherwise native video will potentially be used.
  18851. */
  18852. overrideNativeVideoTracks(override) {
  18853. this.overrideNative_('Video', override);
  18854. }
  18855. /**
  18856. * Proxy native track list events for the given type to our track
  18857. * lists if the browser we are playing in supports that type of track list.
  18858. *
  18859. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  18860. * @private
  18861. */
  18862. proxyNativeTracksForType_(name) {
  18863. const props = NORMAL[name];
  18864. const elTracks = this.el()[props.getterName];
  18865. const techTracks = this[props.getterName]();
  18866. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  18867. return;
  18868. }
  18869. const listeners = {
  18870. change: e => {
  18871. const event = {
  18872. type: 'change',
  18873. target: techTracks,
  18874. currentTarget: techTracks,
  18875. srcElement: techTracks
  18876. };
  18877. techTracks.trigger(event);
  18878. // if we are a text track change event, we should also notify the
  18879. // remote text track list. This can potentially cause a false positive
  18880. // if we were to get a change event on a non-remote track and
  18881. // we triggered the event on the remote text track list which doesn't
  18882. // contain that track. However, best practices mean looping through the
  18883. // list of tracks and searching for the appropriate mode value, so,
  18884. // this shouldn't pose an issue
  18885. if (name === 'text') {
  18886. this[REMOTE.remoteText.getterName]().trigger(event);
  18887. }
  18888. },
  18889. addtrack(e) {
  18890. techTracks.addTrack(e.track);
  18891. },
  18892. removetrack(e) {
  18893. techTracks.removeTrack(e.track);
  18894. }
  18895. };
  18896. const removeOldTracks = function () {
  18897. const removeTracks = [];
  18898. for (let i = 0; i < techTracks.length; i++) {
  18899. let found = false;
  18900. for (let j = 0; j < elTracks.length; j++) {
  18901. if (elTracks[j] === techTracks[i]) {
  18902. found = true;
  18903. break;
  18904. }
  18905. }
  18906. if (!found) {
  18907. removeTracks.push(techTracks[i]);
  18908. }
  18909. }
  18910. while (removeTracks.length) {
  18911. techTracks.removeTrack(removeTracks.shift());
  18912. }
  18913. };
  18914. this[props.getterName + 'Listeners_'] = listeners;
  18915. Object.keys(listeners).forEach(eventName => {
  18916. const listener = listeners[eventName];
  18917. elTracks.addEventListener(eventName, listener);
  18918. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  18919. });
  18920. // Remove (native) tracks that are not used anymore
  18921. this.on('loadstart', removeOldTracks);
  18922. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  18923. }
  18924. /**
  18925. * Proxy all native track list events to our track lists if the browser we are playing
  18926. * in supports that type of track list.
  18927. *
  18928. * @private
  18929. */
  18930. proxyNativeTracks_() {
  18931. NORMAL.names.forEach(name => {
  18932. this.proxyNativeTracksForType_(name);
  18933. });
  18934. }
  18935. /**
  18936. * Create the `Html5` Tech's DOM element.
  18937. *
  18938. * @return {Element}
  18939. * The element that gets created.
  18940. */
  18941. createEl() {
  18942. let el = this.options_.tag;
  18943. // Check if this browser supports moving the element into the box.
  18944. // On the iPhone video will break if you move the element,
  18945. // So we have to create a brand new element.
  18946. // If we ingested the player div, we do not need to move the media element.
  18947. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  18948. // If the original tag is still there, clone and remove it.
  18949. if (el) {
  18950. const clone = el.cloneNode(true);
  18951. if (el.parentNode) {
  18952. el.parentNode.insertBefore(clone, el);
  18953. }
  18954. Html5.disposeMediaElement(el);
  18955. el = clone;
  18956. } else {
  18957. el = document.createElement('video');
  18958. // determine if native controls should be used
  18959. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  18960. const attributes = merge({}, tagAttributes);
  18961. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  18962. delete attributes.controls;
  18963. }
  18964. setAttributes(el, Object.assign(attributes, {
  18965. id: this.options_.techId,
  18966. class: 'vjs-tech'
  18967. }));
  18968. }
  18969. el.playerId = this.options_.playerId;
  18970. }
  18971. if (typeof this.options_.preload !== 'undefined') {
  18972. setAttribute(el, 'preload', this.options_.preload);
  18973. }
  18974. if (this.options_.disablePictureInPicture !== undefined) {
  18975. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  18976. }
  18977. // Update specific tag settings, in case they were overridden
  18978. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  18979. // when iOS/Safari or other browsers attempt to autoplay.
  18980. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  18981. for (let i = 0; i < settingsAttrs.length; i++) {
  18982. const attr = settingsAttrs[i];
  18983. const value = this.options_[attr];
  18984. if (typeof value !== 'undefined') {
  18985. if (value) {
  18986. setAttribute(el, attr, attr);
  18987. } else {
  18988. removeAttribute(el, attr);
  18989. }
  18990. el[attr] = value;
  18991. }
  18992. }
  18993. return el;
  18994. }
  18995. /**
  18996. * This will be triggered if the loadstart event has already fired, before videojs was
  18997. * ready. Two known examples of when this can happen are:
  18998. * 1. If we're loading the playback object after it has started loading
  18999. * 2. The media is already playing the (often with autoplay on) then
  19000. *
  19001. * This function will fire another loadstart so that videojs can catchup.
  19002. *
  19003. * @fires Tech#loadstart
  19004. *
  19005. * @return {undefined}
  19006. * returns nothing.
  19007. */
  19008. handleLateInit_(el) {
  19009. if (el.networkState === 0 || el.networkState === 3) {
  19010. // The video element hasn't started loading the source yet
  19011. // or didn't find a source
  19012. return;
  19013. }
  19014. if (el.readyState === 0) {
  19015. // NetworkState is set synchronously BUT loadstart is fired at the
  19016. // end of the current stack, usually before setInterval(fn, 0).
  19017. // So at this point we know loadstart may have already fired or is
  19018. // about to fire, and either way the player hasn't seen it yet.
  19019. // We don't want to fire loadstart prematurely here and cause a
  19020. // double loadstart so we'll wait and see if it happens between now
  19021. // and the next loop, and fire it if not.
  19022. // HOWEVER, we also want to make sure it fires before loadedmetadata
  19023. // which could also happen between now and the next loop, so we'll
  19024. // watch for that also.
  19025. let loadstartFired = false;
  19026. const setLoadstartFired = function () {
  19027. loadstartFired = true;
  19028. };
  19029. this.on('loadstart', setLoadstartFired);
  19030. const triggerLoadstart = function () {
  19031. // We did miss the original loadstart. Make sure the player
  19032. // sees loadstart before loadedmetadata
  19033. if (!loadstartFired) {
  19034. this.trigger('loadstart');
  19035. }
  19036. };
  19037. this.on('loadedmetadata', triggerLoadstart);
  19038. this.ready(function () {
  19039. this.off('loadstart', setLoadstartFired);
  19040. this.off('loadedmetadata', triggerLoadstart);
  19041. if (!loadstartFired) {
  19042. // We did miss the original native loadstart. Fire it now.
  19043. this.trigger('loadstart');
  19044. }
  19045. });
  19046. return;
  19047. }
  19048. // From here on we know that loadstart already fired and we missed it.
  19049. // The other readyState events aren't as much of a problem if we double
  19050. // them, so not going to go to as much trouble as loadstart to prevent
  19051. // that unless we find reason to.
  19052. const eventsToTrigger = ['loadstart'];
  19053. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  19054. eventsToTrigger.push('loadedmetadata');
  19055. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  19056. if (el.readyState >= 2) {
  19057. eventsToTrigger.push('loadeddata');
  19058. }
  19059. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  19060. if (el.readyState >= 3) {
  19061. eventsToTrigger.push('canplay');
  19062. }
  19063. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  19064. if (el.readyState >= 4) {
  19065. eventsToTrigger.push('canplaythrough');
  19066. }
  19067. // We still need to give the player time to add event listeners
  19068. this.ready(function () {
  19069. eventsToTrigger.forEach(function (type) {
  19070. this.trigger(type);
  19071. }, this);
  19072. });
  19073. }
  19074. /**
  19075. * Set whether we are scrubbing or not.
  19076. * This is used to decide whether we should use `fastSeek` or not.
  19077. * `fastSeek` is used to provide trick play on Safari browsers.
  19078. *
  19079. * @param {boolean} isScrubbing
  19080. * - true for we are currently scrubbing
  19081. * - false for we are no longer scrubbing
  19082. */
  19083. setScrubbing(isScrubbing) {
  19084. this.isScrubbing_ = isScrubbing;
  19085. }
  19086. /**
  19087. * Get whether we are scrubbing or not.
  19088. *
  19089. * @return {boolean} isScrubbing
  19090. * - true for we are currently scrubbing
  19091. * - false for we are no longer scrubbing
  19092. */
  19093. scrubbing() {
  19094. return this.isScrubbing_;
  19095. }
  19096. /**
  19097. * Set current time for the `HTML5` tech.
  19098. *
  19099. * @param {number} seconds
  19100. * Set the current time of the media to this.
  19101. */
  19102. setCurrentTime(seconds) {
  19103. try {
  19104. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  19105. this.el_.fastSeek(seconds);
  19106. } else {
  19107. this.el_.currentTime = seconds;
  19108. }
  19109. } catch (e) {
  19110. log(e, 'Video is not ready. (Video.js)');
  19111. // this.warning(VideoJS.warnings.videoNotReady);
  19112. }
  19113. }
  19114. /**
  19115. * Get the current duration of the HTML5 media element.
  19116. *
  19117. * @return {number}
  19118. * The duration of the media or 0 if there is no duration.
  19119. */
  19120. duration() {
  19121. // Android Chrome will report duration as Infinity for VOD HLS until after
  19122. // playback has started, which triggers the live display erroneously.
  19123. // Return NaN if playback has not started and trigger a durationupdate once
  19124. // the duration can be reliably known.
  19125. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  19126. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  19127. // several with 0
  19128. const checkProgress = () => {
  19129. if (this.el_.currentTime > 0) {
  19130. // Trigger durationchange for genuinely live video
  19131. if (this.el_.duration === Infinity) {
  19132. this.trigger('durationchange');
  19133. }
  19134. this.off('timeupdate', checkProgress);
  19135. }
  19136. };
  19137. this.on('timeupdate', checkProgress);
  19138. return NaN;
  19139. }
  19140. return this.el_.duration || NaN;
  19141. }
  19142. /**
  19143. * Get the current width of the HTML5 media element.
  19144. *
  19145. * @return {number}
  19146. * The width of the HTML5 media element.
  19147. */
  19148. width() {
  19149. return this.el_.offsetWidth;
  19150. }
  19151. /**
  19152. * Get the current height of the HTML5 media element.
  19153. *
  19154. * @return {number}
  19155. * The height of the HTML5 media element.
  19156. */
  19157. height() {
  19158. return this.el_.offsetHeight;
  19159. }
  19160. /**
  19161. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  19162. * `fullscreenchange` event.
  19163. *
  19164. * @private
  19165. * @fires fullscreenchange
  19166. * @listens webkitendfullscreen
  19167. * @listens webkitbeginfullscreen
  19168. * @listens webkitbeginfullscreen
  19169. */
  19170. proxyWebkitFullscreen_() {
  19171. if (!('webkitDisplayingFullscreen' in this.el_)) {
  19172. return;
  19173. }
  19174. const endFn = function () {
  19175. this.trigger('fullscreenchange', {
  19176. isFullscreen: false
  19177. });
  19178. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  19179. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  19180. this.el_.controls = false;
  19181. }
  19182. };
  19183. const beginFn = function () {
  19184. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  19185. this.one('webkitendfullscreen', endFn);
  19186. this.trigger('fullscreenchange', {
  19187. isFullscreen: true,
  19188. // set a flag in case another tech triggers fullscreenchange
  19189. nativeIOSFullscreen: true
  19190. });
  19191. }
  19192. };
  19193. this.on('webkitbeginfullscreen', beginFn);
  19194. this.on('dispose', () => {
  19195. this.off('webkitbeginfullscreen', beginFn);
  19196. this.off('webkitendfullscreen', endFn);
  19197. });
  19198. }
  19199. /**
  19200. * Check if fullscreen is supported on the video el.
  19201. *
  19202. * @return {boolean}
  19203. * - True if fullscreen is supported.
  19204. * - False if fullscreen is not supported.
  19205. */
  19206. supportsFullScreen() {
  19207. return typeof this.el_.webkitEnterFullScreen === 'function';
  19208. }
  19209. /**
  19210. * Request that the `HTML5` Tech enter fullscreen.
  19211. */
  19212. enterFullScreen() {
  19213. const video = this.el_;
  19214. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  19215. // attempt to prime the video element for programmatic access
  19216. // this isn't necessary on the desktop but shouldn't hurt
  19217. silencePromise(this.el_.play());
  19218. // playing and pausing synchronously during the transition to fullscreen
  19219. // can get iOS ~6.1 devices into a play/pause loop
  19220. this.setTimeout(function () {
  19221. video.pause();
  19222. try {
  19223. video.webkitEnterFullScreen();
  19224. } catch (e) {
  19225. this.trigger('fullscreenerror', e);
  19226. }
  19227. }, 0);
  19228. } else {
  19229. try {
  19230. video.webkitEnterFullScreen();
  19231. } catch (e) {
  19232. this.trigger('fullscreenerror', e);
  19233. }
  19234. }
  19235. }
  19236. /**
  19237. * Request that the `HTML5` Tech exit fullscreen.
  19238. */
  19239. exitFullScreen() {
  19240. if (!this.el_.webkitDisplayingFullscreen) {
  19241. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  19242. return;
  19243. }
  19244. this.el_.webkitExitFullScreen();
  19245. }
  19246. /**
  19247. * Create a floating video window always on top of other windows so that users may
  19248. * continue consuming media while they interact with other content sites, or
  19249. * applications on their device.
  19250. *
  19251. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  19252. *
  19253. * @return {Promise}
  19254. * A promise with a Picture-in-Picture window.
  19255. */
  19256. requestPictureInPicture() {
  19257. return this.el_.requestPictureInPicture();
  19258. }
  19259. /**
  19260. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  19261. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  19262. * Needs to be checked later than the constructor
  19263. * This will be a false positive for clear sources loaded after a Fairplay source
  19264. *
  19265. * @param {function} cb function to call
  19266. * @return {number} id of request
  19267. */
  19268. requestVideoFrameCallback(cb) {
  19269. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19270. return this.el_.requestVideoFrameCallback(cb);
  19271. }
  19272. return super.requestVideoFrameCallback(cb);
  19273. }
  19274. /**
  19275. * Native or fallback requestVideoFrameCallback
  19276. *
  19277. * @param {number} id request id to cancel
  19278. */
  19279. cancelVideoFrameCallback(id) {
  19280. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19281. this.el_.cancelVideoFrameCallback(id);
  19282. } else {
  19283. super.cancelVideoFrameCallback(id);
  19284. }
  19285. }
  19286. /**
  19287. * A getter/setter for the `Html5` Tech's source object.
  19288. * > Note: Please use {@link Html5#setSource}
  19289. *
  19290. * @param {Tech~SourceObject} [src]
  19291. * The source object you want to set on the `HTML5` techs element.
  19292. *
  19293. * @return {Tech~SourceObject|undefined}
  19294. * - The current source object when a source is not passed in.
  19295. * - undefined when setting
  19296. *
  19297. * @deprecated Since version 5.
  19298. */
  19299. src(src) {
  19300. if (src === undefined) {
  19301. return this.el_.src;
  19302. }
  19303. // Setting src through `src` instead of `setSrc` will be deprecated
  19304. this.setSrc(src);
  19305. }
  19306. /**
  19307. * Reset the tech by removing all sources and then calling
  19308. * {@link Html5.resetMediaElement}.
  19309. */
  19310. reset() {
  19311. Html5.resetMediaElement(this.el_);
  19312. }
  19313. /**
  19314. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  19315. * the HTML5 media element.
  19316. *
  19317. * @return {Tech~SourceObject}
  19318. * The current source object from the HTML5 tech. With a fallback to the
  19319. * elements source.
  19320. */
  19321. currentSrc() {
  19322. if (this.currentSource_) {
  19323. return this.currentSource_.src;
  19324. }
  19325. return this.el_.currentSrc;
  19326. }
  19327. /**
  19328. * Set controls attribute for the HTML5 media Element.
  19329. *
  19330. * @param {string} val
  19331. * Value to set the controls attribute to
  19332. */
  19333. setControls(val) {
  19334. this.el_.controls = !!val;
  19335. }
  19336. /**
  19337. * Create and returns a remote {@link TextTrack} object.
  19338. *
  19339. * @param {string} kind
  19340. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  19341. *
  19342. * @param {string} [label]
  19343. * Label to identify the text track
  19344. *
  19345. * @param {string} [language]
  19346. * Two letter language abbreviation
  19347. *
  19348. * @return {TextTrack}
  19349. * The TextTrack that gets created.
  19350. */
  19351. addTextTrack(kind, label, language) {
  19352. if (!this.featuresNativeTextTracks) {
  19353. return super.addTextTrack(kind, label, language);
  19354. }
  19355. return this.el_.addTextTrack(kind, label, language);
  19356. }
  19357. /**
  19358. * Creates either native TextTrack or an emulated TextTrack depending
  19359. * on the value of `featuresNativeTextTracks`
  19360. *
  19361. * @param {Object} options
  19362. * The object should contain the options to initialize the TextTrack with.
  19363. *
  19364. * @param {string} [options.kind]
  19365. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  19366. *
  19367. * @param {string} [options.label]
  19368. * Label to identify the text track
  19369. *
  19370. * @param {string} [options.language]
  19371. * Two letter language abbreviation.
  19372. *
  19373. * @param {boolean} [options.default]
  19374. * Default this track to on.
  19375. *
  19376. * @param {string} [options.id]
  19377. * The internal id to assign this track.
  19378. *
  19379. * @param {string} [options.src]
  19380. * A source url for the track.
  19381. *
  19382. * @return {HTMLTrackElement}
  19383. * The track element that gets created.
  19384. */
  19385. createRemoteTextTrack(options) {
  19386. if (!this.featuresNativeTextTracks) {
  19387. return super.createRemoteTextTrack(options);
  19388. }
  19389. const htmlTrackElement = document.createElement('track');
  19390. if (options.kind) {
  19391. htmlTrackElement.kind = options.kind;
  19392. }
  19393. if (options.label) {
  19394. htmlTrackElement.label = options.label;
  19395. }
  19396. if (options.language || options.srclang) {
  19397. htmlTrackElement.srclang = options.language || options.srclang;
  19398. }
  19399. if (options.default) {
  19400. htmlTrackElement.default = options.default;
  19401. }
  19402. if (options.id) {
  19403. htmlTrackElement.id = options.id;
  19404. }
  19405. if (options.src) {
  19406. htmlTrackElement.src = options.src;
  19407. }
  19408. return htmlTrackElement;
  19409. }
  19410. /**
  19411. * Creates a remote text track object and returns an html track element.
  19412. *
  19413. * @param {Object} options The object should contain values for
  19414. * kind, language, label, and src (location of the WebVTT file)
  19415. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  19416. * will not be removed from the TextTrackList and HtmlTrackElementList
  19417. * after a source change
  19418. * @return {HTMLTrackElement} An Html Track Element.
  19419. * This can be an emulated {@link HTMLTrackElement} or a native one.
  19420. *
  19421. */
  19422. addRemoteTextTrack(options, manualCleanup) {
  19423. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  19424. if (this.featuresNativeTextTracks) {
  19425. this.el().appendChild(htmlTrackElement);
  19426. }
  19427. return htmlTrackElement;
  19428. }
  19429. /**
  19430. * Remove remote `TextTrack` from `TextTrackList` object
  19431. *
  19432. * @param {TextTrack} track
  19433. * `TextTrack` object to remove
  19434. */
  19435. removeRemoteTextTrack(track) {
  19436. super.removeRemoteTextTrack(track);
  19437. if (this.featuresNativeTextTracks) {
  19438. const tracks = this.$$('track');
  19439. let i = tracks.length;
  19440. while (i--) {
  19441. if (track === tracks[i] || track === tracks[i].track) {
  19442. this.el().removeChild(tracks[i]);
  19443. }
  19444. }
  19445. }
  19446. }
  19447. /**
  19448. * Gets available media playback quality metrics as specified by the W3C's Media
  19449. * Playback Quality API.
  19450. *
  19451. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  19452. *
  19453. * @return {Object}
  19454. * An object with supported media playback quality metrics
  19455. */
  19456. getVideoPlaybackQuality() {
  19457. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  19458. return this.el().getVideoPlaybackQuality();
  19459. }
  19460. const videoPlaybackQuality = {};
  19461. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  19462. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  19463. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  19464. }
  19465. if (window.performance) {
  19466. videoPlaybackQuality.creationTime = window.performance.now();
  19467. }
  19468. return videoPlaybackQuality;
  19469. }
  19470. }
  19471. /* HTML5 Support Testing ---------------------------------------------------- */
  19472. /**
  19473. * Element for testing browser HTML5 media capabilities
  19474. *
  19475. * @type {Element}
  19476. * @constant
  19477. * @private
  19478. */
  19479. defineLazyProperty(Html5, 'TEST_VID', function () {
  19480. if (!isReal()) {
  19481. return;
  19482. }
  19483. const video = document.createElement('video');
  19484. const track = document.createElement('track');
  19485. track.kind = 'captions';
  19486. track.srclang = 'en';
  19487. track.label = 'English';
  19488. video.appendChild(track);
  19489. return video;
  19490. });
  19491. /**
  19492. * Check if HTML5 media is supported by this browser/device.
  19493. *
  19494. * @return {boolean}
  19495. * - True if HTML5 media is supported.
  19496. * - False if HTML5 media is not supported.
  19497. */
  19498. Html5.isSupported = function () {
  19499. // IE with no Media Player is a LIAR! (#984)
  19500. try {
  19501. Html5.TEST_VID.volume = 0.5;
  19502. } catch (e) {
  19503. return false;
  19504. }
  19505. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  19506. };
  19507. /**
  19508. * Check if the tech can support the given type
  19509. *
  19510. * @param {string} type
  19511. * The mimetype to check
  19512. * @return {string} 'probably', 'maybe', or '' (empty string)
  19513. */
  19514. Html5.canPlayType = function (type) {
  19515. return Html5.TEST_VID.canPlayType(type);
  19516. };
  19517. /**
  19518. * Check if the tech can support the given source
  19519. *
  19520. * @param {Object} srcObj
  19521. * The source object
  19522. * @param {Object} options
  19523. * The options passed to the tech
  19524. * @return {string} 'probably', 'maybe', or '' (empty string)
  19525. */
  19526. Html5.canPlaySource = function (srcObj, options) {
  19527. return Html5.canPlayType(srcObj.type);
  19528. };
  19529. /**
  19530. * Check if the volume can be changed in this browser/device.
  19531. * Volume cannot be changed in a lot of mobile devices.
  19532. * Specifically, it can't be changed from 1 on iOS.
  19533. *
  19534. * @return {boolean}
  19535. * - True if volume can be controlled
  19536. * - False otherwise
  19537. */
  19538. Html5.canControlVolume = function () {
  19539. // IE will error if Windows Media Player not installed #3315
  19540. try {
  19541. const volume = Html5.TEST_VID.volume;
  19542. Html5.TEST_VID.volume = volume / 2 + 0.1;
  19543. const canControl = volume !== Html5.TEST_VID.volume;
  19544. // With the introduction of iOS 15, there are cases where the volume is read as
  19545. // changed but reverts back to its original state at the start of the next tick.
  19546. // To determine whether volume can be controlled on iOS,
  19547. // a timeout is set and the volume is checked asynchronously.
  19548. // Since `features` doesn't currently work asynchronously, the value is manually set.
  19549. if (canControl && IS_IOS) {
  19550. window.setTimeout(() => {
  19551. if (Html5 && Html5.prototype) {
  19552. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  19553. }
  19554. });
  19555. // default iOS to false, which will be updated in the timeout above.
  19556. return false;
  19557. }
  19558. return canControl;
  19559. } catch (e) {
  19560. return false;
  19561. }
  19562. };
  19563. /**
  19564. * Check if the volume can be muted in this browser/device.
  19565. * Some devices, e.g. iOS, don't allow changing volume
  19566. * but permits muting/unmuting.
  19567. *
  19568. * @return {boolean}
  19569. * - True if volume can be muted
  19570. * - False otherwise
  19571. */
  19572. Html5.canMuteVolume = function () {
  19573. try {
  19574. const muted = Html5.TEST_VID.muted;
  19575. // in some versions of iOS muted property doesn't always
  19576. // work, so we want to set both property and attribute
  19577. Html5.TEST_VID.muted = !muted;
  19578. if (Html5.TEST_VID.muted) {
  19579. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  19580. } else {
  19581. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  19582. }
  19583. return muted !== Html5.TEST_VID.muted;
  19584. } catch (e) {
  19585. return false;
  19586. }
  19587. };
  19588. /**
  19589. * Check if the playback rate can be changed in this browser/device.
  19590. *
  19591. * @return {boolean}
  19592. * - True if playback rate can be controlled
  19593. * - False otherwise
  19594. */
  19595. Html5.canControlPlaybackRate = function () {
  19596. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  19597. // https://github.com/videojs/video.js/issues/3180
  19598. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  19599. return false;
  19600. }
  19601. // IE will error if Windows Media Player not installed #3315
  19602. try {
  19603. const playbackRate = Html5.TEST_VID.playbackRate;
  19604. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  19605. return playbackRate !== Html5.TEST_VID.playbackRate;
  19606. } catch (e) {
  19607. return false;
  19608. }
  19609. };
  19610. /**
  19611. * Check if we can override a video/audio elements attributes, with
  19612. * Object.defineProperty.
  19613. *
  19614. * @return {boolean}
  19615. * - True if builtin attributes can be overridden
  19616. * - False otherwise
  19617. */
  19618. Html5.canOverrideAttributes = function () {
  19619. // if we cannot overwrite the src/innerHTML property, there is no support
  19620. // iOS 7 safari for instance cannot do this.
  19621. try {
  19622. const noop = () => {};
  19623. Object.defineProperty(document.createElement('video'), 'src', {
  19624. get: noop,
  19625. set: noop
  19626. });
  19627. Object.defineProperty(document.createElement('audio'), 'src', {
  19628. get: noop,
  19629. set: noop
  19630. });
  19631. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  19632. get: noop,
  19633. set: noop
  19634. });
  19635. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  19636. get: noop,
  19637. set: noop
  19638. });
  19639. } catch (e) {
  19640. return false;
  19641. }
  19642. return true;
  19643. };
  19644. /**
  19645. * Check to see if native `TextTrack`s are supported by this browser/device.
  19646. *
  19647. * @return {boolean}
  19648. * - True if native `TextTrack`s are supported.
  19649. * - False otherwise
  19650. */
  19651. Html5.supportsNativeTextTracks = function () {
  19652. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  19653. };
  19654. /**
  19655. * Check to see if native `VideoTrack`s are supported by this browser/device
  19656. *
  19657. * @return {boolean}
  19658. * - True if native `VideoTrack`s are supported.
  19659. * - False otherwise
  19660. */
  19661. Html5.supportsNativeVideoTracks = function () {
  19662. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  19663. };
  19664. /**
  19665. * Check to see if native `AudioTrack`s are supported by this browser/device
  19666. *
  19667. * @return {boolean}
  19668. * - True if native `AudioTrack`s are supported.
  19669. * - False otherwise
  19670. */
  19671. Html5.supportsNativeAudioTracks = function () {
  19672. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  19673. };
  19674. /**
  19675. * An array of events available on the Html5 tech.
  19676. *
  19677. * @private
  19678. * @type {Array}
  19679. */
  19680. 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'];
  19681. /**
  19682. * Boolean indicating whether the `Tech` supports volume control.
  19683. *
  19684. * @type {boolean}
  19685. * @default {@link Html5.canControlVolume}
  19686. */
  19687. /**
  19688. * Boolean indicating whether the `Tech` supports muting volume.
  19689. *
  19690. * @type {boolean}
  19691. * @default {@link Html5.canMuteVolume}
  19692. */
  19693. /**
  19694. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  19695. * plays. Examples:
  19696. * - Set player to play 2x (twice) as fast
  19697. * - Set player to play 0.5x (half) as fast
  19698. *
  19699. * @type {boolean}
  19700. * @default {@link Html5.canControlPlaybackRate}
  19701. */
  19702. /**
  19703. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  19704. *
  19705. * @type {boolean}
  19706. * @default
  19707. */
  19708. /**
  19709. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  19710. *
  19711. * @type {boolean}
  19712. * @default {@link Html5.supportsNativeTextTracks}
  19713. */
  19714. /**
  19715. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  19716. *
  19717. * @type {boolean}
  19718. * @default {@link Html5.supportsNativeVideoTracks}
  19719. */
  19720. /**
  19721. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  19722. *
  19723. * @type {boolean}
  19724. * @default {@link Html5.supportsNativeAudioTracks}
  19725. */
  19726. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  19727. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  19728. });
  19729. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  19730. /**
  19731. * Boolean indicating whether the `HTML5` tech currently supports the media element
  19732. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  19733. * false there. Everywhere else this should be true.
  19734. *
  19735. * @type {boolean}
  19736. * @default
  19737. */
  19738. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  19739. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  19740. // Is this true?
  19741. /**
  19742. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  19743. * when going into fullscreen.
  19744. *
  19745. * @type {boolean}
  19746. * @default
  19747. */
  19748. Html5.prototype.featuresFullscreenResize = true;
  19749. /**
  19750. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  19751. * If this is false, manual `progress` events will be triggered instead.
  19752. *
  19753. * @type {boolean}
  19754. * @default
  19755. */
  19756. Html5.prototype.featuresProgressEvents = true;
  19757. /**
  19758. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  19759. * If this is false, manual `timeupdate` events will be triggered instead.
  19760. *
  19761. * @default
  19762. */
  19763. Html5.prototype.featuresTimeupdateEvents = true;
  19764. /**
  19765. * Whether the HTML5 el supports `requestVideoFrameCallback`
  19766. *
  19767. * @type {boolean}
  19768. */
  19769. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  19770. Html5.disposeMediaElement = function (el) {
  19771. if (!el) {
  19772. return;
  19773. }
  19774. if (el.parentNode) {
  19775. el.parentNode.removeChild(el);
  19776. }
  19777. // remove any child track or source nodes to prevent their loading
  19778. while (el.hasChildNodes()) {
  19779. el.removeChild(el.firstChild);
  19780. }
  19781. // remove any src reference. not setting `src=''` because that causes a warning
  19782. // in firefox
  19783. el.removeAttribute('src');
  19784. // force the media element to update its loading state by calling load()
  19785. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  19786. if (typeof el.load === 'function') {
  19787. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  19788. (function () {
  19789. try {
  19790. el.load();
  19791. } catch (e) {
  19792. // not supported
  19793. }
  19794. })();
  19795. }
  19796. };
  19797. Html5.resetMediaElement = function (el) {
  19798. if (!el) {
  19799. return;
  19800. }
  19801. const sources = el.querySelectorAll('source');
  19802. let i = sources.length;
  19803. while (i--) {
  19804. el.removeChild(sources[i]);
  19805. }
  19806. // remove any src reference.
  19807. // not setting `src=''` because that throws an error
  19808. el.removeAttribute('src');
  19809. if (typeof el.load === 'function') {
  19810. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  19811. (function () {
  19812. try {
  19813. el.load();
  19814. } catch (e) {
  19815. // satisfy linter
  19816. }
  19817. })();
  19818. }
  19819. };
  19820. /* Native HTML5 element property wrapping ----------------------------------- */
  19821. // Wrap native boolean attributes with getters that check both property and attribute
  19822. // The list is as followed:
  19823. // muted, defaultMuted, autoplay, controls, loop, playsinline
  19824. [
  19825. /**
  19826. * Get the value of `muted` from the media element. `muted` indicates
  19827. * that the volume for the media should be set to silent. This does not actually change
  19828. * the `volume` attribute.
  19829. *
  19830. * @method Html5#muted
  19831. * @return {boolean}
  19832. * - True if the value of `volume` should be ignored and the audio set to silent.
  19833. * - False if the value of `volume` should be used.
  19834. *
  19835. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  19836. */
  19837. 'muted',
  19838. /**
  19839. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  19840. * whether the media should start muted or not. Only changes the default state of the
  19841. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  19842. * current state.
  19843. *
  19844. * @method Html5#defaultMuted
  19845. * @return {boolean}
  19846. * - The value of `defaultMuted` from the media element.
  19847. * - True indicates that the media should start muted.
  19848. * - False indicates that the media should not start muted
  19849. *
  19850. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  19851. */
  19852. 'defaultMuted',
  19853. /**
  19854. * Get the value of `autoplay` from the media element. `autoplay` indicates
  19855. * that the media should start to play as soon as the page is ready.
  19856. *
  19857. * @method Html5#autoplay
  19858. * @return {boolean}
  19859. * - The value of `autoplay` from the media element.
  19860. * - True indicates that the media should start as soon as the page loads.
  19861. * - False indicates that the media should not start as soon as the page loads.
  19862. *
  19863. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  19864. */
  19865. 'autoplay',
  19866. /**
  19867. * Get the value of `controls` from the media element. `controls` indicates
  19868. * whether the native media controls should be shown or hidden.
  19869. *
  19870. * @method Html5#controls
  19871. * @return {boolean}
  19872. * - The value of `controls` from the media element.
  19873. * - True indicates that native controls should be showing.
  19874. * - False indicates that native controls should be hidden.
  19875. *
  19876. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  19877. */
  19878. 'controls',
  19879. /**
  19880. * Get the value of `loop` from the media element. `loop` indicates
  19881. * that the media should return to the start of the media and continue playing once
  19882. * it reaches the end.
  19883. *
  19884. * @method Html5#loop
  19885. * @return {boolean}
  19886. * - The value of `loop` from the media element.
  19887. * - True indicates that playback should seek back to start once
  19888. * the end of a media is reached.
  19889. * - False indicates that playback should not loop back to the start when the
  19890. * end of the media is reached.
  19891. *
  19892. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  19893. */
  19894. 'loop',
  19895. /**
  19896. * Get the value of `playsinline` from the media element. `playsinline` indicates
  19897. * to the browser that non-fullscreen playback is preferred when fullscreen
  19898. * playback is the native default, such as in iOS Safari.
  19899. *
  19900. * @method Html5#playsinline
  19901. * @return {boolean}
  19902. * - The value of `playsinline` from the media element.
  19903. * - True indicates that the media should play inline.
  19904. * - False indicates that the media should not play inline.
  19905. *
  19906. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  19907. */
  19908. 'playsinline'].forEach(function (prop) {
  19909. Html5.prototype[prop] = function () {
  19910. return this.el_[prop] || this.el_.hasAttribute(prop);
  19911. };
  19912. });
  19913. // Wrap native boolean attributes with setters that set both property and attribute
  19914. // The list is as followed:
  19915. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  19916. // setControls is special-cased above
  19917. [
  19918. /**
  19919. * Set the value of `muted` on the media element. `muted` indicates that the current
  19920. * audio level should be silent.
  19921. *
  19922. * @method Html5#setMuted
  19923. * @param {boolean} muted
  19924. * - True if the audio should be set to silent
  19925. * - False otherwise
  19926. *
  19927. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  19928. */
  19929. 'muted',
  19930. /**
  19931. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  19932. * audio level should be silent, but will only effect the muted level on initial playback..
  19933. *
  19934. * @method Html5.prototype.setDefaultMuted
  19935. * @param {boolean} defaultMuted
  19936. * - True if the audio should be set to silent
  19937. * - False otherwise
  19938. *
  19939. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  19940. */
  19941. 'defaultMuted',
  19942. /**
  19943. * Set the value of `autoplay` on the media element. `autoplay` indicates
  19944. * that the media should start to play as soon as the page is ready.
  19945. *
  19946. * @method Html5#setAutoplay
  19947. * @param {boolean} autoplay
  19948. * - True indicates that the media should start as soon as the page loads.
  19949. * - False indicates that the media should not start as soon as the page loads.
  19950. *
  19951. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  19952. */
  19953. 'autoplay',
  19954. /**
  19955. * Set the value of `loop` on the media element. `loop` indicates
  19956. * that the media should return to the start of the media and continue playing once
  19957. * it reaches the end.
  19958. *
  19959. * @method Html5#setLoop
  19960. * @param {boolean} loop
  19961. * - True indicates that playback should seek back to start once
  19962. * the end of a media is reached.
  19963. * - False indicates that playback should not loop back to the start when the
  19964. * end of the media is reached.
  19965. *
  19966. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  19967. */
  19968. 'loop',
  19969. /**
  19970. * Set the value of `playsinline` from the media element. `playsinline` indicates
  19971. * to the browser that non-fullscreen playback is preferred when fullscreen
  19972. * playback is the native default, such as in iOS Safari.
  19973. *
  19974. * @method Html5#setPlaysinline
  19975. * @param {boolean} playsinline
  19976. * - True indicates that the media should play inline.
  19977. * - False indicates that the media should not play inline.
  19978. *
  19979. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  19980. */
  19981. 'playsinline'].forEach(function (prop) {
  19982. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  19983. this.el_[prop] = v;
  19984. if (v) {
  19985. this.el_.setAttribute(prop, prop);
  19986. } else {
  19987. this.el_.removeAttribute(prop);
  19988. }
  19989. };
  19990. });
  19991. // Wrap native properties with a getter
  19992. // The list is as followed
  19993. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  19994. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  19995. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  19996. [
  19997. /**
  19998. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  19999. * is currently paused or not.
  20000. *
  20001. * @method Html5#paused
  20002. * @return {boolean}
  20003. * The value of `paused` from the media element.
  20004. *
  20005. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  20006. */
  20007. 'paused',
  20008. /**
  20009. * Get the value of `currentTime` from the media element. `currentTime` indicates
  20010. * the current second that the media is at in playback.
  20011. *
  20012. * @method Html5#currentTime
  20013. * @return {number}
  20014. * The value of `currentTime` from the media element.
  20015. *
  20016. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  20017. */
  20018. 'currentTime',
  20019. /**
  20020. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  20021. * object that represents the parts of the media that are already downloaded and
  20022. * available for playback.
  20023. *
  20024. * @method Html5#buffered
  20025. * @return {TimeRange}
  20026. * The value of `buffered` from the media element.
  20027. *
  20028. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  20029. */
  20030. 'buffered',
  20031. /**
  20032. * Get the value of `volume` from the media element. `volume` indicates
  20033. * the current playback volume of audio for a media. `volume` will be a value from 0
  20034. * (silent) to 1 (loudest and default).
  20035. *
  20036. * @method Html5#volume
  20037. * @return {number}
  20038. * The value of `volume` from the media element. Value will be between 0-1.
  20039. *
  20040. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20041. */
  20042. 'volume',
  20043. /**
  20044. * Get the value of `poster` from the media element. `poster` indicates
  20045. * that the url of an image file that can/will be shown when no media data is available.
  20046. *
  20047. * @method Html5#poster
  20048. * @return {string}
  20049. * The value of `poster` from the media element. Value will be a url to an
  20050. * image.
  20051. *
  20052. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  20053. */
  20054. 'poster',
  20055. /**
  20056. * Get the value of `preload` from the media element. `preload` indicates
  20057. * what should download before the media is interacted with. It can have the following
  20058. * values:
  20059. * - none: nothing should be downloaded
  20060. * - metadata: poster and the first few frames of the media may be downloaded to get
  20061. * media dimensions and other metadata
  20062. * - auto: allow the media and metadata for the media to be downloaded before
  20063. * interaction
  20064. *
  20065. * @method Html5#preload
  20066. * @return {string}
  20067. * The value of `preload` from the media element. Will be 'none', 'metadata',
  20068. * or 'auto'.
  20069. *
  20070. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20071. */
  20072. 'preload',
  20073. /**
  20074. * Get the value of the `error` from the media element. `error` indicates any
  20075. * MediaError that may have occurred during playback. If error returns null there is no
  20076. * current error.
  20077. *
  20078. * @method Html5#error
  20079. * @return {MediaError|null}
  20080. * The value of `error` from the media element. Will be `MediaError` if there
  20081. * is a current error and null otherwise.
  20082. *
  20083. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  20084. */
  20085. 'error',
  20086. /**
  20087. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  20088. * media is currently seeking to a new position or not.
  20089. *
  20090. * @method Html5#seeking
  20091. * @return {boolean}
  20092. * - The value of `seeking` from the media element.
  20093. * - True indicates that the media is currently seeking to a new position.
  20094. * - False indicates that the media is not seeking to a new position at this time.
  20095. *
  20096. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  20097. */
  20098. 'seeking',
  20099. /**
  20100. * Get the value of `seekable` from the media element. `seekable` returns a
  20101. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  20102. *
  20103. * @method Html5#seekable
  20104. * @return {TimeRange}
  20105. * The value of `seekable` from the media element. A `TimeRange` object
  20106. * indicating the current ranges of time that can be seeked to.
  20107. *
  20108. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  20109. */
  20110. 'seekable',
  20111. /**
  20112. * Get the value of `ended` from the media element. `ended` indicates whether
  20113. * the media has reached the end or not.
  20114. *
  20115. * @method Html5#ended
  20116. * @return {boolean}
  20117. * - The value of `ended` from the media element.
  20118. * - True indicates that the media has ended.
  20119. * - False indicates that the media has not ended.
  20120. *
  20121. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  20122. */
  20123. 'ended',
  20124. /**
  20125. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  20126. * the rate at which the media is currently playing back. Examples:
  20127. * - if playbackRate is set to 2, media will play twice as fast.
  20128. * - if playbackRate is set to 0.5, media will play half as fast.
  20129. *
  20130. * @method Html5#playbackRate
  20131. * @return {number}
  20132. * The value of `playbackRate` from the media element. A number indicating
  20133. * the current playback speed of the media, where 1 is normal speed.
  20134. *
  20135. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20136. */
  20137. 'playbackRate',
  20138. /**
  20139. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  20140. * the rate at which the media is currently playing back. This value will not indicate the current
  20141. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  20142. *
  20143. * Examples:
  20144. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  20145. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  20146. *
  20147. * @method Html5.prototype.defaultPlaybackRate
  20148. * @return {number}
  20149. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20150. * the current playback speed of the media, where 1 is normal speed.
  20151. *
  20152. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20153. */
  20154. 'defaultPlaybackRate',
  20155. /**
  20156. * Get the value of 'disablePictureInPicture' from the video element.
  20157. *
  20158. * @method Html5#disablePictureInPicture
  20159. * @return {boolean} value
  20160. * - The value of `disablePictureInPicture` from the video element.
  20161. * - True indicates that the video can't be played in Picture-In-Picture mode
  20162. * - False indicates that the video can be played in Picture-In-Picture mode
  20163. *
  20164. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20165. */
  20166. 'disablePictureInPicture',
  20167. /**
  20168. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  20169. * object representing points in the media timeline that have been played.
  20170. *
  20171. * @method Html5#played
  20172. * @return {TimeRange}
  20173. * The value of `played` from the media element. A `TimeRange` object indicating
  20174. * the ranges of time that have been played.
  20175. *
  20176. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  20177. */
  20178. 'played',
  20179. /**
  20180. * Get the value of `networkState` from the media element. `networkState` indicates
  20181. * the current network state. It returns an enumeration from the following list:
  20182. * - 0: NETWORK_EMPTY
  20183. * - 1: NETWORK_IDLE
  20184. * - 2: NETWORK_LOADING
  20185. * - 3: NETWORK_NO_SOURCE
  20186. *
  20187. * @method Html5#networkState
  20188. * @return {number}
  20189. * The value of `networkState` from the media element. This will be a number
  20190. * from the list in the description.
  20191. *
  20192. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  20193. */
  20194. 'networkState',
  20195. /**
  20196. * Get the value of `readyState` from the media element. `readyState` indicates
  20197. * the current state of the media element. It returns an enumeration from the
  20198. * following list:
  20199. * - 0: HAVE_NOTHING
  20200. * - 1: HAVE_METADATA
  20201. * - 2: HAVE_CURRENT_DATA
  20202. * - 3: HAVE_FUTURE_DATA
  20203. * - 4: HAVE_ENOUGH_DATA
  20204. *
  20205. * @method Html5#readyState
  20206. * @return {number}
  20207. * The value of `readyState` from the media element. This will be a number
  20208. * from the list in the description.
  20209. *
  20210. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  20211. */
  20212. 'readyState',
  20213. /**
  20214. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  20215. * the current width of the video in css pixels.
  20216. *
  20217. * @method Html5#videoWidth
  20218. * @return {number}
  20219. * The value of `videoWidth` from the video element. This will be a number
  20220. * in css pixels.
  20221. *
  20222. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20223. */
  20224. 'videoWidth',
  20225. /**
  20226. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  20227. * the current height of the video in css pixels.
  20228. *
  20229. * @method Html5#videoHeight
  20230. * @return {number}
  20231. * The value of `videoHeight` from the video element. This will be a number
  20232. * in css pixels.
  20233. *
  20234. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20235. */
  20236. 'videoHeight',
  20237. /**
  20238. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20239. * to the browser that should sent the cookies along with the requests for the
  20240. * different assets/playlists
  20241. *
  20242. * @method Html5#crossOrigin
  20243. * @return {string}
  20244. * - anonymous indicates that the media should not sent cookies.
  20245. * - use-credentials indicates that the media should sent cookies along the requests.
  20246. *
  20247. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20248. */
  20249. 'crossOrigin'].forEach(function (prop) {
  20250. Html5.prototype[prop] = function () {
  20251. return this.el_[prop];
  20252. };
  20253. });
  20254. // Wrap native properties with a setter in this format:
  20255. // set + toTitleCase(name)
  20256. // The list is as follows:
  20257. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  20258. // setDisablePictureInPicture, setCrossOrigin
  20259. [
  20260. /**
  20261. * Set the value of `volume` on the media element. `volume` indicates the current
  20262. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  20263. * so on.
  20264. *
  20265. * @method Html5#setVolume
  20266. * @param {number} percentAsDecimal
  20267. * The volume percent as a decimal. Valid range is from 0-1.
  20268. *
  20269. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20270. */
  20271. 'volume',
  20272. /**
  20273. * Set the value of `src` on the media element. `src` indicates the current
  20274. * {@link Tech~SourceObject} for the media.
  20275. *
  20276. * @method Html5#setSrc
  20277. * @param {Tech~SourceObject} src
  20278. * The source object to set as the current source.
  20279. *
  20280. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  20281. */
  20282. 'src',
  20283. /**
  20284. * Set the value of `poster` on the media element. `poster` is the url to
  20285. * an image file that can/will be shown when no media data is available.
  20286. *
  20287. * @method Html5#setPoster
  20288. * @param {string} poster
  20289. * The url to an image that should be used as the `poster` for the media
  20290. * element.
  20291. *
  20292. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  20293. */
  20294. 'poster',
  20295. /**
  20296. * Set the value of `preload` on the media element. `preload` indicates
  20297. * what should download before the media is interacted with. It can have the following
  20298. * values:
  20299. * - none: nothing should be downloaded
  20300. * - metadata: poster and the first few frames of the media may be downloaded to get
  20301. * media dimensions and other metadata
  20302. * - auto: allow the media and metadata for the media to be downloaded before
  20303. * interaction
  20304. *
  20305. * @method Html5#setPreload
  20306. * @param {string} preload
  20307. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  20308. * or 'auto'.
  20309. *
  20310. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20311. */
  20312. 'preload',
  20313. /**
  20314. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  20315. * the rate at which the media should play back. Examples:
  20316. * - if playbackRate is set to 2, media will play twice as fast.
  20317. * - if playbackRate is set to 0.5, media will play half as fast.
  20318. *
  20319. * @method Html5#setPlaybackRate
  20320. * @return {number}
  20321. * The value of `playbackRate` from the media element. A number indicating
  20322. * the current playback speed of the media, where 1 is normal speed.
  20323. *
  20324. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20325. */
  20326. 'playbackRate',
  20327. /**
  20328. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  20329. * the rate at which the media should play back upon initial startup. Changing this value
  20330. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  20331. *
  20332. * Example Values:
  20333. * - if playbackRate is set to 2, media will play twice as fast.
  20334. * - if playbackRate is set to 0.5, media will play half as fast.
  20335. *
  20336. * @method Html5.prototype.setDefaultPlaybackRate
  20337. * @return {number}
  20338. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20339. * the current playback speed of the media, where 1 is normal speed.
  20340. *
  20341. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  20342. */
  20343. 'defaultPlaybackRate',
  20344. /**
  20345. * Prevents the browser from suggesting a Picture-in-Picture context menu
  20346. * or to request Picture-in-Picture automatically in some cases.
  20347. *
  20348. * @method Html5#setDisablePictureInPicture
  20349. * @param {boolean} value
  20350. * The true value will disable Picture-in-Picture mode.
  20351. *
  20352. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20353. */
  20354. 'disablePictureInPicture',
  20355. /**
  20356. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20357. * to the browser that should sent the cookies along with the requests for the
  20358. * different assets/playlists
  20359. *
  20360. * @method Html5#setCrossOrigin
  20361. * @param {string} crossOrigin
  20362. * - anonymous indicates that the media should not sent cookies.
  20363. * - use-credentials indicates that the media should sent cookies along the requests.
  20364. *
  20365. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20366. */
  20367. 'crossOrigin'].forEach(function (prop) {
  20368. Html5.prototype['set' + toTitleCase(prop)] = function (v) {
  20369. this.el_[prop] = v;
  20370. };
  20371. });
  20372. // wrap native functions with a function
  20373. // The list is as follows:
  20374. // pause, load, play
  20375. [
  20376. /**
  20377. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  20378. * media elements `pause` function.
  20379. *
  20380. * @method Html5#pause
  20381. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  20382. */
  20383. 'pause',
  20384. /**
  20385. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  20386. * media element `load` function.
  20387. *
  20388. * @method Html5#load
  20389. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  20390. */
  20391. 'load',
  20392. /**
  20393. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  20394. * media element `play` function.
  20395. *
  20396. * @method Html5#play
  20397. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  20398. */
  20399. 'play'].forEach(function (prop) {
  20400. Html5.prototype[prop] = function () {
  20401. return this.el_[prop]();
  20402. };
  20403. });
  20404. Tech.withSourceHandlers(Html5);
  20405. /**
  20406. * Native source handler for Html5, simply passes the source to the media element.
  20407. *
  20408. * @property {Tech~SourceObject} source
  20409. * The source object
  20410. *
  20411. * @property {Html5} tech
  20412. * The instance of the HTML5 tech.
  20413. */
  20414. Html5.nativeSourceHandler = {};
  20415. /**
  20416. * Check if the media element can play the given mime type.
  20417. *
  20418. * @param {string} type
  20419. * The mimetype to check
  20420. *
  20421. * @return {string}
  20422. * 'probably', 'maybe', or '' (empty string)
  20423. */
  20424. Html5.nativeSourceHandler.canPlayType = function (type) {
  20425. // IE without MediaPlayer throws an error (#519)
  20426. try {
  20427. return Html5.TEST_VID.canPlayType(type);
  20428. } catch (e) {
  20429. return '';
  20430. }
  20431. };
  20432. /**
  20433. * Check if the media element can handle a source natively.
  20434. *
  20435. * @param {Tech~SourceObject} source
  20436. * The source object
  20437. *
  20438. * @param {Object} [options]
  20439. * Options to be passed to the tech.
  20440. *
  20441. * @return {string}
  20442. * 'probably', 'maybe', or '' (empty string).
  20443. */
  20444. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  20445. // If a type was provided we should rely on that
  20446. if (source.type) {
  20447. return Html5.nativeSourceHandler.canPlayType(source.type);
  20448. // If no type, fall back to checking 'video/[EXTENSION]'
  20449. } else if (source.src) {
  20450. const ext = getFileExtension(source.src);
  20451. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  20452. }
  20453. return '';
  20454. };
  20455. /**
  20456. * Pass the source to the native media element.
  20457. *
  20458. * @param {Tech~SourceObject} source
  20459. * The source object
  20460. *
  20461. * @param {Html5} tech
  20462. * The instance of the Html5 tech
  20463. *
  20464. * @param {Object} [options]
  20465. * The options to pass to the source
  20466. */
  20467. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  20468. tech.setSrc(source.src);
  20469. };
  20470. /**
  20471. * A noop for the native dispose function, as cleanup is not needed.
  20472. */
  20473. Html5.nativeSourceHandler.dispose = function () {};
  20474. // Register the native source handler
  20475. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  20476. Tech.registerTech('Html5', Html5);
  20477. /**
  20478. * @file player.js
  20479. */
  20480. // The following tech events are simply re-triggered
  20481. // on the player when they happen
  20482. const TECH_EVENTS_RETRIGGER = [
  20483. /**
  20484. * Fired while the user agent is downloading media data.
  20485. *
  20486. * @event Player#progress
  20487. * @type {Event}
  20488. */
  20489. /**
  20490. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  20491. *
  20492. * @private
  20493. * @method Player#handleTechProgress_
  20494. * @fires Player#progress
  20495. * @listens Tech#progress
  20496. */
  20497. 'progress',
  20498. /**
  20499. * Fires when the loading of an audio/video is aborted.
  20500. *
  20501. * @event Player#abort
  20502. * @type {Event}
  20503. */
  20504. /**
  20505. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  20506. *
  20507. * @private
  20508. * @method Player#handleTechAbort_
  20509. * @fires Player#abort
  20510. * @listens Tech#abort
  20511. */
  20512. 'abort',
  20513. /**
  20514. * Fires when the browser is intentionally not getting media data.
  20515. *
  20516. * @event Player#suspend
  20517. * @type {Event}
  20518. */
  20519. /**
  20520. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  20521. *
  20522. * @private
  20523. * @method Player#handleTechSuspend_
  20524. * @fires Player#suspend
  20525. * @listens Tech#suspend
  20526. */
  20527. 'suspend',
  20528. /**
  20529. * Fires when the current playlist is empty.
  20530. *
  20531. * @event Player#emptied
  20532. * @type {Event}
  20533. */
  20534. /**
  20535. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  20536. *
  20537. * @private
  20538. * @method Player#handleTechEmptied_
  20539. * @fires Player#emptied
  20540. * @listens Tech#emptied
  20541. */
  20542. 'emptied',
  20543. /**
  20544. * Fires when the browser is trying to get media data, but data is not available.
  20545. *
  20546. * @event Player#stalled
  20547. * @type {Event}
  20548. */
  20549. /**
  20550. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  20551. *
  20552. * @private
  20553. * @method Player#handleTechStalled_
  20554. * @fires Player#stalled
  20555. * @listens Tech#stalled
  20556. */
  20557. 'stalled',
  20558. /**
  20559. * Fires when the browser has loaded meta data for the audio/video.
  20560. *
  20561. * @event Player#loadedmetadata
  20562. * @type {Event}
  20563. */
  20564. /**
  20565. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  20566. *
  20567. * @private
  20568. * @method Player#handleTechLoadedmetadata_
  20569. * @fires Player#loadedmetadata
  20570. * @listens Tech#loadedmetadata
  20571. */
  20572. 'loadedmetadata',
  20573. /**
  20574. * Fires when the browser has loaded the current frame of the audio/video.
  20575. *
  20576. * @event Player#loadeddata
  20577. * @type {event}
  20578. */
  20579. /**
  20580. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  20581. *
  20582. * @private
  20583. * @method Player#handleTechLoaddeddata_
  20584. * @fires Player#loadeddata
  20585. * @listens Tech#loadeddata
  20586. */
  20587. 'loadeddata',
  20588. /**
  20589. * Fires when the current playback position has changed.
  20590. *
  20591. * @event Player#timeupdate
  20592. * @type {event}
  20593. */
  20594. /**
  20595. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  20596. *
  20597. * @private
  20598. * @method Player#handleTechTimeUpdate_
  20599. * @fires Player#timeupdate
  20600. * @listens Tech#timeupdate
  20601. */
  20602. 'timeupdate',
  20603. /**
  20604. * Fires when the video's intrinsic dimensions change
  20605. *
  20606. * @event Player#resize
  20607. * @type {event}
  20608. */
  20609. /**
  20610. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  20611. *
  20612. * @private
  20613. * @method Player#handleTechResize_
  20614. * @fires Player#resize
  20615. * @listens Tech#resize
  20616. */
  20617. 'resize',
  20618. /**
  20619. * Fires when the volume has been changed
  20620. *
  20621. * @event Player#volumechange
  20622. * @type {event}
  20623. */
  20624. /**
  20625. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  20626. *
  20627. * @private
  20628. * @method Player#handleTechVolumechange_
  20629. * @fires Player#volumechange
  20630. * @listens Tech#volumechange
  20631. */
  20632. 'volumechange',
  20633. /**
  20634. * Fires when the text track has been changed
  20635. *
  20636. * @event Player#texttrackchange
  20637. * @type {event}
  20638. */
  20639. /**
  20640. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  20641. *
  20642. * @private
  20643. * @method Player#handleTechTexttrackchange_
  20644. * @fires Player#texttrackchange
  20645. * @listens Tech#texttrackchange
  20646. */
  20647. 'texttrackchange'];
  20648. // events to queue when playback rate is zero
  20649. // this is a hash for the sole purpose of mapping non-camel-cased event names
  20650. // to camel-cased function names
  20651. const TECH_EVENTS_QUEUE = {
  20652. canplay: 'CanPlay',
  20653. canplaythrough: 'CanPlayThrough',
  20654. playing: 'Playing',
  20655. seeked: 'Seeked'
  20656. };
  20657. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  20658. const BREAKPOINT_CLASSES = {};
  20659. // grep: vjs-layout-tiny
  20660. // grep: vjs-layout-x-small
  20661. // grep: vjs-layout-small
  20662. // grep: vjs-layout-medium
  20663. // grep: vjs-layout-large
  20664. // grep: vjs-layout-x-large
  20665. // grep: vjs-layout-huge
  20666. BREAKPOINT_ORDER.forEach(k => {
  20667. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  20668. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  20669. });
  20670. const DEFAULT_BREAKPOINTS = {
  20671. tiny: 210,
  20672. xsmall: 320,
  20673. small: 425,
  20674. medium: 768,
  20675. large: 1440,
  20676. xlarge: 2560,
  20677. huge: Infinity
  20678. };
  20679. /**
  20680. * An instance of the `Player` class is created when any of the Video.js setup methods
  20681. * are used to initialize a video.
  20682. *
  20683. * After an instance has been created it can be accessed globally in three ways:
  20684. * 1. By calling `videojs.getPlayer('example_video_1');`
  20685. * 2. By calling `videojs('example_video_1');` (not recomended)
  20686. * 2. By using it directly via `videojs.players.example_video_1;`
  20687. *
  20688. * @extends Component
  20689. * @global
  20690. */
  20691. class Player extends Component {
  20692. /**
  20693. * Create an instance of this class.
  20694. *
  20695. * @param {Element} tag
  20696. * The original video DOM element used for configuring options.
  20697. *
  20698. * @param {Object} [options]
  20699. * Object of option names and values.
  20700. *
  20701. * @param {Function} [ready]
  20702. * Ready callback function.
  20703. */
  20704. constructor(tag, options, ready) {
  20705. // Make sure tag ID exists
  20706. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  20707. // Set Options
  20708. // The options argument overrides options set in the video tag
  20709. // which overrides globally set options.
  20710. // This latter part coincides with the load order
  20711. // (tag must exist before Player)
  20712. options = Object.assign(Player.getTagSettings(tag), options);
  20713. // Delay the initialization of children because we need to set up
  20714. // player properties first, and can't use `this` before `super()`
  20715. options.initChildren = false;
  20716. // Same with creating the element
  20717. options.createEl = false;
  20718. // don't auto mixin the evented mixin
  20719. options.evented = false;
  20720. // we don't want the player to report touch activity on itself
  20721. // see enableTouchActivity in Component
  20722. options.reportTouchActivity = false;
  20723. // If language is not set, get the closest lang attribute
  20724. if (!options.language) {
  20725. const closest = tag.closest('[lang]');
  20726. if (closest) {
  20727. options.language = closest.getAttribute('lang');
  20728. }
  20729. }
  20730. // Run base component initializing with new options
  20731. super(null, options, ready);
  20732. // Create bound methods for document listeners.
  20733. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  20734. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  20735. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  20736. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  20737. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  20738. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  20739. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  20740. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  20741. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  20742. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  20743. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  20744. // default isFullscreen_ to false
  20745. this.isFullscreen_ = false;
  20746. // create logger
  20747. this.log = createLogger(this.id_);
  20748. // Hold our own reference to fullscreen api so it can be mocked in tests
  20749. this.fsApi_ = FullscreenApi;
  20750. // Tracks when a tech changes the poster
  20751. this.isPosterFromTech_ = false;
  20752. // Holds callback info that gets queued when playback rate is zero
  20753. // and a seek is happening
  20754. this.queuedCallbacks_ = [];
  20755. // Turn off API access because we're loading a new tech that might load asynchronously
  20756. this.isReady_ = false;
  20757. // Init state hasStarted_
  20758. this.hasStarted_ = false;
  20759. // Init state userActive_
  20760. this.userActive_ = false;
  20761. // Init debugEnabled_
  20762. this.debugEnabled_ = false;
  20763. // Init state audioOnlyMode_
  20764. this.audioOnlyMode_ = false;
  20765. // Init state audioPosterMode_
  20766. this.audioPosterMode_ = false;
  20767. // Init state audioOnlyCache_
  20768. this.audioOnlyCache_ = {
  20769. playerHeight: null,
  20770. hiddenChildren: []
  20771. };
  20772. // if the global option object was accidentally blown away by
  20773. // someone, bail early with an informative error
  20774. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  20775. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  20776. }
  20777. // Store the original tag used to set options
  20778. this.tag = tag;
  20779. // Store the tag attributes used to restore html5 element
  20780. this.tagAttributes = tag && getAttributes(tag);
  20781. // Update current language
  20782. this.language(this.options_.language);
  20783. // Update Supported Languages
  20784. if (options.languages) {
  20785. // Normalise player option languages to lowercase
  20786. const languagesToLower = {};
  20787. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  20788. languagesToLower[name.toLowerCase()] = options.languages[name];
  20789. });
  20790. this.languages_ = languagesToLower;
  20791. } else {
  20792. this.languages_ = Player.prototype.options_.languages;
  20793. }
  20794. this.resetCache_();
  20795. // Set poster
  20796. this.poster_ = options.poster || '';
  20797. // Set controls
  20798. this.controls_ = !!options.controls;
  20799. // Original tag settings stored in options
  20800. // now remove immediately so native controls don't flash.
  20801. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  20802. tag.controls = false;
  20803. tag.removeAttribute('controls');
  20804. this.changingSrc_ = false;
  20805. this.playCallbacks_ = [];
  20806. this.playTerminatedQueue_ = [];
  20807. // the attribute overrides the option
  20808. if (tag.hasAttribute('autoplay')) {
  20809. this.autoplay(true);
  20810. } else {
  20811. // otherwise use the setter to validate and
  20812. // set the correct value.
  20813. this.autoplay(this.options_.autoplay);
  20814. }
  20815. // check plugins
  20816. if (options.plugins) {
  20817. Object.keys(options.plugins).forEach(name => {
  20818. if (typeof this[name] !== 'function') {
  20819. throw new Error(`plugin "${name}" does not exist`);
  20820. }
  20821. });
  20822. }
  20823. /*
  20824. * Store the internal state of scrubbing
  20825. *
  20826. * @private
  20827. * @return {Boolean} True if the user is scrubbing
  20828. */
  20829. this.scrubbing_ = false;
  20830. this.el_ = this.createEl();
  20831. // Make this an evented object and use `el_` as its event bus.
  20832. evented(this, {
  20833. eventBusKey: 'el_'
  20834. });
  20835. // listen to document and player fullscreenchange handlers so we receive those events
  20836. // before a user can receive them so we can update isFullscreen appropriately.
  20837. // make sure that we listen to fullscreenchange events before everything else to make sure that
  20838. // our isFullscreen method is updated properly for internal components as well as external.
  20839. if (this.fsApi_.requestFullscreen) {
  20840. on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20841. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20842. }
  20843. if (this.fluid_) {
  20844. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  20845. }
  20846. // We also want to pass the original player options to each component and plugin
  20847. // as well so they don't need to reach back into the player for options later.
  20848. // We also need to do another copy of this.options_ so we don't end up with
  20849. // an infinite loop.
  20850. const playerOptionsCopy = merge(this.options_);
  20851. // Load plugins
  20852. if (options.plugins) {
  20853. Object.keys(options.plugins).forEach(name => {
  20854. this[name](options.plugins[name]);
  20855. });
  20856. }
  20857. // Enable debug mode to fire debugon event for all plugins.
  20858. if (options.debug) {
  20859. this.debug(true);
  20860. }
  20861. this.options_.playerOptions = playerOptionsCopy;
  20862. this.middleware_ = [];
  20863. this.playbackRates(options.playbackRates);
  20864. this.initChildren();
  20865. // Set isAudio based on whether or not an audio tag was used
  20866. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  20867. // Update controls className. Can't do this when the controls are initially
  20868. // set because the element doesn't exist yet.
  20869. if (this.controls()) {
  20870. this.addClass('vjs-controls-enabled');
  20871. } else {
  20872. this.addClass('vjs-controls-disabled');
  20873. }
  20874. // Set ARIA label and region role depending on player type
  20875. this.el_.setAttribute('role', 'region');
  20876. if (this.isAudio()) {
  20877. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  20878. } else {
  20879. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  20880. }
  20881. if (this.isAudio()) {
  20882. this.addClass('vjs-audio');
  20883. }
  20884. // TODO: Make this smarter. Toggle user state between touching/mousing
  20885. // using events, since devices can have both touch and mouse events.
  20886. // TODO: Make this check be performed again when the window switches between monitors
  20887. // (See https://github.com/videojs/video.js/issues/5683)
  20888. if (TOUCH_ENABLED) {
  20889. this.addClass('vjs-touch-enabled');
  20890. }
  20891. // iOS Safari has broken hover handling
  20892. if (!IS_IOS) {
  20893. this.addClass('vjs-workinghover');
  20894. }
  20895. // Make player easily findable by ID
  20896. Player.players[this.id_] = this;
  20897. // Add a major version class to aid css in plugins
  20898. const majorVersion = version.split('.')[0];
  20899. this.addClass(`vjs-v${majorVersion}`);
  20900. // When the player is first initialized, trigger activity so components
  20901. // like the control bar show themselves if needed
  20902. this.userActive(true);
  20903. this.reportUserActivity();
  20904. this.one('play', e => this.listenForUserActivity_(e));
  20905. this.on('keydown', e => this.handleKeyDown(e));
  20906. this.on('languagechange', e => this.handleLanguagechange(e));
  20907. this.breakpoints(this.options_.breakpoints);
  20908. this.responsive(this.options_.responsive);
  20909. // Calling both the audio mode methods after the player is fully
  20910. // setup to be able to listen to the events triggered by them
  20911. this.on('ready', () => {
  20912. // Calling the audioPosterMode method first so that
  20913. // the audioOnlyMode can take precedence when both options are set to true
  20914. this.audioPosterMode(this.options_.audioPosterMode);
  20915. this.audioOnlyMode(this.options_.audioOnlyMode);
  20916. });
  20917. }
  20918. /**
  20919. * Destroys the video player and does any necessary cleanup.
  20920. *
  20921. * This is especially helpful if you are dynamically adding and removing videos
  20922. * to/from the DOM.
  20923. *
  20924. * @fires Player#dispose
  20925. */
  20926. dispose() {
  20927. /**
  20928. * Called when the player is being disposed of.
  20929. *
  20930. * @event Player#dispose
  20931. * @type {Event}
  20932. */
  20933. this.trigger('dispose');
  20934. // prevent dispose from being called twice
  20935. this.off('dispose');
  20936. // Make sure all player-specific document listeners are unbound. This is
  20937. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  20938. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  20939. if (this.styleEl_ && this.styleEl_.parentNode) {
  20940. this.styleEl_.parentNode.removeChild(this.styleEl_);
  20941. this.styleEl_ = null;
  20942. }
  20943. // Kill reference to this player
  20944. Player.players[this.id_] = null;
  20945. if (this.tag && this.tag.player) {
  20946. this.tag.player = null;
  20947. }
  20948. if (this.el_ && this.el_.player) {
  20949. this.el_.player = null;
  20950. }
  20951. if (this.tech_) {
  20952. this.tech_.dispose();
  20953. this.isPosterFromTech_ = false;
  20954. this.poster_ = '';
  20955. }
  20956. if (this.playerElIngest_) {
  20957. this.playerElIngest_ = null;
  20958. }
  20959. if (this.tag) {
  20960. this.tag = null;
  20961. }
  20962. clearCacheForPlayer(this);
  20963. // remove all event handlers for track lists
  20964. // all tracks and track listeners are removed on
  20965. // tech dispose
  20966. ALL.names.forEach(name => {
  20967. const props = ALL[name];
  20968. const list = this[props.getterName]();
  20969. // if it is not a native list
  20970. // we have to manually remove event listeners
  20971. if (list && list.off) {
  20972. list.off();
  20973. }
  20974. });
  20975. // the actual .el_ is removed here, or replaced if
  20976. super.dispose({
  20977. restoreEl: this.options_.restoreEl
  20978. });
  20979. }
  20980. /**
  20981. * Create the `Player`'s DOM element.
  20982. *
  20983. * @return {Element}
  20984. * The DOM element that gets created.
  20985. */
  20986. createEl() {
  20987. let tag = this.tag;
  20988. let el;
  20989. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  20990. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  20991. if (playerElIngest) {
  20992. el = this.el_ = tag.parentNode;
  20993. } else if (!divEmbed) {
  20994. el = this.el_ = super.createEl('div');
  20995. }
  20996. // Copy over all the attributes from the tag, including ID and class
  20997. // ID will now reference player box, not the video tag
  20998. const attrs = getAttributes(tag);
  20999. if (divEmbed) {
  21000. el = this.el_ = tag;
  21001. tag = this.tag = document.createElement('video');
  21002. while (el.children.length) {
  21003. tag.appendChild(el.firstChild);
  21004. }
  21005. if (!hasClass(el, 'video-js')) {
  21006. addClass(el, 'video-js');
  21007. }
  21008. el.appendChild(tag);
  21009. playerElIngest = this.playerElIngest_ = el;
  21010. // move properties over from our custom `video-js` element
  21011. // to our new `video` element. This will move things like
  21012. // `src` or `controls` that were set via js before the player
  21013. // was initialized.
  21014. Object.keys(el).forEach(k => {
  21015. try {
  21016. tag[k] = el[k];
  21017. } catch (e) {
  21018. // we got a a property like outerHTML which we can't actually copy, ignore it
  21019. }
  21020. });
  21021. }
  21022. // set tabindex to -1 to remove the video element from the focus order
  21023. tag.setAttribute('tabindex', '-1');
  21024. attrs.tabindex = '-1';
  21025. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  21026. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  21027. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  21028. // doesn't change behavior of Chrome if JAWS is not being used
  21029. if (IS_CHROME && IS_WINDOWS) {
  21030. tag.setAttribute('role', 'application');
  21031. attrs.role = 'application';
  21032. }
  21033. // Remove width/height attrs from tag so CSS can make it 100% width/height
  21034. tag.removeAttribute('width');
  21035. tag.removeAttribute('height');
  21036. if ('width' in attrs) {
  21037. delete attrs.width;
  21038. }
  21039. if ('height' in attrs) {
  21040. delete attrs.height;
  21041. }
  21042. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  21043. // don't copy over the class attribute to the player element when we're in a div embed
  21044. // the class is already set up properly in the divEmbed case
  21045. // and we want to make sure that the `video-js` class doesn't get lost
  21046. if (!(divEmbed && attr === 'class')) {
  21047. el.setAttribute(attr, attrs[attr]);
  21048. }
  21049. if (divEmbed) {
  21050. tag.setAttribute(attr, attrs[attr]);
  21051. }
  21052. });
  21053. // Update tag id/class for use as HTML5 playback tech
  21054. // Might think we should do this after embedding in container so .vjs-tech class
  21055. // doesn't flash 100% width/height, but class only applies with .video-js parent
  21056. tag.playerId = tag.id;
  21057. tag.id += '_html5_api';
  21058. tag.className = 'vjs-tech';
  21059. // Make player findable on elements
  21060. tag.player = el.player = this;
  21061. // Default state of video is paused
  21062. this.addClass('vjs-paused');
  21063. // Add a style element in the player that we'll use to set the width/height
  21064. // of the player in a way that's still overridable by CSS, just like the
  21065. // video element
  21066. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  21067. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  21068. const defaultsStyleEl = $('.vjs-styles-defaults');
  21069. const head = $('head');
  21070. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  21071. }
  21072. this.fill_ = false;
  21073. this.fluid_ = false;
  21074. // Pass in the width/height/aspectRatio options which will update the style el
  21075. this.width(this.options_.width);
  21076. this.height(this.options_.height);
  21077. this.fill(this.options_.fill);
  21078. this.fluid(this.options_.fluid);
  21079. this.aspectRatio(this.options_.aspectRatio);
  21080. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  21081. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  21082. // Hide any links within the video/audio tag,
  21083. // because IE doesn't hide them completely from screen readers.
  21084. const links = tag.getElementsByTagName('a');
  21085. for (let i = 0; i < links.length; i++) {
  21086. const linkEl = links.item(i);
  21087. addClass(linkEl, 'vjs-hidden');
  21088. linkEl.setAttribute('hidden', 'hidden');
  21089. }
  21090. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  21091. // keep track of the original for later so we can know if the source originally failed
  21092. tag.initNetworkState_ = tag.networkState;
  21093. // Wrap video tag in div (el/box) container
  21094. if (tag.parentNode && !playerElIngest) {
  21095. tag.parentNode.insertBefore(el, tag);
  21096. }
  21097. // insert the tag as the first child of the player element
  21098. // then manually add it to the children array so that this.addChild
  21099. // will work properly for other components
  21100. //
  21101. // Breaks iPhone, fixed in HTML5 setup.
  21102. prependTo(tag, el);
  21103. this.children_.unshift(tag);
  21104. // Set lang attr on player to ensure CSS :lang() in consistent with player
  21105. // if it's been set to something different to the doc
  21106. this.el_.setAttribute('lang', this.language_);
  21107. this.el_.setAttribute('translate', 'no');
  21108. this.el_ = el;
  21109. return el;
  21110. }
  21111. /**
  21112. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  21113. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  21114. * behavior.
  21115. *
  21116. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  21117. *
  21118. * @param {string|null} [value]
  21119. * The value to set the `Player`'s crossOrigin to. If an argument is
  21120. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  21121. *
  21122. * @return {string|null|undefined}
  21123. * - The current crossOrigin value of the `Player` when getting.
  21124. * - undefined when setting
  21125. */
  21126. crossOrigin(value) {
  21127. // `null` can be set to unset a value
  21128. if (typeof value === 'undefined') {
  21129. return this.techGet_('crossOrigin');
  21130. }
  21131. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  21132. log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  21133. return;
  21134. }
  21135. this.techCall_('setCrossOrigin', value);
  21136. if (this.posterImage) {
  21137. this.posterImage.crossOrigin(value);
  21138. }
  21139. return;
  21140. }
  21141. /**
  21142. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  21143. * To get the current width use `currentWidth()`.
  21144. *
  21145. * @param {number} [value]
  21146. * The value to set the `Player`'s width to.
  21147. *
  21148. * @return {number}
  21149. * The current width of the `Player` when getting.
  21150. */
  21151. width(value) {
  21152. return this.dimension('width', value);
  21153. }
  21154. /**
  21155. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  21156. * To get the current height use `currentheight()`.
  21157. *
  21158. * @param {number} [value]
  21159. * The value to set the `Player`'s height to.
  21160. *
  21161. * @return {number}
  21162. * The current height of the `Player` when getting.
  21163. */
  21164. height(value) {
  21165. return this.dimension('height', value);
  21166. }
  21167. /**
  21168. * A getter/setter for the `Player`'s width & height.
  21169. *
  21170. * @param {string} dimension
  21171. * This string can be:
  21172. * - 'width'
  21173. * - 'height'
  21174. *
  21175. * @param {number} [value]
  21176. * Value for dimension specified in the first argument.
  21177. *
  21178. * @return {number}
  21179. * The dimension arguments value when getting (width/height).
  21180. */
  21181. dimension(dimension, value) {
  21182. const privDimension = dimension + '_';
  21183. if (value === undefined) {
  21184. return this[privDimension] || 0;
  21185. }
  21186. if (value === '' || value === 'auto') {
  21187. // If an empty string is given, reset the dimension to be automatic
  21188. this[privDimension] = undefined;
  21189. this.updateStyleEl_();
  21190. return;
  21191. }
  21192. const parsedVal = parseFloat(value);
  21193. if (isNaN(parsedVal)) {
  21194. log.error(`Improper value "${value}" supplied for for ${dimension}`);
  21195. return;
  21196. }
  21197. this[privDimension] = parsedVal;
  21198. this.updateStyleEl_();
  21199. }
  21200. /**
  21201. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  21202. *
  21203. * Turning this on will turn off fill mode.
  21204. *
  21205. * @param {boolean} [bool]
  21206. * - A value of true adds the class.
  21207. * - A value of false removes the class.
  21208. * - No value will be a getter.
  21209. *
  21210. * @return {boolean|undefined}
  21211. * - The value of fluid when getting.
  21212. * - `undefined` when setting.
  21213. */
  21214. fluid(bool) {
  21215. if (bool === undefined) {
  21216. return !!this.fluid_;
  21217. }
  21218. this.fluid_ = !!bool;
  21219. if (isEvented(this)) {
  21220. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21221. }
  21222. if (bool) {
  21223. this.addClass('vjs-fluid');
  21224. this.fill(false);
  21225. addEventedCallback(this, () => {
  21226. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21227. });
  21228. } else {
  21229. this.removeClass('vjs-fluid');
  21230. }
  21231. this.updateStyleEl_();
  21232. }
  21233. /**
  21234. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  21235. *
  21236. * Turning this on will turn off fluid mode.
  21237. *
  21238. * @param {boolean} [bool]
  21239. * - A value of true adds the class.
  21240. * - A value of false removes the class.
  21241. * - No value will be a getter.
  21242. *
  21243. * @return {boolean|undefined}
  21244. * - The value of fluid when getting.
  21245. * - `undefined` when setting.
  21246. */
  21247. fill(bool) {
  21248. if (bool === undefined) {
  21249. return !!this.fill_;
  21250. }
  21251. this.fill_ = !!bool;
  21252. if (bool) {
  21253. this.addClass('vjs-fill');
  21254. this.fluid(false);
  21255. } else {
  21256. this.removeClass('vjs-fill');
  21257. }
  21258. }
  21259. /**
  21260. * Get/Set the aspect ratio
  21261. *
  21262. * @param {string} [ratio]
  21263. * Aspect ratio for player
  21264. *
  21265. * @return {string|undefined}
  21266. * returns the current aspect ratio when getting
  21267. */
  21268. /**
  21269. * A getter/setter for the `Player`'s aspect ratio.
  21270. *
  21271. * @param {string} [ratio]
  21272. * The value to set the `Player`'s aspect ratio to.
  21273. *
  21274. * @return {string|undefined}
  21275. * - The current aspect ratio of the `Player` when getting.
  21276. * - undefined when setting
  21277. */
  21278. aspectRatio(ratio) {
  21279. if (ratio === undefined) {
  21280. return this.aspectRatio_;
  21281. }
  21282. // Check for width:height format
  21283. if (!/^\d+\:\d+$/.test(ratio)) {
  21284. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  21285. }
  21286. this.aspectRatio_ = ratio;
  21287. // We're assuming if you set an aspect ratio you want fluid mode,
  21288. // because in fixed mode you could calculate width and height yourself.
  21289. this.fluid(true);
  21290. this.updateStyleEl_();
  21291. }
  21292. /**
  21293. * Update styles of the `Player` element (height, width and aspect ratio).
  21294. *
  21295. * @private
  21296. * @listens Tech#loadedmetadata
  21297. */
  21298. updateStyleEl_() {
  21299. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  21300. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  21301. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  21302. const techEl = this.tech_ && this.tech_.el();
  21303. if (techEl) {
  21304. if (width >= 0) {
  21305. techEl.width = width;
  21306. }
  21307. if (height >= 0) {
  21308. techEl.height = height;
  21309. }
  21310. }
  21311. return;
  21312. }
  21313. let width;
  21314. let height;
  21315. let aspectRatio;
  21316. let idClass;
  21317. // The aspect ratio is either used directly or to calculate width and height.
  21318. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  21319. // Use any aspectRatio that's been specifically set
  21320. aspectRatio = this.aspectRatio_;
  21321. } else if (this.videoWidth() > 0) {
  21322. // Otherwise try to get the aspect ratio from the video metadata
  21323. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  21324. } else {
  21325. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  21326. aspectRatio = '16:9';
  21327. }
  21328. // Get the ratio as a decimal we can use to calculate dimensions
  21329. const ratioParts = aspectRatio.split(':');
  21330. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  21331. if (this.width_ !== undefined) {
  21332. // Use any width that's been specifically set
  21333. width = this.width_;
  21334. } else if (this.height_ !== undefined) {
  21335. // Or calculate the width from the aspect ratio if a height has been set
  21336. width = this.height_ / ratioMultiplier;
  21337. } else {
  21338. // Or use the video's metadata, or use the video el's default of 300
  21339. width = this.videoWidth() || 300;
  21340. }
  21341. if (this.height_ !== undefined) {
  21342. // Use any height that's been specifically set
  21343. height = this.height_;
  21344. } else {
  21345. // Otherwise calculate the height from the ratio and the width
  21346. height = width * ratioMultiplier;
  21347. }
  21348. // Ensure the CSS class is valid by starting with an alpha character
  21349. if (/^[^a-zA-Z]/.test(this.id())) {
  21350. idClass = 'dimensions-' + this.id();
  21351. } else {
  21352. idClass = this.id() + '-dimensions';
  21353. }
  21354. // Ensure the right class is still on the player for the style element
  21355. this.addClass(idClass);
  21356. setTextContent(this.styleEl_, `
  21357. .${idClass} {
  21358. width: ${width}px;
  21359. height: ${height}px;
  21360. }
  21361. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  21362. padding-top: ${ratioMultiplier * 100}%;
  21363. }
  21364. `);
  21365. }
  21366. /**
  21367. * Load/Create an instance of playback {@link Tech} including element
  21368. * and API methods. Then append the `Tech` element in `Player` as a child.
  21369. *
  21370. * @param {string} techName
  21371. * name of the playback technology
  21372. *
  21373. * @param {string} source
  21374. * video source
  21375. *
  21376. * @private
  21377. */
  21378. loadTech_(techName, source) {
  21379. // Pause and remove current playback technology
  21380. if (this.tech_) {
  21381. this.unloadTech_();
  21382. }
  21383. const titleTechName = toTitleCase(techName);
  21384. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  21385. // get rid of the HTML5 video tag as soon as we are using another tech
  21386. if (titleTechName !== 'Html5' && this.tag) {
  21387. Tech.getTech('Html5').disposeMediaElement(this.tag);
  21388. this.tag.player = null;
  21389. this.tag = null;
  21390. }
  21391. this.techName_ = titleTechName;
  21392. // Turn off API access because we're loading a new tech that might load asynchronously
  21393. this.isReady_ = false;
  21394. let autoplay = this.autoplay();
  21395. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  21396. // because the player is going to handle autoplay on `loadstart`
  21397. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  21398. autoplay = false;
  21399. }
  21400. // Grab tech-specific options from player options and add source and parent element to use.
  21401. const techOptions = {
  21402. source,
  21403. autoplay,
  21404. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  21405. 'playerId': this.id(),
  21406. 'techId': `${this.id()}_${camelTechName}_api`,
  21407. 'playsinline': this.options_.playsinline,
  21408. 'preload': this.options_.preload,
  21409. 'loop': this.options_.loop,
  21410. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  21411. 'muted': this.options_.muted,
  21412. 'poster': this.poster(),
  21413. 'language': this.language(),
  21414. 'playerElIngest': this.playerElIngest_ || false,
  21415. 'vtt.js': this.options_['vtt.js'],
  21416. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  21417. 'enableSourceset': this.options_.enableSourceset
  21418. };
  21419. ALL.names.forEach(name => {
  21420. const props = ALL[name];
  21421. techOptions[props.getterName] = this[props.privateName];
  21422. });
  21423. Object.assign(techOptions, this.options_[titleTechName]);
  21424. Object.assign(techOptions, this.options_[camelTechName]);
  21425. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  21426. if (this.tag) {
  21427. techOptions.tag = this.tag;
  21428. }
  21429. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  21430. techOptions.startTime = this.cache_.currentTime;
  21431. }
  21432. // Initialize tech instance
  21433. const TechClass = Tech.getTech(techName);
  21434. if (!TechClass) {
  21435. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  21436. }
  21437. this.tech_ = new TechClass(techOptions);
  21438. // player.triggerReady is always async, so don't need this to be async
  21439. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  21440. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  21441. // Listen to all HTML5-defined events and trigger them on the player
  21442. TECH_EVENTS_RETRIGGER.forEach(event => {
  21443. this.on(this.tech_, event, e => this[`handleTech${toTitleCase(event)}_`](e));
  21444. });
  21445. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  21446. this.on(this.tech_, event, eventObj => {
  21447. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  21448. this.queuedCallbacks_.push({
  21449. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  21450. event: eventObj
  21451. });
  21452. return;
  21453. }
  21454. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  21455. });
  21456. });
  21457. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  21458. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  21459. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  21460. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  21461. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  21462. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  21463. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  21464. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  21465. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  21466. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  21467. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  21468. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  21469. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  21470. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  21471. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  21472. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  21473. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  21474. this.usingNativeControls(this.techGet_('controls'));
  21475. if (this.controls() && !this.usingNativeControls()) {
  21476. this.addTechControlsListeners_();
  21477. }
  21478. // Add the tech element in the DOM if it was not already there
  21479. // Make sure to not insert the original video element if using Html5
  21480. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  21481. prependTo(this.tech_.el(), this.el());
  21482. }
  21483. // Get rid of the original video tag reference after the first tech is loaded
  21484. if (this.tag) {
  21485. this.tag.player = null;
  21486. this.tag = null;
  21487. }
  21488. }
  21489. /**
  21490. * Unload and dispose of the current playback {@link Tech}.
  21491. *
  21492. * @private
  21493. */
  21494. unloadTech_() {
  21495. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  21496. ALL.names.forEach(name => {
  21497. const props = ALL[name];
  21498. this[props.privateName] = this[props.getterName]();
  21499. });
  21500. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  21501. this.isReady_ = false;
  21502. this.tech_.dispose();
  21503. this.tech_ = false;
  21504. if (this.isPosterFromTech_) {
  21505. this.poster_ = '';
  21506. this.trigger('posterchange');
  21507. }
  21508. this.isPosterFromTech_ = false;
  21509. }
  21510. /**
  21511. * Return a reference to the current {@link Tech}.
  21512. * It will print a warning by default about the danger of using the tech directly
  21513. * but any argument that is passed in will silence the warning.
  21514. *
  21515. * @param {*} [safety]
  21516. * Anything passed in to silence the warning
  21517. *
  21518. * @return {Tech}
  21519. * The Tech
  21520. */
  21521. tech(safety) {
  21522. if (safety === undefined) {
  21523. 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');
  21524. }
  21525. return this.tech_;
  21526. }
  21527. /**
  21528. * Set up click and touch listeners for the playback element
  21529. *
  21530. * - On desktops: a click on the video itself will toggle playback
  21531. * - On mobile devices: a click on the video toggles controls
  21532. * which is done by toggling the user state between active and
  21533. * inactive
  21534. * - A tap can signal that a user has become active or has become inactive
  21535. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  21536. * quick tap should hide them again (signaling the user is in an inactive
  21537. * viewing state)
  21538. * - In addition to this, we still want the user to be considered inactive after
  21539. * a few seconds of inactivity.
  21540. *
  21541. * > Note: the only part of iOS interaction we can't mimic with this setup
  21542. * is a touch and hold on the video element counting as activity in order to
  21543. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  21544. * on any controls will still keep the user active
  21545. *
  21546. * @private
  21547. */
  21548. addTechControlsListeners_() {
  21549. // Make sure to remove all the previous listeners in case we are called multiple times.
  21550. this.removeTechControlsListeners_();
  21551. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  21552. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21553. // If the controls were hidden we don't want that to change without a tap event
  21554. // so we'll check if the controls were already showing before reporting user
  21555. // activity
  21556. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21557. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21558. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21559. // The tap listener needs to come after the touchend listener because the tap
  21560. // listener cancels out any reportedUserActivity when setting userActive(false)
  21561. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  21562. }
  21563. /**
  21564. * Remove the listeners used for click and tap controls. This is needed for
  21565. * toggling to controls disabled, where a tap/touch should do nothing.
  21566. *
  21567. * @private
  21568. */
  21569. removeTechControlsListeners_() {
  21570. // We don't want to just use `this.off()` because there might be other needed
  21571. // listeners added by techs that extend this.
  21572. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  21573. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21574. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21575. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21576. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  21577. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21578. }
  21579. /**
  21580. * Player waits for the tech to be ready
  21581. *
  21582. * @private
  21583. */
  21584. handleTechReady_() {
  21585. this.triggerReady();
  21586. // Keep the same volume as before
  21587. if (this.cache_.volume) {
  21588. this.techCall_('setVolume', this.cache_.volume);
  21589. }
  21590. // Look if the tech found a higher resolution poster while loading
  21591. this.handleTechPosterChange_();
  21592. // Update the duration if available
  21593. this.handleTechDurationChange_();
  21594. }
  21595. /**
  21596. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  21597. *
  21598. * @fires Player#loadstart
  21599. * @listens Tech#loadstart
  21600. * @private
  21601. */
  21602. handleTechLoadStart_() {
  21603. // TODO: Update to use `emptied` event instead. See #1277.
  21604. this.removeClass('vjs-ended', 'vjs-seeking');
  21605. // reset the error state
  21606. this.error(null);
  21607. // Update the duration
  21608. this.handleTechDurationChange_();
  21609. if (!this.paused()) {
  21610. /**
  21611. * Fired when the user agent begins looking for media data
  21612. *
  21613. * @event Player#loadstart
  21614. * @type {Event}
  21615. */
  21616. this.trigger('loadstart');
  21617. } else {
  21618. // reset the hasStarted state
  21619. this.hasStarted(false);
  21620. this.trigger('loadstart');
  21621. }
  21622. // autoplay happens after loadstart for the browser,
  21623. // so we mimic that behavior
  21624. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  21625. }
  21626. /**
  21627. * Handle autoplay string values, rather than the typical boolean
  21628. * values that should be handled by the tech. Note that this is not
  21629. * part of any specification. Valid values and what they do can be
  21630. * found on the autoplay getter at Player#autoplay()
  21631. */
  21632. manualAutoplay_(type) {
  21633. if (!this.tech_ || typeof type !== 'string') {
  21634. return;
  21635. }
  21636. // Save original muted() value, set muted to true, and attempt to play().
  21637. // On promise rejection, restore muted from saved value
  21638. const resolveMuted = () => {
  21639. const previouslyMuted = this.muted();
  21640. this.muted(true);
  21641. const restoreMuted = () => {
  21642. this.muted(previouslyMuted);
  21643. };
  21644. // restore muted on play terminatation
  21645. this.playTerminatedQueue_.push(restoreMuted);
  21646. const mutedPromise = this.play();
  21647. if (!isPromise(mutedPromise)) {
  21648. return;
  21649. }
  21650. return mutedPromise.catch(err => {
  21651. restoreMuted();
  21652. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  21653. });
  21654. };
  21655. let promise;
  21656. // if muted defaults to true
  21657. // the only thing we can do is call play
  21658. if (type === 'any' && !this.muted()) {
  21659. promise = this.play();
  21660. if (isPromise(promise)) {
  21661. promise = promise.catch(resolveMuted);
  21662. }
  21663. } else if (type === 'muted' && !this.muted()) {
  21664. promise = resolveMuted();
  21665. } else {
  21666. promise = this.play();
  21667. }
  21668. if (!isPromise(promise)) {
  21669. return;
  21670. }
  21671. return promise.then(() => {
  21672. this.trigger({
  21673. type: 'autoplay-success',
  21674. autoplay: type
  21675. });
  21676. }).catch(() => {
  21677. this.trigger({
  21678. type: 'autoplay-failure',
  21679. autoplay: type
  21680. });
  21681. });
  21682. }
  21683. /**
  21684. * Update the internal source caches so that we return the correct source from
  21685. * `src()`, `currentSource()`, and `currentSources()`.
  21686. *
  21687. * > Note: `currentSources` will not be updated if the source that is passed in exists
  21688. * in the current `currentSources` cache.
  21689. *
  21690. *
  21691. * @param {Tech~SourceObject} srcObj
  21692. * A string or object source to update our caches to.
  21693. */
  21694. updateSourceCaches_(srcObj = '') {
  21695. let src = srcObj;
  21696. let type = '';
  21697. if (typeof src !== 'string') {
  21698. src = srcObj.src;
  21699. type = srcObj.type;
  21700. }
  21701. // make sure all the caches are set to default values
  21702. // to prevent null checking
  21703. this.cache_.source = this.cache_.source || {};
  21704. this.cache_.sources = this.cache_.sources || [];
  21705. // try to get the type of the src that was passed in
  21706. if (src && !type) {
  21707. type = findMimetype(this, src);
  21708. }
  21709. // update `currentSource` cache always
  21710. this.cache_.source = merge({}, srcObj, {
  21711. src,
  21712. type
  21713. });
  21714. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  21715. const sourceElSources = [];
  21716. const sourceEls = this.$$('source');
  21717. const matchingSourceEls = [];
  21718. for (let i = 0; i < sourceEls.length; i++) {
  21719. const sourceObj = getAttributes(sourceEls[i]);
  21720. sourceElSources.push(sourceObj);
  21721. if (sourceObj.src && sourceObj.src === src) {
  21722. matchingSourceEls.push(sourceObj.src);
  21723. }
  21724. }
  21725. // if we have matching source els but not matching sources
  21726. // the current source cache is not up to date
  21727. if (matchingSourceEls.length && !matchingSources.length) {
  21728. this.cache_.sources = sourceElSources;
  21729. // if we don't have matching source or source els set the
  21730. // sources cache to the `currentSource` cache
  21731. } else if (!matchingSources.length) {
  21732. this.cache_.sources = [this.cache_.source];
  21733. }
  21734. // update the tech `src` cache
  21735. this.cache_.src = src;
  21736. }
  21737. /**
  21738. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  21739. * causing the media element to reload.
  21740. *
  21741. * It will fire for the initial source and each subsequent source.
  21742. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  21743. *
  21744. * The event object for this event contains a `src` property that will contain the source
  21745. * that was available when the event was triggered. This is generally only necessary if Video.js
  21746. * is switching techs while the source was being changed.
  21747. *
  21748. * It is also fired when `load` is called on the player (or media element)
  21749. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  21750. * says that the resource selection algorithm needs to be aborted and restarted.
  21751. * In this case, it is very likely that the `src` property will be set to the
  21752. * empty string `""` to indicate we do not know what the source will be but
  21753. * that it is changing.
  21754. *
  21755. * *This event is currently still experimental and may change in minor releases.*
  21756. * __To use this, pass `enableSourceset` option to the player.__
  21757. *
  21758. * @event Player#sourceset
  21759. * @type {Event}
  21760. * @prop {string} src
  21761. * The source url available when the `sourceset` was triggered.
  21762. * It will be an empty string if we cannot know what the source is
  21763. * but know that the source will change.
  21764. */
  21765. /**
  21766. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  21767. *
  21768. * @fires Player#sourceset
  21769. * @listens Tech#sourceset
  21770. * @private
  21771. */
  21772. handleTechSourceset_(event) {
  21773. // only update the source cache when the source
  21774. // was not updated using the player api
  21775. if (!this.changingSrc_) {
  21776. let updateSourceCaches = src => this.updateSourceCaches_(src);
  21777. const playerSrc = this.currentSource().src;
  21778. const eventSrc = event.src;
  21779. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  21780. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  21781. // if both the tech source and the player source were updated we assume
  21782. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  21783. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  21784. updateSourceCaches = () => {};
  21785. }
  21786. }
  21787. // update the source to the initial source right away
  21788. // in some cases this will be empty string
  21789. updateSourceCaches(eventSrc);
  21790. // if the `sourceset` `src` was an empty string
  21791. // wait for a `loadstart` to update the cache to `currentSrc`.
  21792. // If a sourceset happens before a `loadstart`, we reset the state
  21793. if (!event.src) {
  21794. this.tech_.any(['sourceset', 'loadstart'], e => {
  21795. // if a sourceset happens before a `loadstart` there
  21796. // is nothing to do as this `handleTechSourceset_`
  21797. // will be called again and this will be handled there.
  21798. if (e.type === 'sourceset') {
  21799. return;
  21800. }
  21801. const techSrc = this.techGet('currentSrc');
  21802. this.lastSource_.tech = techSrc;
  21803. this.updateSourceCaches_(techSrc);
  21804. });
  21805. }
  21806. }
  21807. this.lastSource_ = {
  21808. player: this.currentSource().src,
  21809. tech: event.src
  21810. };
  21811. this.trigger({
  21812. src: event.src,
  21813. type: 'sourceset'
  21814. });
  21815. }
  21816. /**
  21817. * Add/remove the vjs-has-started class
  21818. *
  21819. *
  21820. * @param {boolean} request
  21821. * - true: adds the class
  21822. * - false: remove the class
  21823. *
  21824. * @return {boolean}
  21825. * the boolean value of hasStarted_
  21826. */
  21827. hasStarted(request) {
  21828. if (request === undefined) {
  21829. // act as getter, if we have no request to change
  21830. return this.hasStarted_;
  21831. }
  21832. if (request === this.hasStarted_) {
  21833. return;
  21834. }
  21835. this.hasStarted_ = request;
  21836. if (this.hasStarted_) {
  21837. this.addClass('vjs-has-started');
  21838. } else {
  21839. this.removeClass('vjs-has-started');
  21840. }
  21841. }
  21842. /**
  21843. * Fired whenever the media begins or resumes playback
  21844. *
  21845. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  21846. * @fires Player#play
  21847. * @listens Tech#play
  21848. * @private
  21849. */
  21850. handleTechPlay_() {
  21851. this.removeClass('vjs-ended', 'vjs-paused');
  21852. this.addClass('vjs-playing');
  21853. // hide the poster when the user hits play
  21854. this.hasStarted(true);
  21855. /**
  21856. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  21857. * playback has started or resumed.
  21858. *
  21859. * @event Player#play
  21860. * @type {Event}
  21861. */
  21862. this.trigger('play');
  21863. }
  21864. /**
  21865. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  21866. *
  21867. * If there were any events queued while the playback rate was zero, fire
  21868. * those events now.
  21869. *
  21870. * @private
  21871. * @method Player#handleTechRateChange_
  21872. * @fires Player#ratechange
  21873. * @listens Tech#ratechange
  21874. */
  21875. handleTechRateChange_() {
  21876. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  21877. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  21878. this.queuedCallbacks_ = [];
  21879. }
  21880. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  21881. /**
  21882. * Fires when the playing speed of the audio/video is changed
  21883. *
  21884. * @event Player#ratechange
  21885. * @type {event}
  21886. */
  21887. this.trigger('ratechange');
  21888. }
  21889. /**
  21890. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  21891. *
  21892. * @fires Player#waiting
  21893. * @listens Tech#waiting
  21894. * @private
  21895. */
  21896. handleTechWaiting_() {
  21897. this.addClass('vjs-waiting');
  21898. /**
  21899. * A readyState change on the DOM element has caused playback to stop.
  21900. *
  21901. * @event Player#waiting
  21902. * @type {Event}
  21903. */
  21904. this.trigger('waiting');
  21905. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  21906. // premature removal of the waiting class, wait for the time to change.
  21907. const timeWhenWaiting = this.currentTime();
  21908. const timeUpdateListener = () => {
  21909. if (timeWhenWaiting !== this.currentTime()) {
  21910. this.removeClass('vjs-waiting');
  21911. this.off('timeupdate', timeUpdateListener);
  21912. }
  21913. };
  21914. this.on('timeupdate', timeUpdateListener);
  21915. }
  21916. /**
  21917. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  21918. * > Note: This is not consistent between browsers. See #1351
  21919. *
  21920. * @fires Player#canplay
  21921. * @listens Tech#canplay
  21922. * @private
  21923. */
  21924. handleTechCanPlay_() {
  21925. this.removeClass('vjs-waiting');
  21926. /**
  21927. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  21928. *
  21929. * @event Player#canplay
  21930. * @type {Event}
  21931. */
  21932. this.trigger('canplay');
  21933. }
  21934. /**
  21935. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  21936. *
  21937. * @fires Player#canplaythrough
  21938. * @listens Tech#canplaythrough
  21939. * @private
  21940. */
  21941. handleTechCanPlayThrough_() {
  21942. this.removeClass('vjs-waiting');
  21943. /**
  21944. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  21945. * entire media file can be played without buffering.
  21946. *
  21947. * @event Player#canplaythrough
  21948. * @type {Event}
  21949. */
  21950. this.trigger('canplaythrough');
  21951. }
  21952. /**
  21953. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  21954. *
  21955. * @fires Player#playing
  21956. * @listens Tech#playing
  21957. * @private
  21958. */
  21959. handleTechPlaying_() {
  21960. this.removeClass('vjs-waiting');
  21961. /**
  21962. * The media is no longer blocked from playback, and has started playing.
  21963. *
  21964. * @event Player#playing
  21965. * @type {Event}
  21966. */
  21967. this.trigger('playing');
  21968. }
  21969. /**
  21970. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  21971. *
  21972. * @fires Player#seeking
  21973. * @listens Tech#seeking
  21974. * @private
  21975. */
  21976. handleTechSeeking_() {
  21977. this.addClass('vjs-seeking');
  21978. /**
  21979. * Fired whenever the player is jumping to a new time
  21980. *
  21981. * @event Player#seeking
  21982. * @type {Event}
  21983. */
  21984. this.trigger('seeking');
  21985. }
  21986. /**
  21987. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  21988. *
  21989. * @fires Player#seeked
  21990. * @listens Tech#seeked
  21991. * @private
  21992. */
  21993. handleTechSeeked_() {
  21994. this.removeClass('vjs-seeking', 'vjs-ended');
  21995. /**
  21996. * Fired when the player has finished jumping to a new time
  21997. *
  21998. * @event Player#seeked
  21999. * @type {Event}
  22000. */
  22001. this.trigger('seeked');
  22002. }
  22003. /**
  22004. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  22005. *
  22006. * @fires Player#pause
  22007. * @listens Tech#pause
  22008. * @private
  22009. */
  22010. handleTechPause_() {
  22011. this.removeClass('vjs-playing');
  22012. this.addClass('vjs-paused');
  22013. /**
  22014. * Fired whenever the media has been paused
  22015. *
  22016. * @event Player#pause
  22017. * @type {Event}
  22018. */
  22019. this.trigger('pause');
  22020. }
  22021. /**
  22022. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  22023. *
  22024. * @fires Player#ended
  22025. * @listens Tech#ended
  22026. * @private
  22027. */
  22028. handleTechEnded_() {
  22029. this.addClass('vjs-ended');
  22030. this.removeClass('vjs-waiting');
  22031. if (this.options_.loop) {
  22032. this.currentTime(0);
  22033. this.play();
  22034. } else if (!this.paused()) {
  22035. this.pause();
  22036. }
  22037. /**
  22038. * Fired when the end of the media resource is reached (currentTime == duration)
  22039. *
  22040. * @event Player#ended
  22041. * @type {Event}
  22042. */
  22043. this.trigger('ended');
  22044. }
  22045. /**
  22046. * Fired when the duration of the media resource is first known or changed
  22047. *
  22048. * @listens Tech#durationchange
  22049. * @private
  22050. */
  22051. handleTechDurationChange_() {
  22052. this.duration(this.techGet_('duration'));
  22053. }
  22054. /**
  22055. * Handle a click on the media element to play/pause
  22056. *
  22057. * @param {Event} event
  22058. * the event that caused this function to trigger
  22059. *
  22060. * @listens Tech#click
  22061. * @private
  22062. */
  22063. handleTechClick_(event) {
  22064. // When controls are disabled a click should not toggle playback because
  22065. // the click is considered a control
  22066. if (!this.controls_) {
  22067. return;
  22068. }
  22069. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  22070. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  22071. this.options_.userActions.click.call(this, event);
  22072. } else if (this.paused()) {
  22073. silencePromise(this.play());
  22074. } else {
  22075. this.pause();
  22076. }
  22077. }
  22078. }
  22079. /**
  22080. * Handle a double-click on the media element to enter/exit fullscreen
  22081. *
  22082. * @param {Event} event
  22083. * the event that caused this function to trigger
  22084. *
  22085. * @listens Tech#dblclick
  22086. * @private
  22087. */
  22088. handleTechDoubleClick_(event) {
  22089. if (!this.controls_) {
  22090. return;
  22091. }
  22092. // we do not want to toggle fullscreen state
  22093. // when double-clicking inside a control bar or a modal
  22094. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  22095. if (!inAllowedEls) {
  22096. /*
  22097. * options.userActions.doubleClick
  22098. *
  22099. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  22100. * Set to `false` to disable double-click handling
  22101. * Set to a function to substitute an external double-click handler
  22102. */
  22103. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  22104. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  22105. this.options_.userActions.doubleClick.call(this, event);
  22106. } else if (this.isFullscreen()) {
  22107. this.exitFullscreen();
  22108. } else {
  22109. this.requestFullscreen();
  22110. }
  22111. }
  22112. }
  22113. }
  22114. /**
  22115. * Handle a tap on the media element. It will toggle the user
  22116. * activity state, which hides and shows the controls.
  22117. *
  22118. * @listens Tech#tap
  22119. * @private
  22120. */
  22121. handleTechTap_() {
  22122. this.userActive(!this.userActive());
  22123. }
  22124. /**
  22125. * Handle touch to start
  22126. *
  22127. * @listens Tech#touchstart
  22128. * @private
  22129. */
  22130. handleTechTouchStart_() {
  22131. this.userWasActive = this.userActive();
  22132. }
  22133. /**
  22134. * Handle touch to move
  22135. *
  22136. * @listens Tech#touchmove
  22137. * @private
  22138. */
  22139. handleTechTouchMove_() {
  22140. if (this.userWasActive) {
  22141. this.reportUserActivity();
  22142. }
  22143. }
  22144. /**
  22145. * Handle touch to end
  22146. *
  22147. * @param {Event} event
  22148. * the touchend event that triggered
  22149. * this function
  22150. *
  22151. * @listens Tech#touchend
  22152. * @private
  22153. */
  22154. handleTechTouchEnd_(event) {
  22155. // Stop the mouse events from also happening
  22156. if (event.cancelable) {
  22157. event.preventDefault();
  22158. }
  22159. }
  22160. /**
  22161. * @private
  22162. */
  22163. toggleFullscreenClass_() {
  22164. if (this.isFullscreen()) {
  22165. this.addClass('vjs-fullscreen');
  22166. } else {
  22167. this.removeClass('vjs-fullscreen');
  22168. }
  22169. }
  22170. /**
  22171. * when the document fschange event triggers it calls this
  22172. */
  22173. documentFullscreenChange_(e) {
  22174. const targetPlayer = e.target.player;
  22175. // if another player was fullscreen
  22176. // do a null check for targetPlayer because older firefox's would put document as e.target
  22177. if (targetPlayer && targetPlayer !== this) {
  22178. return;
  22179. }
  22180. const el = this.el();
  22181. let isFs = document[this.fsApi_.fullscreenElement] === el;
  22182. if (!isFs && el.matches) {
  22183. isFs = el.matches(':' + this.fsApi_.fullscreen);
  22184. } else if (!isFs && el.msMatchesSelector) {
  22185. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  22186. }
  22187. this.isFullscreen(isFs);
  22188. }
  22189. /**
  22190. * Handle Tech Fullscreen Change
  22191. *
  22192. * @param {Event} event
  22193. * the fullscreenchange event that triggered this function
  22194. *
  22195. * @param {Object} data
  22196. * the data that was sent with the event
  22197. *
  22198. * @private
  22199. * @listens Tech#fullscreenchange
  22200. * @fires Player#fullscreenchange
  22201. */
  22202. handleTechFullscreenChange_(event, data) {
  22203. if (data) {
  22204. if (data.nativeIOSFullscreen) {
  22205. this.addClass('vjs-ios-native-fs');
  22206. this.tech_.one('webkitendfullscreen', () => {
  22207. this.removeClass('vjs-ios-native-fs');
  22208. });
  22209. }
  22210. this.isFullscreen(data.isFullscreen);
  22211. }
  22212. }
  22213. handleTechFullscreenError_(event, err) {
  22214. this.trigger('fullscreenerror', err);
  22215. }
  22216. /**
  22217. * @private
  22218. */
  22219. togglePictureInPictureClass_() {
  22220. if (this.isInPictureInPicture()) {
  22221. this.addClass('vjs-picture-in-picture');
  22222. } else {
  22223. this.removeClass('vjs-picture-in-picture');
  22224. }
  22225. }
  22226. /**
  22227. * Handle Tech Enter Picture-in-Picture.
  22228. *
  22229. * @param {Event} event
  22230. * the enterpictureinpicture event that triggered this function
  22231. *
  22232. * @private
  22233. * @listens Tech#enterpictureinpicture
  22234. */
  22235. handleTechEnterPictureInPicture_(event) {
  22236. this.isInPictureInPicture(true);
  22237. }
  22238. /**
  22239. * Handle Tech Leave Picture-in-Picture.
  22240. *
  22241. * @param {Event} event
  22242. * the leavepictureinpicture event that triggered this function
  22243. *
  22244. * @private
  22245. * @listens Tech#leavepictureinpicture
  22246. */
  22247. handleTechLeavePictureInPicture_(event) {
  22248. this.isInPictureInPicture(false);
  22249. }
  22250. /**
  22251. * Fires when an error occurred during the loading of an audio/video.
  22252. *
  22253. * @private
  22254. * @listens Tech#error
  22255. */
  22256. handleTechError_() {
  22257. const error = this.tech_.error();
  22258. this.error(error);
  22259. }
  22260. /**
  22261. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  22262. *
  22263. * @fires Player#textdata
  22264. * @listens Tech#textdata
  22265. * @private
  22266. */
  22267. handleTechTextData_() {
  22268. let data = null;
  22269. if (arguments.length > 1) {
  22270. data = arguments[1];
  22271. }
  22272. /**
  22273. * Fires when we get a textdata event from tech
  22274. *
  22275. * @event Player#textdata
  22276. * @type {Event}
  22277. */
  22278. this.trigger('textdata', data);
  22279. }
  22280. /**
  22281. * Get object for cached values.
  22282. *
  22283. * @return {Object}
  22284. * get the current object cache
  22285. */
  22286. getCache() {
  22287. return this.cache_;
  22288. }
  22289. /**
  22290. * Resets the internal cache object.
  22291. *
  22292. * Using this function outside the player constructor or reset method may
  22293. * have unintended side-effects.
  22294. *
  22295. * @private
  22296. */
  22297. resetCache_() {
  22298. this.cache_ = {
  22299. // Right now, the currentTime is not _really_ cached because it is always
  22300. // retrieved from the tech (see: currentTime). However, for completeness,
  22301. // we set it to zero here to ensure that if we do start actually caching
  22302. // it, we reset it along with everything else.
  22303. currentTime: 0,
  22304. initTime: 0,
  22305. inactivityTimeout: this.options_.inactivityTimeout,
  22306. duration: NaN,
  22307. lastVolume: 1,
  22308. lastPlaybackRate: this.defaultPlaybackRate(),
  22309. media: null,
  22310. src: '',
  22311. source: {},
  22312. sources: [],
  22313. playbackRates: [],
  22314. volume: 1
  22315. };
  22316. }
  22317. /**
  22318. * Pass values to the playback tech
  22319. *
  22320. * @param {string} [method]
  22321. * the method to call
  22322. *
  22323. * @param {Object} arg
  22324. * the argument to pass
  22325. *
  22326. * @private
  22327. */
  22328. techCall_(method, arg) {
  22329. // If it's not ready yet, call method when it is
  22330. this.ready(function () {
  22331. if (method in allowedSetters) {
  22332. return set(this.middleware_, this.tech_, method, arg);
  22333. } else if (method in allowedMediators) {
  22334. return mediate(this.middleware_, this.tech_, method, arg);
  22335. }
  22336. try {
  22337. if (this.tech_) {
  22338. this.tech_[method](arg);
  22339. }
  22340. } catch (e) {
  22341. log(e);
  22342. throw e;
  22343. }
  22344. }, true);
  22345. }
  22346. /**
  22347. * Mediate attempt to call playback tech method
  22348. * and return the value of the method called.
  22349. *
  22350. * @param {string} method
  22351. * Tech method
  22352. *
  22353. * @return {*}
  22354. * Value returned by the tech method called, undefined if tech
  22355. * is not ready or tech method is not present
  22356. *
  22357. * @private
  22358. */
  22359. techGet_(method) {
  22360. if (!this.tech_ || !this.tech_.isReady_) {
  22361. return;
  22362. }
  22363. if (method in allowedGetters) {
  22364. return get(this.middleware_, this.tech_, method);
  22365. } else if (method in allowedMediators) {
  22366. return mediate(this.middleware_, this.tech_, method);
  22367. }
  22368. // Log error when playback tech object is present but method
  22369. // is undefined or unavailable
  22370. try {
  22371. return this.tech_[method]();
  22372. } catch (e) {
  22373. // When building additional tech libs, an expected method may not be defined yet
  22374. if (this.tech_[method] === undefined) {
  22375. log(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  22376. throw e;
  22377. }
  22378. // When a method isn't available on the object it throws a TypeError
  22379. if (e.name === 'TypeError') {
  22380. log(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  22381. this.tech_.isReady_ = false;
  22382. throw e;
  22383. }
  22384. // If error unknown, just log and throw
  22385. log(e);
  22386. throw e;
  22387. }
  22388. }
  22389. /**
  22390. * Attempt to begin playback at the first opportunity.
  22391. *
  22392. * @return {Promise|undefined}
  22393. * Returns a promise if the browser supports Promises (or one
  22394. * was passed in as an option). This promise will be resolved on
  22395. * the return value of play. If this is undefined it will fulfill the
  22396. * promise chain otherwise the promise chain will be fulfilled when
  22397. * the promise from play is fulfilled.
  22398. */
  22399. play() {
  22400. return new Promise(resolve => {
  22401. this.play_(resolve);
  22402. });
  22403. }
  22404. /**
  22405. * The actual logic for play, takes a callback that will be resolved on the
  22406. * return value of play. This allows us to resolve to the play promise if there
  22407. * is one on modern browsers.
  22408. *
  22409. * @private
  22410. * @param {Function} [callback]
  22411. * The callback that should be called when the techs play is actually called
  22412. */
  22413. play_(callback = silencePromise) {
  22414. this.playCallbacks_.push(callback);
  22415. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  22416. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  22417. // treat calls to play_ somewhat like the `one` event function
  22418. if (this.waitToPlay_) {
  22419. this.off(['ready', 'loadstart'], this.waitToPlay_);
  22420. this.waitToPlay_ = null;
  22421. }
  22422. // if the player/tech is not ready or the src itself is not ready
  22423. // queue up a call to play on `ready` or `loadstart`
  22424. if (!this.isReady_ || !isSrcReady) {
  22425. this.waitToPlay_ = e => {
  22426. this.play_();
  22427. };
  22428. this.one(['ready', 'loadstart'], this.waitToPlay_);
  22429. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  22430. // in that case, we need to prime the video element by calling load so it'll be ready in time
  22431. if (!isSrcReady && isSafariOrIOS) {
  22432. this.load();
  22433. }
  22434. return;
  22435. }
  22436. // If the player/tech is ready and we have a source, we can attempt playback.
  22437. const val = this.techGet_('play');
  22438. // For native playback, reset the progress bar if we get a play call from a replay.
  22439. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  22440. if (isNativeReplay) {
  22441. this.resetProgressBar_();
  22442. }
  22443. // play was terminated if the returned value is null
  22444. if (val === null) {
  22445. this.runPlayTerminatedQueue_();
  22446. } else {
  22447. this.runPlayCallbacks_(val);
  22448. }
  22449. }
  22450. /**
  22451. * These functions will be run when if play is terminated. If play
  22452. * runPlayCallbacks_ is run these function will not be run. This allows us
  22453. * to differentiate between a terminated play and an actual call to play.
  22454. */
  22455. runPlayTerminatedQueue_() {
  22456. const queue = this.playTerminatedQueue_.slice(0);
  22457. this.playTerminatedQueue_ = [];
  22458. queue.forEach(function (q) {
  22459. q();
  22460. });
  22461. }
  22462. /**
  22463. * When a callback to play is delayed we have to run these
  22464. * callbacks when play is actually called on the tech. This function
  22465. * runs the callbacks that were delayed and accepts the return value
  22466. * from the tech.
  22467. *
  22468. * @param {undefined|Promise} val
  22469. * The return value from the tech.
  22470. */
  22471. runPlayCallbacks_(val) {
  22472. const callbacks = this.playCallbacks_.slice(0);
  22473. this.playCallbacks_ = [];
  22474. // clear play terminatedQueue since we finished a real play
  22475. this.playTerminatedQueue_ = [];
  22476. callbacks.forEach(function (cb) {
  22477. cb(val);
  22478. });
  22479. }
  22480. /**
  22481. * Pause the video playback
  22482. *
  22483. * @return {Player}
  22484. * A reference to the player object this function was called on
  22485. */
  22486. pause() {
  22487. this.techCall_('pause');
  22488. }
  22489. /**
  22490. * Check if the player is paused or has yet to play
  22491. *
  22492. * @return {boolean}
  22493. * - false: if the media is currently playing
  22494. * - true: if media is not currently playing
  22495. */
  22496. paused() {
  22497. // The initial state of paused should be true (in Safari it's actually false)
  22498. return this.techGet_('paused') === false ? false : true;
  22499. }
  22500. /**
  22501. * Get a TimeRange object representing the current ranges of time that the user
  22502. * has played.
  22503. *
  22504. * @return { import('./utils/time').TimeRange }
  22505. * A time range object that represents all the increments of time that have
  22506. * been played.
  22507. */
  22508. played() {
  22509. return this.techGet_('played') || createTimeRanges(0, 0);
  22510. }
  22511. /**
  22512. * Returns whether or not the user is "scrubbing". Scrubbing is
  22513. * when the user has clicked the progress bar handle and is
  22514. * dragging it along the progress bar.
  22515. *
  22516. * @param {boolean} [isScrubbing]
  22517. * whether the user is or is not scrubbing
  22518. *
  22519. * @return {boolean}
  22520. * The value of scrubbing when getting
  22521. */
  22522. scrubbing(isScrubbing) {
  22523. if (typeof isScrubbing === 'undefined') {
  22524. return this.scrubbing_;
  22525. }
  22526. this.scrubbing_ = !!isScrubbing;
  22527. this.techCall_('setScrubbing', this.scrubbing_);
  22528. if (isScrubbing) {
  22529. this.addClass('vjs-scrubbing');
  22530. } else {
  22531. this.removeClass('vjs-scrubbing');
  22532. }
  22533. }
  22534. /**
  22535. * Get or set the current time (in seconds)
  22536. *
  22537. * @param {number|string} [seconds]
  22538. * The time to seek to in seconds
  22539. *
  22540. * @return {number}
  22541. * - the current time in seconds when getting
  22542. */
  22543. currentTime(seconds) {
  22544. if (typeof seconds !== 'undefined') {
  22545. if (seconds < 0) {
  22546. seconds = 0;
  22547. }
  22548. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  22549. this.cache_.initTime = seconds;
  22550. this.off('canplay', this.boundApplyInitTime_);
  22551. this.one('canplay', this.boundApplyInitTime_);
  22552. return;
  22553. }
  22554. this.techCall_('setCurrentTime', seconds);
  22555. this.cache_.initTime = 0;
  22556. return;
  22557. }
  22558. // cache last currentTime and return. default to 0 seconds
  22559. //
  22560. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  22561. // currentTime when scrubbing, but may not provide much performance benefit after all.
  22562. // Should be tested. Also something has to read the actual current time or the cache will
  22563. // never get updated.
  22564. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  22565. return this.cache_.currentTime;
  22566. }
  22567. /**
  22568. * Apply the value of initTime stored in cache as currentTime.
  22569. *
  22570. * @private
  22571. */
  22572. applyInitTime_() {
  22573. this.currentTime(this.cache_.initTime);
  22574. }
  22575. /**
  22576. * Normally gets the length in time of the video in seconds;
  22577. * in all but the rarest use cases an argument will NOT be passed to the method
  22578. *
  22579. * > **NOTE**: The video must have started loading before the duration can be
  22580. * known, and depending on preload behaviour may not be known until the video starts
  22581. * playing.
  22582. *
  22583. * @fires Player#durationchange
  22584. *
  22585. * @param {number} [seconds]
  22586. * The duration of the video to set in seconds
  22587. *
  22588. * @return {number}
  22589. * - The duration of the video in seconds when getting
  22590. */
  22591. duration(seconds) {
  22592. if (seconds === undefined) {
  22593. // return NaN if the duration is not known
  22594. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  22595. }
  22596. seconds = parseFloat(seconds);
  22597. // Standardize on Infinity for signaling video is live
  22598. if (seconds < 0) {
  22599. seconds = Infinity;
  22600. }
  22601. if (seconds !== this.cache_.duration) {
  22602. // Cache the last set value for optimized scrubbing
  22603. this.cache_.duration = seconds;
  22604. if (seconds === Infinity) {
  22605. this.addClass('vjs-live');
  22606. } else {
  22607. this.removeClass('vjs-live');
  22608. }
  22609. if (!isNaN(seconds)) {
  22610. // Do not fire durationchange unless the duration value is known.
  22611. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  22612. /**
  22613. * @event Player#durationchange
  22614. * @type {Event}
  22615. */
  22616. this.trigger('durationchange');
  22617. }
  22618. }
  22619. }
  22620. /**
  22621. * Calculates how much time is left in the video. Not part
  22622. * of the native video API.
  22623. *
  22624. * @return {number}
  22625. * The time remaining in seconds
  22626. */
  22627. remainingTime() {
  22628. return this.duration() - this.currentTime();
  22629. }
  22630. /**
  22631. * A remaining time function that is intended to be used when
  22632. * the time is to be displayed directly to the user.
  22633. *
  22634. * @return {number}
  22635. * The rounded time remaining in seconds
  22636. */
  22637. remainingTimeDisplay() {
  22638. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  22639. }
  22640. //
  22641. // Kind of like an array of portions of the video that have been downloaded.
  22642. /**
  22643. * Get a TimeRange object with an array of the times of the video
  22644. * that have been downloaded. If you just want the percent of the
  22645. * video that's been downloaded, use bufferedPercent.
  22646. *
  22647. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  22648. *
  22649. * @return { import('./utils/time').TimeRange }
  22650. * A mock {@link TimeRanges} object (following HTML spec)
  22651. */
  22652. buffered() {
  22653. let buffered = this.techGet_('buffered');
  22654. if (!buffered || !buffered.length) {
  22655. buffered = createTimeRanges(0, 0);
  22656. }
  22657. return buffered;
  22658. }
  22659. /**
  22660. * Get the percent (as a decimal) of the video that's been downloaded.
  22661. * This method is not a part of the native HTML video API.
  22662. *
  22663. * @return {number}
  22664. * A decimal between 0 and 1 representing the percent
  22665. * that is buffered 0 being 0% and 1 being 100%
  22666. */
  22667. bufferedPercent() {
  22668. return bufferedPercent(this.buffered(), this.duration());
  22669. }
  22670. /**
  22671. * Get the ending time of the last buffered time range
  22672. * This is used in the progress bar to encapsulate all time ranges.
  22673. *
  22674. * @return {number}
  22675. * The end of the last buffered time range
  22676. */
  22677. bufferedEnd() {
  22678. const buffered = this.buffered();
  22679. const duration = this.duration();
  22680. let end = buffered.end(buffered.length - 1);
  22681. if (end > duration) {
  22682. end = duration;
  22683. }
  22684. return end;
  22685. }
  22686. /**
  22687. * Get or set the current volume of the media
  22688. *
  22689. * @param {number} [percentAsDecimal]
  22690. * The new volume as a decimal percent:
  22691. * - 0 is muted/0%/off
  22692. * - 1.0 is 100%/full
  22693. * - 0.5 is half volume or 50%
  22694. *
  22695. * @return {number}
  22696. * The current volume as a percent when getting
  22697. */
  22698. volume(percentAsDecimal) {
  22699. let vol;
  22700. if (percentAsDecimal !== undefined) {
  22701. // Force value to between 0 and 1
  22702. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  22703. this.cache_.volume = vol;
  22704. this.techCall_('setVolume', vol);
  22705. if (vol > 0) {
  22706. this.lastVolume_(vol);
  22707. }
  22708. return;
  22709. }
  22710. // Default to 1 when returning current volume.
  22711. vol = parseFloat(this.techGet_('volume'));
  22712. return isNaN(vol) ? 1 : vol;
  22713. }
  22714. /**
  22715. * Get the current muted state, or turn mute on or off
  22716. *
  22717. * @param {boolean} [muted]
  22718. * - true to mute
  22719. * - false to unmute
  22720. *
  22721. * @return {boolean}
  22722. * - true if mute is on and getting
  22723. * - false if mute is off and getting
  22724. */
  22725. muted(muted) {
  22726. if (muted !== undefined) {
  22727. this.techCall_('setMuted', muted);
  22728. return;
  22729. }
  22730. return this.techGet_('muted') || false;
  22731. }
  22732. /**
  22733. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  22734. * indicates the state of muted on initial playback.
  22735. *
  22736. * ```js
  22737. * var myPlayer = videojs('some-player-id');
  22738. *
  22739. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  22740. *
  22741. * // get, should be false
  22742. * console.log(myPlayer.defaultMuted());
  22743. * // set to true
  22744. * myPlayer.defaultMuted(true);
  22745. * // get should be true
  22746. * console.log(myPlayer.defaultMuted());
  22747. * ```
  22748. *
  22749. * @param {boolean} [defaultMuted]
  22750. * - true to mute
  22751. * - false to unmute
  22752. *
  22753. * @return {boolean|Player}
  22754. * - true if defaultMuted is on and getting
  22755. * - false if defaultMuted is off and getting
  22756. * - A reference to the current player when setting
  22757. */
  22758. defaultMuted(defaultMuted) {
  22759. if (defaultMuted !== undefined) {
  22760. return this.techCall_('setDefaultMuted', defaultMuted);
  22761. }
  22762. return this.techGet_('defaultMuted') || false;
  22763. }
  22764. /**
  22765. * Get the last volume, or set it
  22766. *
  22767. * @param {number} [percentAsDecimal]
  22768. * The new last volume as a decimal percent:
  22769. * - 0 is muted/0%/off
  22770. * - 1.0 is 100%/full
  22771. * - 0.5 is half volume or 50%
  22772. *
  22773. * @return {number}
  22774. * the current value of lastVolume as a percent when getting
  22775. *
  22776. * @private
  22777. */
  22778. lastVolume_(percentAsDecimal) {
  22779. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  22780. this.cache_.lastVolume = percentAsDecimal;
  22781. return;
  22782. }
  22783. return this.cache_.lastVolume;
  22784. }
  22785. /**
  22786. * Check if current tech can support native fullscreen
  22787. * (e.g. with built in controls like iOS)
  22788. *
  22789. * @return {boolean}
  22790. * if native fullscreen is supported
  22791. */
  22792. supportsFullScreen() {
  22793. return this.techGet_('supportsFullScreen') || false;
  22794. }
  22795. /**
  22796. * Check if the player is in fullscreen mode or tell the player that it
  22797. * is or is not in fullscreen mode.
  22798. *
  22799. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  22800. * property and instead document.fullscreenElement is used. But isFullscreen is
  22801. * still a valuable property for internal player workings.
  22802. *
  22803. * @param {boolean} [isFS]
  22804. * Set the players current fullscreen state
  22805. *
  22806. * @return {boolean}
  22807. * - true if fullscreen is on and getting
  22808. * - false if fullscreen is off and getting
  22809. */
  22810. isFullscreen(isFS) {
  22811. if (isFS !== undefined) {
  22812. const oldValue = this.isFullscreen_;
  22813. this.isFullscreen_ = Boolean(isFS);
  22814. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  22815. // this is the only place where we trigger fullscreenchange events for older browsers
  22816. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  22817. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  22818. /**
  22819. * @event Player#fullscreenchange
  22820. * @type {Event}
  22821. */
  22822. this.trigger('fullscreenchange');
  22823. }
  22824. this.toggleFullscreenClass_();
  22825. return;
  22826. }
  22827. return this.isFullscreen_;
  22828. }
  22829. /**
  22830. * Increase the size of the video to full screen
  22831. * In some browsers, full screen is not supported natively, so it enters
  22832. * "full window mode", where the video fills the browser window.
  22833. * In browsers and devices that support native full screen, sometimes the
  22834. * browser's default controls will be shown, and not the Video.js custom skin.
  22835. * This includes most mobile devices (iOS, Android) and older versions of
  22836. * Safari.
  22837. *
  22838. * @param {Object} [fullscreenOptions]
  22839. * Override the player fullscreen options
  22840. *
  22841. * @fires Player#fullscreenchange
  22842. */
  22843. requestFullscreen(fullscreenOptions) {
  22844. if (this.isInPictureInPicture()) {
  22845. this.exitPictureInPicture();
  22846. }
  22847. const self = this;
  22848. return new Promise((resolve, reject) => {
  22849. function offHandler() {
  22850. self.off('fullscreenerror', errorHandler);
  22851. self.off('fullscreenchange', changeHandler);
  22852. }
  22853. function changeHandler() {
  22854. offHandler();
  22855. resolve();
  22856. }
  22857. function errorHandler(e, err) {
  22858. offHandler();
  22859. reject(err);
  22860. }
  22861. self.one('fullscreenchange', changeHandler);
  22862. self.one('fullscreenerror', errorHandler);
  22863. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  22864. if (promise) {
  22865. promise.then(offHandler, offHandler);
  22866. promise.then(resolve, reject);
  22867. }
  22868. });
  22869. }
  22870. requestFullscreenHelper_(fullscreenOptions) {
  22871. let fsOptions;
  22872. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  22873. // Use defaults or player configured option unless passed directly to this method.
  22874. if (!this.fsApi_.prefixed) {
  22875. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  22876. if (fullscreenOptions !== undefined) {
  22877. fsOptions = fullscreenOptions;
  22878. }
  22879. }
  22880. // This method works as follows:
  22881. // 1. if a fullscreen api is available, use it
  22882. // 1. call requestFullscreen with potential options
  22883. // 2. if we got a promise from above, use it to update isFullscreen()
  22884. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  22885. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  22886. // 3. otherwise, use "fullWindow" mode
  22887. if (this.fsApi_.requestFullscreen) {
  22888. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  22889. // Even on browsers with promise support this may not return a promise
  22890. if (promise) {
  22891. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  22892. }
  22893. return promise;
  22894. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  22895. // we can't take the video.js controls fullscreen but we can go fullscreen
  22896. // with native controls
  22897. this.techCall_('enterFullScreen');
  22898. } else {
  22899. // fullscreen isn't supported so we'll just stretch the video element to
  22900. // fill the viewport
  22901. this.enterFullWindow();
  22902. }
  22903. }
  22904. /**
  22905. * Return the video to its normal size after having been in full screen mode
  22906. *
  22907. * @fires Player#fullscreenchange
  22908. */
  22909. exitFullscreen() {
  22910. const self = this;
  22911. return new Promise((resolve, reject) => {
  22912. function offHandler() {
  22913. self.off('fullscreenerror', errorHandler);
  22914. self.off('fullscreenchange', changeHandler);
  22915. }
  22916. function changeHandler() {
  22917. offHandler();
  22918. resolve();
  22919. }
  22920. function errorHandler(e, err) {
  22921. offHandler();
  22922. reject(err);
  22923. }
  22924. self.one('fullscreenchange', changeHandler);
  22925. self.one('fullscreenerror', errorHandler);
  22926. const promise = self.exitFullscreenHelper_();
  22927. if (promise) {
  22928. promise.then(offHandler, offHandler);
  22929. // map the promise to our resolve/reject methods
  22930. promise.then(resolve, reject);
  22931. }
  22932. });
  22933. }
  22934. exitFullscreenHelper_() {
  22935. if (this.fsApi_.requestFullscreen) {
  22936. const promise = document[this.fsApi_.exitFullscreen]();
  22937. // Even on browsers with promise support this may not return a promise
  22938. if (promise) {
  22939. // we're splitting the promise here, so, we want to catch the
  22940. // potential error so that this chain doesn't have unhandled errors
  22941. silencePromise(promise.then(() => this.isFullscreen(false)));
  22942. }
  22943. return promise;
  22944. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  22945. this.techCall_('exitFullScreen');
  22946. } else {
  22947. this.exitFullWindow();
  22948. }
  22949. }
  22950. /**
  22951. * When fullscreen isn't supported we can stretch the
  22952. * video container to as wide as the browser will let us.
  22953. *
  22954. * @fires Player#enterFullWindow
  22955. */
  22956. enterFullWindow() {
  22957. this.isFullscreen(true);
  22958. this.isFullWindow = true;
  22959. // Storing original doc overflow value to return to when fullscreen is off
  22960. this.docOrigOverflow = document.documentElement.style.overflow;
  22961. // Add listener for esc key to exit fullscreen
  22962. on(document, 'keydown', this.boundFullWindowOnEscKey_);
  22963. // Hide any scroll bars
  22964. document.documentElement.style.overflow = 'hidden';
  22965. // Apply fullscreen styles
  22966. addClass(document.body, 'vjs-full-window');
  22967. /**
  22968. * @event Player#enterFullWindow
  22969. * @type {Event}
  22970. */
  22971. this.trigger('enterFullWindow');
  22972. }
  22973. /**
  22974. * Check for call to either exit full window or
  22975. * full screen on ESC key
  22976. *
  22977. * @param {string} event
  22978. * Event to check for key press
  22979. */
  22980. fullWindowOnEscKey(event) {
  22981. if (keycode.isEventKey(event, 'Esc')) {
  22982. if (this.isFullscreen() === true) {
  22983. if (!this.isFullWindow) {
  22984. this.exitFullscreen();
  22985. } else {
  22986. this.exitFullWindow();
  22987. }
  22988. }
  22989. }
  22990. }
  22991. /**
  22992. * Exit full window
  22993. *
  22994. * @fires Player#exitFullWindow
  22995. */
  22996. exitFullWindow() {
  22997. this.isFullscreen(false);
  22998. this.isFullWindow = false;
  22999. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  23000. // Unhide scroll bars.
  23001. document.documentElement.style.overflow = this.docOrigOverflow;
  23002. // Remove fullscreen styles
  23003. removeClass(document.body, 'vjs-full-window');
  23004. // Resize the box, controller, and poster to original sizes
  23005. // this.positionAll();
  23006. /**
  23007. * @event Player#exitFullWindow
  23008. * @type {Event}
  23009. */
  23010. this.trigger('exitFullWindow');
  23011. }
  23012. /**
  23013. * Disable Picture-in-Picture mode.
  23014. *
  23015. * @param {boolean} value
  23016. * - true will disable Picture-in-Picture mode
  23017. * - false will enable Picture-in-Picture mode
  23018. */
  23019. disablePictureInPicture(value) {
  23020. if (value === undefined) {
  23021. return this.techGet_('disablePictureInPicture');
  23022. }
  23023. this.techCall_('setDisablePictureInPicture', value);
  23024. this.options_.disablePictureInPicture = value;
  23025. this.trigger('disablepictureinpicturechanged');
  23026. }
  23027. /**
  23028. * Check if the player is in Picture-in-Picture mode or tell the player that it
  23029. * is or is not in Picture-in-Picture mode.
  23030. *
  23031. * @param {boolean} [isPiP]
  23032. * Set the players current Picture-in-Picture state
  23033. *
  23034. * @return {boolean}
  23035. * - true if Picture-in-Picture is on and getting
  23036. * - false if Picture-in-Picture is off and getting
  23037. */
  23038. isInPictureInPicture(isPiP) {
  23039. if (isPiP !== undefined) {
  23040. this.isInPictureInPicture_ = !!isPiP;
  23041. this.togglePictureInPictureClass_();
  23042. return;
  23043. }
  23044. return !!this.isInPictureInPicture_;
  23045. }
  23046. /**
  23047. * Create a floating video window always on top of other windows so that users may
  23048. * continue consuming media while they interact with other content sites, or
  23049. * applications on their device.
  23050. *
  23051. * This can use document picture-in-picture or element picture in picture
  23052. *
  23053. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  23054. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  23055. *
  23056. *
  23057. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  23058. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  23059. *
  23060. * @fires Player#enterpictureinpicture
  23061. *
  23062. * @return {Promise}
  23063. * A promise with a Picture-in-Picture window.
  23064. */
  23065. requestPictureInPicture() {
  23066. if (this.options_.enableDocumentPictureInPicture && window.documentPictureInPicture) {
  23067. const pipContainer = document.createElement(this.el().tagName);
  23068. pipContainer.classList = this.el().classList;
  23069. pipContainer.classList.add('vjs-pip-container');
  23070. if (this.posterImage) {
  23071. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  23072. }
  23073. if (this.titleBar) {
  23074. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  23075. }
  23076. pipContainer.appendChild(createEl('p', {
  23077. className: 'vjs-pip-text'
  23078. }, {}, this.localize('Playing in picture-in-picture')));
  23079. return window.documentPictureInPicture.requestWindow({
  23080. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  23081. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  23082. copyStyleSheets: true
  23083. }).then(pipWindow => {
  23084. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  23085. pipWindow.document.body.append(this.el_);
  23086. pipWindow.document.body.classList.add('vjs-pip-window');
  23087. this.player_.isInPictureInPicture(true);
  23088. this.player_.trigger('enterpictureinpicture');
  23089. // Listen for the PiP closing event to move the video back.
  23090. pipWindow.addEventListener('unload', event => {
  23091. const pipVideo = event.target.querySelector('.video-js');
  23092. pipContainer.replaceWith(pipVideo);
  23093. this.player_.isInPictureInPicture(false);
  23094. this.player_.trigger('leavepictureinpicture');
  23095. });
  23096. return pipWindow;
  23097. });
  23098. }
  23099. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  23100. /**
  23101. * This event fires when the player enters picture in picture mode
  23102. *
  23103. * @event Player#enterpictureinpicture
  23104. * @type {Event}
  23105. */
  23106. return this.techGet_('requestPictureInPicture');
  23107. }
  23108. return Promise.reject('No PiP mode is available');
  23109. }
  23110. /**
  23111. * Exit Picture-in-Picture mode.
  23112. *
  23113. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  23114. *
  23115. * @fires Player#leavepictureinpicture
  23116. *
  23117. * @return {Promise}
  23118. * A promise.
  23119. */
  23120. exitPictureInPicture() {
  23121. if (window.documentPictureInPicture && window.documentPictureInPicture.window) {
  23122. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  23123. window.documentPictureInPicture.window.close();
  23124. return Promise.resolve();
  23125. }
  23126. if ('pictureInPictureEnabled' in document) {
  23127. /**
  23128. * This event fires when the player leaves picture in picture mode
  23129. *
  23130. * @event Player#leavepictureinpicture
  23131. * @type {Event}
  23132. */
  23133. return document.exitPictureInPicture();
  23134. }
  23135. }
  23136. /**
  23137. * Called when this Player has focus and a key gets pressed down, or when
  23138. * any Component of this player receives a key press that it doesn't handle.
  23139. * This allows player-wide hotkeys (either as defined below, or optionally
  23140. * by an external function).
  23141. *
  23142. * @param {Event} event
  23143. * The `keydown` event that caused this function to be called.
  23144. *
  23145. * @listens keydown
  23146. */
  23147. handleKeyDown(event) {
  23148. const {
  23149. userActions
  23150. } = this.options_;
  23151. // Bail out if hotkeys are not configured.
  23152. if (!userActions || !userActions.hotkeys) {
  23153. return;
  23154. }
  23155. // Function that determines whether or not to exclude an element from
  23156. // hotkeys handling.
  23157. const excludeElement = el => {
  23158. const tagName = el.tagName.toLowerCase();
  23159. // The first and easiest test is for `contenteditable` elements.
  23160. if (el.isContentEditable) {
  23161. return true;
  23162. }
  23163. // Inputs matching these types will still trigger hotkey handling as
  23164. // they are not text inputs.
  23165. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  23166. if (tagName === 'input') {
  23167. return allowedInputTypes.indexOf(el.type) === -1;
  23168. }
  23169. // The final test is by tag name. These tags will be excluded entirely.
  23170. const excludedTags = ['textarea'];
  23171. return excludedTags.indexOf(tagName) !== -1;
  23172. };
  23173. // Bail out if the user is focused on an interactive form element.
  23174. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  23175. return;
  23176. }
  23177. if (typeof userActions.hotkeys === 'function') {
  23178. userActions.hotkeys.call(this, event);
  23179. } else {
  23180. this.handleHotkeys(event);
  23181. }
  23182. }
  23183. /**
  23184. * Called when this Player receives a hotkey keydown event.
  23185. * Supported player-wide hotkeys are:
  23186. *
  23187. * f - toggle fullscreen
  23188. * m - toggle mute
  23189. * k or Space - toggle play/pause
  23190. *
  23191. * @param {Event} event
  23192. * The `keydown` event that caused this function to be called.
  23193. */
  23194. handleHotkeys(event) {
  23195. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  23196. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  23197. const {
  23198. fullscreenKey = keydownEvent => keycode.isEventKey(keydownEvent, 'f'),
  23199. muteKey = keydownEvent => keycode.isEventKey(keydownEvent, 'm'),
  23200. playPauseKey = keydownEvent => keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space')
  23201. } = hotkeys;
  23202. if (fullscreenKey.call(this, event)) {
  23203. event.preventDefault();
  23204. event.stopPropagation();
  23205. const FSToggle = Component.getComponent('FullscreenToggle');
  23206. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  23207. FSToggle.prototype.handleClick.call(this, event);
  23208. }
  23209. } else if (muteKey.call(this, event)) {
  23210. event.preventDefault();
  23211. event.stopPropagation();
  23212. const MuteToggle = Component.getComponent('MuteToggle');
  23213. MuteToggle.prototype.handleClick.call(this, event);
  23214. } else if (playPauseKey.call(this, event)) {
  23215. event.preventDefault();
  23216. event.stopPropagation();
  23217. const PlayToggle = Component.getComponent('PlayToggle');
  23218. PlayToggle.prototype.handleClick.call(this, event);
  23219. }
  23220. }
  23221. /**
  23222. * Check whether the player can play a given mimetype
  23223. *
  23224. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  23225. *
  23226. * @param {string} type
  23227. * The mimetype to check
  23228. *
  23229. * @return {string}
  23230. * 'probably', 'maybe', or '' (empty string)
  23231. */
  23232. canPlayType(type) {
  23233. let can;
  23234. // Loop through each playback technology in the options order
  23235. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  23236. const techName = j[i];
  23237. let tech = Tech.getTech(techName);
  23238. // Support old behavior of techs being registered as components.
  23239. // Remove once that deprecated behavior is removed.
  23240. if (!tech) {
  23241. tech = Component.getComponent(techName);
  23242. }
  23243. // Check if the current tech is defined before continuing
  23244. if (!tech) {
  23245. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23246. continue;
  23247. }
  23248. // Check if the browser supports this technology
  23249. if (tech.isSupported()) {
  23250. can = tech.canPlayType(type);
  23251. if (can) {
  23252. return can;
  23253. }
  23254. }
  23255. }
  23256. return '';
  23257. }
  23258. /**
  23259. * Select source based on tech-order or source-order
  23260. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  23261. * defaults to tech-order selection
  23262. *
  23263. * @param {Array} sources
  23264. * The sources for a media asset
  23265. *
  23266. * @return {Object|boolean}
  23267. * Object of source and tech order or false
  23268. */
  23269. selectSource(sources) {
  23270. // Get only the techs specified in `techOrder` that exist and are supported by the
  23271. // current platform
  23272. const techs = this.options_.techOrder.map(techName => {
  23273. return [techName, Tech.getTech(techName)];
  23274. }).filter(([techName, tech]) => {
  23275. // Check if the current tech is defined before continuing
  23276. if (tech) {
  23277. // Check if the browser supports this technology
  23278. return tech.isSupported();
  23279. }
  23280. log.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  23281. return false;
  23282. });
  23283. // Iterate over each `innerArray` element once per `outerArray` element and execute
  23284. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  23285. // that value.
  23286. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  23287. let found;
  23288. outerArray.some(outerChoice => {
  23289. return innerArray.some(innerChoice => {
  23290. found = tester(outerChoice, innerChoice);
  23291. if (found) {
  23292. return true;
  23293. }
  23294. });
  23295. });
  23296. return found;
  23297. };
  23298. let foundSourceAndTech;
  23299. const flip = fn => (a, b) => fn(b, a);
  23300. const finder = ([techName, tech], source) => {
  23301. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  23302. return {
  23303. source,
  23304. tech: techName
  23305. };
  23306. }
  23307. };
  23308. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  23309. // to select from them based on their priority.
  23310. if (this.options_.sourceOrder) {
  23311. // Source-first ordering
  23312. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  23313. } else {
  23314. // Tech-first ordering
  23315. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  23316. }
  23317. return foundSourceAndTech || false;
  23318. }
  23319. /**
  23320. * Executes source setting and getting logic
  23321. *
  23322. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23323. * A SourceObject, an array of SourceObjects, or a string referencing
  23324. * a URL to a media source. It is _highly recommended_ that an object
  23325. * or array of objects is used here, so that source selection
  23326. * algorithms can take the `type` into account.
  23327. *
  23328. * If not provided, this method acts as a getter.
  23329. * @param {boolean} isRetry
  23330. * Indicates whether this is being called internally as a result of a retry
  23331. *
  23332. * @return {string|undefined}
  23333. * If the `source` argument is missing, returns the current source
  23334. * URL. Otherwise, returns nothing/undefined.
  23335. */
  23336. handleSrc_(source, isRetry) {
  23337. // getter usage
  23338. if (typeof source === 'undefined') {
  23339. return this.cache_.src || '';
  23340. }
  23341. // Reset retry behavior for new source
  23342. if (this.resetRetryOnError_) {
  23343. this.resetRetryOnError_();
  23344. }
  23345. // filter out invalid sources and turn our source into
  23346. // an array of source objects
  23347. const sources = filterSource(source);
  23348. // if a source was passed in then it is invalid because
  23349. // it was filtered to a zero length Array. So we have to
  23350. // show an error
  23351. if (!sources.length) {
  23352. this.setTimeout(function () {
  23353. this.error({
  23354. code: 4,
  23355. message: this.options_.notSupportedMessage
  23356. });
  23357. }, 0);
  23358. return;
  23359. }
  23360. // initial sources
  23361. this.changingSrc_ = true;
  23362. // Only update the cached source list if we are not retrying a new source after error,
  23363. // since in that case we want to include the failed source(s) in the cache
  23364. if (!isRetry) {
  23365. this.cache_.sources = sources;
  23366. }
  23367. this.updateSourceCaches_(sources[0]);
  23368. // middlewareSource is the source after it has been changed by middleware
  23369. setSource(this, sources[0], (middlewareSource, mws) => {
  23370. this.middleware_ = mws;
  23371. // since sourceSet is async we have to update the cache again after we select a source since
  23372. // the source that is selected could be out of order from the cache update above this callback.
  23373. if (!isRetry) {
  23374. this.cache_.sources = sources;
  23375. }
  23376. this.updateSourceCaches_(middlewareSource);
  23377. const err = this.src_(middlewareSource);
  23378. if (err) {
  23379. if (sources.length > 1) {
  23380. return this.handleSrc_(sources.slice(1));
  23381. }
  23382. this.changingSrc_ = false;
  23383. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  23384. this.setTimeout(function () {
  23385. this.error({
  23386. code: 4,
  23387. message: this.options_.notSupportedMessage
  23388. });
  23389. }, 0);
  23390. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  23391. // this needs a better comment about why this is needed
  23392. this.triggerReady();
  23393. return;
  23394. }
  23395. setTech(mws, this.tech_);
  23396. });
  23397. // Try another available source if this one fails before playback.
  23398. if (sources.length > 1) {
  23399. const retry = () => {
  23400. // Remove the error modal
  23401. this.error(null);
  23402. this.handleSrc_(sources.slice(1), true);
  23403. };
  23404. const stopListeningForErrors = () => {
  23405. this.off('error', retry);
  23406. };
  23407. this.one('error', retry);
  23408. this.one('playing', stopListeningForErrors);
  23409. this.resetRetryOnError_ = () => {
  23410. this.off('error', retry);
  23411. this.off('playing', stopListeningForErrors);
  23412. };
  23413. }
  23414. }
  23415. /**
  23416. * Get or set the video source.
  23417. *
  23418. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23419. * A SourceObject, an array of SourceObjects, or a string referencing
  23420. * a URL to a media source. It is _highly recommended_ that an object
  23421. * or array of objects is used here, so that source selection
  23422. * algorithms can take the `type` into account.
  23423. *
  23424. * If not provided, this method acts as a getter.
  23425. *
  23426. * @return {string|undefined}
  23427. * If the `source` argument is missing, returns the current source
  23428. * URL. Otherwise, returns nothing/undefined.
  23429. */
  23430. src(source) {
  23431. return this.handleSrc_(source, false);
  23432. }
  23433. /**
  23434. * Set the source object on the tech, returns a boolean that indicates whether
  23435. * there is a tech that can play the source or not
  23436. *
  23437. * @param {Tech~SourceObject} source
  23438. * The source object to set on the Tech
  23439. *
  23440. * @return {boolean}
  23441. * - True if there is no Tech to playback this source
  23442. * - False otherwise
  23443. *
  23444. * @private
  23445. */
  23446. src_(source) {
  23447. const sourceTech = this.selectSource([source]);
  23448. if (!sourceTech) {
  23449. return true;
  23450. }
  23451. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  23452. this.changingSrc_ = true;
  23453. // load this technology with the chosen source
  23454. this.loadTech_(sourceTech.tech, sourceTech.source);
  23455. this.tech_.ready(() => {
  23456. this.changingSrc_ = false;
  23457. });
  23458. return false;
  23459. }
  23460. // wait until the tech is ready to set the source
  23461. // and set it synchronously if possible (#2326)
  23462. this.ready(function () {
  23463. // The setSource tech method was added with source handlers
  23464. // so older techs won't support it
  23465. // We need to check the direct prototype for the case where subclasses
  23466. // of the tech do not support source handlers
  23467. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  23468. this.techCall_('setSource', source);
  23469. } else {
  23470. this.techCall_('src', source.src);
  23471. }
  23472. this.changingSrc_ = false;
  23473. }, true);
  23474. return false;
  23475. }
  23476. /**
  23477. * Begin loading the src data.
  23478. */
  23479. load() {
  23480. this.techCall_('load');
  23481. }
  23482. /**
  23483. * Reset the player. Loads the first tech in the techOrder,
  23484. * removes all the text tracks in the existing `tech`,
  23485. * and calls `reset` on the `tech`.
  23486. */
  23487. reset() {
  23488. if (this.paused()) {
  23489. this.doReset_();
  23490. } else {
  23491. const playPromise = this.play();
  23492. silencePromise(playPromise.then(() => this.doReset_()));
  23493. }
  23494. }
  23495. doReset_() {
  23496. if (this.tech_) {
  23497. this.tech_.clearTracks('text');
  23498. }
  23499. this.resetCache_();
  23500. this.poster('');
  23501. this.loadTech_(this.options_.techOrder[0], null);
  23502. this.techCall_('reset');
  23503. this.resetControlBarUI_();
  23504. if (isEvented(this)) {
  23505. this.trigger('playerreset');
  23506. }
  23507. }
  23508. /**
  23509. * Reset Control Bar's UI by calling sub-methods that reset
  23510. * all of Control Bar's components
  23511. */
  23512. resetControlBarUI_() {
  23513. this.resetProgressBar_();
  23514. this.resetPlaybackRate_();
  23515. this.resetVolumeBar_();
  23516. }
  23517. /**
  23518. * Reset tech's progress so progress bar is reset in the UI
  23519. */
  23520. resetProgressBar_() {
  23521. this.currentTime(0);
  23522. const {
  23523. currentTimeDisplay,
  23524. durationDisplay,
  23525. progressControl,
  23526. remainingTimeDisplay
  23527. } = this.controlBar || {};
  23528. const {
  23529. seekBar
  23530. } = progressControl || {};
  23531. if (currentTimeDisplay) {
  23532. currentTimeDisplay.updateContent();
  23533. }
  23534. if (durationDisplay) {
  23535. durationDisplay.updateContent();
  23536. }
  23537. if (remainingTimeDisplay) {
  23538. remainingTimeDisplay.updateContent();
  23539. }
  23540. if (seekBar) {
  23541. seekBar.update();
  23542. if (seekBar.loadProgressBar) {
  23543. seekBar.loadProgressBar.update();
  23544. }
  23545. }
  23546. }
  23547. /**
  23548. * Reset Playback ratio
  23549. */
  23550. resetPlaybackRate_() {
  23551. this.playbackRate(this.defaultPlaybackRate());
  23552. this.handleTechRateChange_();
  23553. }
  23554. /**
  23555. * Reset Volume bar
  23556. */
  23557. resetVolumeBar_() {
  23558. this.volume(1.0);
  23559. this.trigger('volumechange');
  23560. }
  23561. /**
  23562. * Returns all of the current source objects.
  23563. *
  23564. * @return {Tech~SourceObject[]}
  23565. * The current source objects
  23566. */
  23567. currentSources() {
  23568. const source = this.currentSource();
  23569. const sources = [];
  23570. // assume `{}` or `{ src }`
  23571. if (Object.keys(source).length !== 0) {
  23572. sources.push(source);
  23573. }
  23574. return this.cache_.sources || sources;
  23575. }
  23576. /**
  23577. * Returns the current source object.
  23578. *
  23579. * @return {Tech~SourceObject}
  23580. * The current source object
  23581. */
  23582. currentSource() {
  23583. return this.cache_.source || {};
  23584. }
  23585. /**
  23586. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  23587. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  23588. *
  23589. * @return {string}
  23590. * The current source
  23591. */
  23592. currentSrc() {
  23593. return this.currentSource() && this.currentSource().src || '';
  23594. }
  23595. /**
  23596. * Get the current source type e.g. video/mp4
  23597. * This can allow you rebuild the current source object so that you could load the same
  23598. * source and tech later
  23599. *
  23600. * @return {string}
  23601. * The source MIME type
  23602. */
  23603. currentType() {
  23604. return this.currentSource() && this.currentSource().type || '';
  23605. }
  23606. /**
  23607. * Get or set the preload attribute
  23608. *
  23609. * @param {boolean} [value]
  23610. * - true means that we should preload
  23611. * - false means that we should not preload
  23612. *
  23613. * @return {string}
  23614. * The preload attribute value when getting
  23615. */
  23616. preload(value) {
  23617. if (value !== undefined) {
  23618. this.techCall_('setPreload', value);
  23619. this.options_.preload = value;
  23620. return;
  23621. }
  23622. return this.techGet_('preload');
  23623. }
  23624. /**
  23625. * Get or set the autoplay option. When this is a boolean it will
  23626. * modify the attribute on the tech. When this is a string the attribute on
  23627. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  23628. *
  23629. * @param {boolean|string} [value]
  23630. * - true: autoplay using the browser behavior
  23631. * - false: do not autoplay
  23632. * - 'play': call play() on every loadstart
  23633. * - 'muted': call muted() then play() on every loadstart
  23634. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  23635. * - *: values other than those listed here will be set `autoplay` to true
  23636. *
  23637. * @return {boolean|string}
  23638. * The current value of autoplay when getting
  23639. */
  23640. autoplay(value) {
  23641. // getter usage
  23642. if (value === undefined) {
  23643. return this.options_.autoplay || false;
  23644. }
  23645. let techAutoplay;
  23646. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  23647. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  23648. this.options_.autoplay = value;
  23649. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  23650. techAutoplay = false;
  23651. // any falsy value sets autoplay to false in the browser,
  23652. // lets do the same
  23653. } else if (!value) {
  23654. this.options_.autoplay = false;
  23655. // any other value (ie truthy) sets autoplay to true
  23656. } else {
  23657. this.options_.autoplay = true;
  23658. }
  23659. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  23660. // if we don't have a tech then we do not queue up
  23661. // a setAutoplay call on tech ready. We do this because the
  23662. // autoplay option will be passed in the constructor and we
  23663. // do not need to set it twice
  23664. if (this.tech_) {
  23665. this.techCall_('setAutoplay', techAutoplay);
  23666. }
  23667. }
  23668. /**
  23669. * Set or unset the playsinline attribute.
  23670. * Playsinline tells the browser that non-fullscreen playback is preferred.
  23671. *
  23672. * @param {boolean} [value]
  23673. * - true means that we should try to play inline by default
  23674. * - false means that we should use the browser's default playback mode,
  23675. * which in most cases is inline. iOS Safari is a notable exception
  23676. * and plays fullscreen by default.
  23677. *
  23678. * @return {string|Player}
  23679. * - the current value of playsinline
  23680. * - the player when setting
  23681. *
  23682. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  23683. */
  23684. playsinline(value) {
  23685. if (value !== undefined) {
  23686. this.techCall_('setPlaysinline', value);
  23687. this.options_.playsinline = value;
  23688. return this;
  23689. }
  23690. return this.techGet_('playsinline');
  23691. }
  23692. /**
  23693. * Get or set the loop attribute on the video element.
  23694. *
  23695. * @param {boolean} [value]
  23696. * - true means that we should loop the video
  23697. * - false means that we should not loop the video
  23698. *
  23699. * @return {boolean}
  23700. * The current value of loop when getting
  23701. */
  23702. loop(value) {
  23703. if (value !== undefined) {
  23704. this.techCall_('setLoop', value);
  23705. this.options_.loop = value;
  23706. return;
  23707. }
  23708. return this.techGet_('loop');
  23709. }
  23710. /**
  23711. * Get or set the poster image source url
  23712. *
  23713. * @fires Player#posterchange
  23714. *
  23715. * @param {string} [src]
  23716. * Poster image source URL
  23717. *
  23718. * @return {string}
  23719. * The current value of poster when getting
  23720. */
  23721. poster(src) {
  23722. if (src === undefined) {
  23723. return this.poster_;
  23724. }
  23725. // The correct way to remove a poster is to set as an empty string
  23726. // other falsey values will throw errors
  23727. if (!src) {
  23728. src = '';
  23729. }
  23730. if (src === this.poster_) {
  23731. return;
  23732. }
  23733. // update the internal poster variable
  23734. this.poster_ = src;
  23735. // update the tech's poster
  23736. this.techCall_('setPoster', src);
  23737. this.isPosterFromTech_ = false;
  23738. // alert components that the poster has been set
  23739. /**
  23740. * This event fires when the poster image is changed on the player.
  23741. *
  23742. * @event Player#posterchange
  23743. * @type {Event}
  23744. */
  23745. this.trigger('posterchange');
  23746. }
  23747. /**
  23748. * Some techs (e.g. YouTube) can provide a poster source in an
  23749. * asynchronous way. We want the poster component to use this
  23750. * poster source so that it covers up the tech's controls.
  23751. * (YouTube's play button). However we only want to use this
  23752. * source if the player user hasn't set a poster through
  23753. * the normal APIs.
  23754. *
  23755. * @fires Player#posterchange
  23756. * @listens Tech#posterchange
  23757. * @private
  23758. */
  23759. handleTechPosterChange_() {
  23760. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  23761. const newPoster = this.tech_.poster() || '';
  23762. if (newPoster !== this.poster_) {
  23763. this.poster_ = newPoster;
  23764. this.isPosterFromTech_ = true;
  23765. // Let components know the poster has changed
  23766. this.trigger('posterchange');
  23767. }
  23768. }
  23769. }
  23770. /**
  23771. * Get or set whether or not the controls are showing.
  23772. *
  23773. * @fires Player#controlsenabled
  23774. *
  23775. * @param {boolean} [bool]
  23776. * - true to turn controls on
  23777. * - false to turn controls off
  23778. *
  23779. * @return {boolean}
  23780. * The current value of controls when getting
  23781. */
  23782. controls(bool) {
  23783. if (bool === undefined) {
  23784. return !!this.controls_;
  23785. }
  23786. bool = !!bool;
  23787. // Don't trigger a change event unless it actually changed
  23788. if (this.controls_ === bool) {
  23789. return;
  23790. }
  23791. this.controls_ = bool;
  23792. if (this.usingNativeControls()) {
  23793. this.techCall_('setControls', bool);
  23794. }
  23795. if (this.controls_) {
  23796. this.removeClass('vjs-controls-disabled');
  23797. this.addClass('vjs-controls-enabled');
  23798. /**
  23799. * @event Player#controlsenabled
  23800. * @type {Event}
  23801. */
  23802. this.trigger('controlsenabled');
  23803. if (!this.usingNativeControls()) {
  23804. this.addTechControlsListeners_();
  23805. }
  23806. } else {
  23807. this.removeClass('vjs-controls-enabled');
  23808. this.addClass('vjs-controls-disabled');
  23809. /**
  23810. * @event Player#controlsdisabled
  23811. * @type {Event}
  23812. */
  23813. this.trigger('controlsdisabled');
  23814. if (!this.usingNativeControls()) {
  23815. this.removeTechControlsListeners_();
  23816. }
  23817. }
  23818. }
  23819. /**
  23820. * Toggle native controls on/off. Native controls are the controls built into
  23821. * devices (e.g. default iPhone controls) or other techs
  23822. * (e.g. Vimeo Controls)
  23823. * **This should only be set by the current tech, because only the tech knows
  23824. * if it can support native controls**
  23825. *
  23826. * @fires Player#usingnativecontrols
  23827. * @fires Player#usingcustomcontrols
  23828. *
  23829. * @param {boolean} [bool]
  23830. * - true to turn native controls on
  23831. * - false to turn native controls off
  23832. *
  23833. * @return {boolean}
  23834. * The current value of native controls when getting
  23835. */
  23836. usingNativeControls(bool) {
  23837. if (bool === undefined) {
  23838. return !!this.usingNativeControls_;
  23839. }
  23840. bool = !!bool;
  23841. // Don't trigger a change event unless it actually changed
  23842. if (this.usingNativeControls_ === bool) {
  23843. return;
  23844. }
  23845. this.usingNativeControls_ = bool;
  23846. if (this.usingNativeControls_) {
  23847. this.addClass('vjs-using-native-controls');
  23848. /**
  23849. * player is using the native device controls
  23850. *
  23851. * @event Player#usingnativecontrols
  23852. * @type {Event}
  23853. */
  23854. this.trigger('usingnativecontrols');
  23855. } else {
  23856. this.removeClass('vjs-using-native-controls');
  23857. /**
  23858. * player is using the custom HTML controls
  23859. *
  23860. * @event Player#usingcustomcontrols
  23861. * @type {Event}
  23862. */
  23863. this.trigger('usingcustomcontrols');
  23864. }
  23865. }
  23866. /**
  23867. * Set or get the current MediaError
  23868. *
  23869. * @fires Player#error
  23870. *
  23871. * @param {MediaError|string|number} [err]
  23872. * A MediaError or a string/number to be turned
  23873. * into a MediaError
  23874. *
  23875. * @return {MediaError|null}
  23876. * The current MediaError when getting (or null)
  23877. */
  23878. error(err) {
  23879. if (err === undefined) {
  23880. return this.error_ || null;
  23881. }
  23882. // allow hooks to modify error object
  23883. hooks('beforeerror').forEach(hookFunction => {
  23884. const newErr = hookFunction(this, err);
  23885. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  23886. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  23887. return;
  23888. }
  23889. err = newErr;
  23890. });
  23891. // Suppress the first error message for no compatible source until
  23892. // user interaction
  23893. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  23894. const triggerSuppressedError = function () {
  23895. this.error(err);
  23896. };
  23897. this.options_.suppressNotSupportedError = false;
  23898. this.any(['click', 'touchstart'], triggerSuppressedError);
  23899. this.one('loadstart', function () {
  23900. this.off(['click', 'touchstart'], triggerSuppressedError);
  23901. });
  23902. return;
  23903. }
  23904. // restoring to default
  23905. if (err === null) {
  23906. this.error_ = err;
  23907. this.removeClass('vjs-error');
  23908. if (this.errorDisplay) {
  23909. this.errorDisplay.close();
  23910. }
  23911. return;
  23912. }
  23913. this.error_ = new MediaError(err);
  23914. // add the vjs-error classname to the player
  23915. this.addClass('vjs-error');
  23916. // log the name of the error type and any message
  23917. // IE11 logs "[object object]" and required you to expand message to see error object
  23918. log.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  23919. /**
  23920. * @event Player#error
  23921. * @type {Event}
  23922. */
  23923. this.trigger('error');
  23924. // notify hooks of the per player error
  23925. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  23926. return;
  23927. }
  23928. /**
  23929. * Report user activity
  23930. *
  23931. * @param {Object} event
  23932. * Event object
  23933. */
  23934. reportUserActivity(event) {
  23935. this.userActivity_ = true;
  23936. }
  23937. /**
  23938. * Get/set if user is active
  23939. *
  23940. * @fires Player#useractive
  23941. * @fires Player#userinactive
  23942. *
  23943. * @param {boolean} [bool]
  23944. * - true if the user is active
  23945. * - false if the user is inactive
  23946. *
  23947. * @return {boolean}
  23948. * The current value of userActive when getting
  23949. */
  23950. userActive(bool) {
  23951. if (bool === undefined) {
  23952. return this.userActive_;
  23953. }
  23954. bool = !!bool;
  23955. if (bool === this.userActive_) {
  23956. return;
  23957. }
  23958. this.userActive_ = bool;
  23959. if (this.userActive_) {
  23960. this.userActivity_ = true;
  23961. this.removeClass('vjs-user-inactive');
  23962. this.addClass('vjs-user-active');
  23963. /**
  23964. * @event Player#useractive
  23965. * @type {Event}
  23966. */
  23967. this.trigger('useractive');
  23968. return;
  23969. }
  23970. // Chrome/Safari/IE have bugs where when you change the cursor it can
  23971. // trigger a mousemove event. This causes an issue when you're hiding
  23972. // the cursor when the user is inactive, and a mousemove signals user
  23973. // activity. Making it impossible to go into inactive mode. Specifically
  23974. // this happens in fullscreen when we really need to hide the cursor.
  23975. //
  23976. // When this gets resolved in ALL browsers it can be removed
  23977. // https://code.google.com/p/chromium/issues/detail?id=103041
  23978. if (this.tech_) {
  23979. this.tech_.one('mousemove', function (e) {
  23980. e.stopPropagation();
  23981. e.preventDefault();
  23982. });
  23983. }
  23984. this.userActivity_ = false;
  23985. this.removeClass('vjs-user-active');
  23986. this.addClass('vjs-user-inactive');
  23987. /**
  23988. * @event Player#userinactive
  23989. * @type {Event}
  23990. */
  23991. this.trigger('userinactive');
  23992. }
  23993. /**
  23994. * Listen for user activity based on timeout value
  23995. *
  23996. * @private
  23997. */
  23998. listenForUserActivity_() {
  23999. let mouseInProgress;
  24000. let lastMoveX;
  24001. let lastMoveY;
  24002. const handleActivity = bind_(this, this.reportUserActivity);
  24003. const handleMouseMove = function (e) {
  24004. // #1068 - Prevent mousemove spamming
  24005. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  24006. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  24007. lastMoveX = e.screenX;
  24008. lastMoveY = e.screenY;
  24009. handleActivity();
  24010. }
  24011. };
  24012. const handleMouseDown = function () {
  24013. handleActivity();
  24014. // For as long as the they are touching the device or have their mouse down,
  24015. // we consider them active even if they're not moving their finger or mouse.
  24016. // So we want to continue to update that they are active
  24017. this.clearInterval(mouseInProgress);
  24018. // Setting userActivity=true now and setting the interval to the same time
  24019. // as the activityCheck interval (250) should ensure we never miss the
  24020. // next activityCheck
  24021. mouseInProgress = this.setInterval(handleActivity, 250);
  24022. };
  24023. const handleMouseUpAndMouseLeave = function (event) {
  24024. handleActivity();
  24025. // Stop the interval that maintains activity if the mouse/touch is down
  24026. this.clearInterval(mouseInProgress);
  24027. };
  24028. // Any mouse movement will be considered user activity
  24029. this.on('mousedown', handleMouseDown);
  24030. this.on('mousemove', handleMouseMove);
  24031. this.on('mouseup', handleMouseUpAndMouseLeave);
  24032. this.on('mouseleave', handleMouseUpAndMouseLeave);
  24033. const controlBar = this.getChild('controlBar');
  24034. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  24035. // controlBar would no longer be hidden by default timeout.
  24036. if (controlBar && !IS_IOS && !IS_ANDROID) {
  24037. controlBar.on('mouseenter', function (event) {
  24038. if (this.player().options_.inactivityTimeout !== 0) {
  24039. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  24040. }
  24041. this.player().options_.inactivityTimeout = 0;
  24042. });
  24043. controlBar.on('mouseleave', function (event) {
  24044. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  24045. });
  24046. }
  24047. // Listen for keyboard navigation
  24048. // Shouldn't need to use inProgress interval because of key repeat
  24049. this.on('keydown', handleActivity);
  24050. this.on('keyup', handleActivity);
  24051. // Run an interval every 250 milliseconds instead of stuffing everything into
  24052. // the mousemove/touchmove function itself, to prevent performance degradation.
  24053. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  24054. // then gets picked up by this loop
  24055. // http://ejohn.org/blog/learning-from-twitter/
  24056. let inactivityTimeout;
  24057. this.setInterval(function () {
  24058. // Check to see if mouse/touch activity has happened
  24059. if (!this.userActivity_) {
  24060. return;
  24061. }
  24062. // Reset the activity tracker
  24063. this.userActivity_ = false;
  24064. // If the user state was inactive, set the state to active
  24065. this.userActive(true);
  24066. // Clear any existing inactivity timeout to start the timer over
  24067. this.clearTimeout(inactivityTimeout);
  24068. const timeout = this.options_.inactivityTimeout;
  24069. if (timeout <= 0) {
  24070. return;
  24071. }
  24072. // In <timeout> milliseconds, if no more activity has occurred the
  24073. // user will be considered inactive
  24074. inactivityTimeout = this.setTimeout(function () {
  24075. // Protect against the case where the inactivityTimeout can trigger just
  24076. // before the next user activity is picked up by the activity check loop
  24077. // causing a flicker
  24078. if (!this.userActivity_) {
  24079. this.userActive(false);
  24080. }
  24081. }, timeout);
  24082. }, 250);
  24083. }
  24084. /**
  24085. * Gets or sets the current playback rate. A playback rate of
  24086. * 1.0 represents normal speed and 0.5 would indicate half-speed
  24087. * playback, for instance.
  24088. *
  24089. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  24090. *
  24091. * @param {number} [rate]
  24092. * New playback rate to set.
  24093. *
  24094. * @return {number}
  24095. * The current playback rate when getting or 1.0
  24096. */
  24097. playbackRate(rate) {
  24098. if (rate !== undefined) {
  24099. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  24100. // that is registered above
  24101. this.techCall_('setPlaybackRate', rate);
  24102. return;
  24103. }
  24104. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24105. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  24106. }
  24107. return 1.0;
  24108. }
  24109. /**
  24110. * Gets or sets the current default playback rate. A default playback rate of
  24111. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  24112. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  24113. * not the current playbackRate.
  24114. *
  24115. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  24116. *
  24117. * @param {number} [rate]
  24118. * New default playback rate to set.
  24119. *
  24120. * @return {number|Player}
  24121. * - The default playback rate when getting or 1.0
  24122. * - the player when setting
  24123. */
  24124. defaultPlaybackRate(rate) {
  24125. if (rate !== undefined) {
  24126. return this.techCall_('setDefaultPlaybackRate', rate);
  24127. }
  24128. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24129. return this.techGet_('defaultPlaybackRate');
  24130. }
  24131. return 1.0;
  24132. }
  24133. /**
  24134. * Gets or sets the audio flag
  24135. *
  24136. * @param {boolean} bool
  24137. * - true signals that this is an audio player
  24138. * - false signals that this is not an audio player
  24139. *
  24140. * @return {boolean}
  24141. * The current value of isAudio when getting
  24142. */
  24143. isAudio(bool) {
  24144. if (bool !== undefined) {
  24145. this.isAudio_ = !!bool;
  24146. return;
  24147. }
  24148. return !!this.isAudio_;
  24149. }
  24150. enableAudioOnlyUI_() {
  24151. // Update styling immediately to show the control bar so we can get its height
  24152. this.addClass('vjs-audio-only-mode');
  24153. const playerChildren = this.children();
  24154. const controlBar = this.getChild('ControlBar');
  24155. const controlBarHeight = controlBar && controlBar.currentHeight();
  24156. // Hide all player components except the control bar. Control bar components
  24157. // needed only for video are hidden with CSS
  24158. playerChildren.forEach(child => {
  24159. if (child === controlBar) {
  24160. return;
  24161. }
  24162. if (child.el_ && !child.hasClass('vjs-hidden')) {
  24163. child.hide();
  24164. this.audioOnlyCache_.hiddenChildren.push(child);
  24165. }
  24166. });
  24167. this.audioOnlyCache_.playerHeight = this.currentHeight();
  24168. // Set the player height the same as the control bar
  24169. this.height(controlBarHeight);
  24170. this.trigger('audioonlymodechange');
  24171. }
  24172. disableAudioOnlyUI_() {
  24173. this.removeClass('vjs-audio-only-mode');
  24174. // Show player components that were previously hidden
  24175. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  24176. // Reset player height
  24177. this.height(this.audioOnlyCache_.playerHeight);
  24178. this.trigger('audioonlymodechange');
  24179. }
  24180. /**
  24181. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  24182. *
  24183. * Setting this to `true` will hide all player components except the control bar,
  24184. * as well as control bar components needed only for video.
  24185. *
  24186. * @param {boolean} [value]
  24187. * The value to set audioOnlyMode to.
  24188. *
  24189. * @return {Promise|boolean}
  24190. * A Promise is returned when setting the state, and a boolean when getting
  24191. * the present state
  24192. */
  24193. audioOnlyMode(value) {
  24194. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  24195. return this.audioOnlyMode_;
  24196. }
  24197. this.audioOnlyMode_ = value;
  24198. // Enable Audio Only Mode
  24199. if (value) {
  24200. const exitPromises = [];
  24201. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  24202. if (this.isInPictureInPicture()) {
  24203. exitPromises.push(this.exitPictureInPicture());
  24204. }
  24205. if (this.isFullscreen()) {
  24206. exitPromises.push(this.exitFullscreen());
  24207. }
  24208. if (this.audioPosterMode()) {
  24209. exitPromises.push(this.audioPosterMode(false));
  24210. }
  24211. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  24212. }
  24213. // Disable Audio Only Mode
  24214. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  24215. }
  24216. enablePosterModeUI_() {
  24217. // Hide the video element and show the poster image to enable posterModeUI
  24218. const tech = this.tech_ && this.tech_;
  24219. tech.hide();
  24220. this.addClass('vjs-audio-poster-mode');
  24221. this.trigger('audiopostermodechange');
  24222. }
  24223. disablePosterModeUI_() {
  24224. // Show the video element and hide the poster image to disable posterModeUI
  24225. const tech = this.tech_ && this.tech_;
  24226. tech.show();
  24227. this.removeClass('vjs-audio-poster-mode');
  24228. this.trigger('audiopostermodechange');
  24229. }
  24230. /**
  24231. * Get the current audioPosterMode state or set audioPosterMode to true or false
  24232. *
  24233. * @param {boolean} [value]
  24234. * The value to set audioPosterMode to.
  24235. *
  24236. * @return {Promise|boolean}
  24237. * A Promise is returned when setting the state, and a boolean when getting
  24238. * the present state
  24239. */
  24240. audioPosterMode(value) {
  24241. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  24242. return this.audioPosterMode_;
  24243. }
  24244. this.audioPosterMode_ = value;
  24245. if (value) {
  24246. if (this.audioOnlyMode()) {
  24247. const audioOnlyModePromise = this.audioOnlyMode(false);
  24248. return audioOnlyModePromise.then(() => {
  24249. // enable audio poster mode after audio only mode is disabled
  24250. this.enablePosterModeUI_();
  24251. });
  24252. }
  24253. return Promise.resolve().then(() => {
  24254. // enable audio poster mode
  24255. this.enablePosterModeUI_();
  24256. });
  24257. }
  24258. return Promise.resolve().then(() => {
  24259. // disable audio poster mode
  24260. this.disablePosterModeUI_();
  24261. });
  24262. }
  24263. /**
  24264. * A helper method for adding a {@link TextTrack} to our
  24265. * {@link TextTrackList}.
  24266. *
  24267. * In addition to the W3C settings we allow adding additional info through options.
  24268. *
  24269. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  24270. *
  24271. * @param {string} [kind]
  24272. * the kind of TextTrack you are adding
  24273. *
  24274. * @param {string} [label]
  24275. * the label to give the TextTrack label
  24276. *
  24277. * @param {string} [language]
  24278. * the language to set on the TextTrack
  24279. *
  24280. * @return {TextTrack|undefined}
  24281. * the TextTrack that was added or undefined
  24282. * if there is no tech
  24283. */
  24284. addTextTrack(kind, label, language) {
  24285. if (this.tech_) {
  24286. return this.tech_.addTextTrack(kind, label, language);
  24287. }
  24288. }
  24289. /**
  24290. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  24291. *
  24292. * @param {Object} options
  24293. * Options to pass to {@link HTMLTrackElement} during creation. See
  24294. * {@link HTMLTrackElement} for object properties that you should use.
  24295. *
  24296. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  24297. * from the TextTrackList and HtmlTrackElementList
  24298. * after a source change
  24299. *
  24300. * @return { import('./tracks/html-track-element').default }
  24301. * the HTMLTrackElement that was created and added
  24302. * to the HtmlTrackElementList and the remote
  24303. * TextTrackList
  24304. *
  24305. */
  24306. addRemoteTextTrack(options, manualCleanup) {
  24307. if (this.tech_) {
  24308. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  24309. }
  24310. }
  24311. /**
  24312. * Remove a remote {@link TextTrack} from the respective
  24313. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  24314. *
  24315. * @param {Object} track
  24316. * Remote {@link TextTrack} to remove
  24317. *
  24318. * @return {undefined}
  24319. * does not return anything
  24320. */
  24321. removeRemoteTextTrack(obj = {}) {
  24322. let {
  24323. track
  24324. } = obj;
  24325. if (!track) {
  24326. track = obj;
  24327. }
  24328. // destructure the input into an object with a track argument, defaulting to arguments[0]
  24329. // default the whole argument to an empty object if nothing was passed in
  24330. if (this.tech_) {
  24331. return this.tech_.removeRemoteTextTrack(track);
  24332. }
  24333. }
  24334. /**
  24335. * Gets available media playback quality metrics as specified by the W3C's Media
  24336. * Playback Quality API.
  24337. *
  24338. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  24339. *
  24340. * @return {Object|undefined}
  24341. * An object with supported media playback quality metrics or undefined if there
  24342. * is no tech or the tech does not support it.
  24343. */
  24344. getVideoPlaybackQuality() {
  24345. return this.techGet_('getVideoPlaybackQuality');
  24346. }
  24347. /**
  24348. * Get video width
  24349. *
  24350. * @return {number}
  24351. * current video width
  24352. */
  24353. videoWidth() {
  24354. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  24355. }
  24356. /**
  24357. * Get video height
  24358. *
  24359. * @return {number}
  24360. * current video height
  24361. */
  24362. videoHeight() {
  24363. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  24364. }
  24365. /**
  24366. * The player's language code.
  24367. *
  24368. * Changing the language will trigger
  24369. * [languagechange]{@link Player#event:languagechange}
  24370. * which Components can use to update control text.
  24371. * ClickableComponent will update its control text by default on
  24372. * [languagechange]{@link Player#event:languagechange}.
  24373. *
  24374. * @fires Player#languagechange
  24375. *
  24376. * @param {string} [code]
  24377. * the language code to set the player to
  24378. *
  24379. * @return {string}
  24380. * The current language code when getting
  24381. */
  24382. language(code) {
  24383. if (code === undefined) {
  24384. return this.language_;
  24385. }
  24386. if (this.language_ !== String(code).toLowerCase()) {
  24387. this.language_ = String(code).toLowerCase();
  24388. // during first init, it's possible some things won't be evented
  24389. if (isEvented(this)) {
  24390. /**
  24391. * fires when the player language change
  24392. *
  24393. * @event Player#languagechange
  24394. * @type {Event}
  24395. */
  24396. this.trigger('languagechange');
  24397. }
  24398. }
  24399. }
  24400. /**
  24401. * Get the player's language dictionary
  24402. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  24403. * Languages specified directly in the player options have precedence
  24404. *
  24405. * @return {Array}
  24406. * An array of of supported languages
  24407. */
  24408. languages() {
  24409. return merge(Player.prototype.options_.languages, this.languages_);
  24410. }
  24411. /**
  24412. * returns a JavaScript object representing the current track
  24413. * information. **DOES not return it as JSON**
  24414. *
  24415. * @return {Object}
  24416. * Object representing the current of track info
  24417. */
  24418. toJSON() {
  24419. const options = merge(this.options_);
  24420. const tracks = options.tracks;
  24421. options.tracks = [];
  24422. for (let i = 0; i < tracks.length; i++) {
  24423. let track = tracks[i];
  24424. // deep merge tracks and null out player so no circular references
  24425. track = merge(track);
  24426. track.player = undefined;
  24427. options.tracks[i] = track;
  24428. }
  24429. return options;
  24430. }
  24431. /**
  24432. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  24433. * component) that immediately overlays the player with arbitrary
  24434. * content and removes itself when closed.
  24435. *
  24436. * @param {string|Function|Element|Array|null} content
  24437. * Same as {@link ModalDialog#content}'s param of the same name.
  24438. * The most straight-forward usage is to provide a string or DOM
  24439. * element.
  24440. *
  24441. * @param {Object} [options]
  24442. * Extra options which will be passed on to the {@link ModalDialog}.
  24443. *
  24444. * @return {ModalDialog}
  24445. * the {@link ModalDialog} that was created
  24446. */
  24447. createModal(content, options) {
  24448. options = options || {};
  24449. options.content = content || '';
  24450. const modal = new ModalDialog(this, options);
  24451. this.addChild(modal);
  24452. modal.on('dispose', () => {
  24453. this.removeChild(modal);
  24454. });
  24455. modal.open();
  24456. return modal;
  24457. }
  24458. /**
  24459. * Change breakpoint classes when the player resizes.
  24460. *
  24461. * @private
  24462. */
  24463. updateCurrentBreakpoint_() {
  24464. if (!this.responsive()) {
  24465. return;
  24466. }
  24467. const currentBreakpoint = this.currentBreakpoint();
  24468. const currentWidth = this.currentWidth();
  24469. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  24470. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  24471. const maxWidth = this.breakpoints_[candidateBreakpoint];
  24472. if (currentWidth <= maxWidth) {
  24473. // The current breakpoint did not change, nothing to do.
  24474. if (currentBreakpoint === candidateBreakpoint) {
  24475. return;
  24476. }
  24477. // Only remove a class if there is a current breakpoint.
  24478. if (currentBreakpoint) {
  24479. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  24480. }
  24481. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  24482. this.breakpoint_ = candidateBreakpoint;
  24483. break;
  24484. }
  24485. }
  24486. }
  24487. /**
  24488. * Removes the current breakpoint.
  24489. *
  24490. * @private
  24491. */
  24492. removeCurrentBreakpoint_() {
  24493. const className = this.currentBreakpointClass();
  24494. this.breakpoint_ = '';
  24495. if (className) {
  24496. this.removeClass(className);
  24497. }
  24498. }
  24499. /**
  24500. * Get or set breakpoints on the player.
  24501. *
  24502. * Calling this method with an object or `true` will remove any previous
  24503. * custom breakpoints and start from the defaults again.
  24504. *
  24505. * @param {Object|boolean} [breakpoints]
  24506. * If an object is given, it can be used to provide custom
  24507. * breakpoints. If `true` is given, will set default breakpoints.
  24508. * If this argument is not given, will simply return the current
  24509. * breakpoints.
  24510. *
  24511. * @param {number} [breakpoints.tiny]
  24512. * The maximum width for the "vjs-layout-tiny" class.
  24513. *
  24514. * @param {number} [breakpoints.xsmall]
  24515. * The maximum width for the "vjs-layout-x-small" class.
  24516. *
  24517. * @param {number} [breakpoints.small]
  24518. * The maximum width for the "vjs-layout-small" class.
  24519. *
  24520. * @param {number} [breakpoints.medium]
  24521. * The maximum width for the "vjs-layout-medium" class.
  24522. *
  24523. * @param {number} [breakpoints.large]
  24524. * The maximum width for the "vjs-layout-large" class.
  24525. *
  24526. * @param {number} [breakpoints.xlarge]
  24527. * The maximum width for the "vjs-layout-x-large" class.
  24528. *
  24529. * @param {number} [breakpoints.huge]
  24530. * The maximum width for the "vjs-layout-huge" class.
  24531. *
  24532. * @return {Object}
  24533. * An object mapping breakpoint names to maximum width values.
  24534. */
  24535. breakpoints(breakpoints) {
  24536. // Used as a getter.
  24537. if (breakpoints === undefined) {
  24538. return Object.assign(this.breakpoints_);
  24539. }
  24540. this.breakpoint_ = '';
  24541. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  24542. // When breakpoint definitions change, we need to update the currently
  24543. // selected breakpoint.
  24544. this.updateCurrentBreakpoint_();
  24545. // Clone the breakpoints before returning.
  24546. return Object.assign(this.breakpoints_);
  24547. }
  24548. /**
  24549. * Get or set a flag indicating whether or not this player should adjust
  24550. * its UI based on its dimensions.
  24551. *
  24552. * @param {boolean} value
  24553. * Should be `true` if the player should adjust its UI based on its
  24554. * dimensions; otherwise, should be `false`.
  24555. *
  24556. * @return {boolean}
  24557. * Will be `true` if this player should adjust its UI based on its
  24558. * dimensions; otherwise, will be `false`.
  24559. */
  24560. responsive(value) {
  24561. // Used as a getter.
  24562. if (value === undefined) {
  24563. return this.responsive_;
  24564. }
  24565. value = Boolean(value);
  24566. const current = this.responsive_;
  24567. // Nothing changed.
  24568. if (value === current) {
  24569. return;
  24570. }
  24571. // The value actually changed, set it.
  24572. this.responsive_ = value;
  24573. // Start listening for breakpoints and set the initial breakpoint if the
  24574. // player is now responsive.
  24575. if (value) {
  24576. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  24577. this.updateCurrentBreakpoint_();
  24578. // Stop listening for breakpoints if the player is no longer responsive.
  24579. } else {
  24580. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  24581. this.removeCurrentBreakpoint_();
  24582. }
  24583. return value;
  24584. }
  24585. /**
  24586. * Get current breakpoint name, if any.
  24587. *
  24588. * @return {string}
  24589. * If there is currently a breakpoint set, returns a the key from the
  24590. * breakpoints object matching it. Otherwise, returns an empty string.
  24591. */
  24592. currentBreakpoint() {
  24593. return this.breakpoint_;
  24594. }
  24595. /**
  24596. * Get the current breakpoint class name.
  24597. *
  24598. * @return {string}
  24599. * The matching class name (e.g. `"vjs-layout-tiny"` or
  24600. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  24601. * there is no current breakpoint.
  24602. */
  24603. currentBreakpointClass() {
  24604. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  24605. }
  24606. /**
  24607. * An object that describes a single piece of media.
  24608. *
  24609. * Properties that are not part of this type description will be retained; so,
  24610. * this can be viewed as a generic metadata storage mechanism as well.
  24611. *
  24612. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  24613. * @typedef {Object} Player~MediaObject
  24614. *
  24615. * @property {string} [album]
  24616. * Unused, except if this object is passed to the `MediaSession`
  24617. * API.
  24618. *
  24619. * @property {string} [artist]
  24620. * Unused, except if this object is passed to the `MediaSession`
  24621. * API.
  24622. *
  24623. * @property {Object[]} [artwork]
  24624. * Unused, except if this object is passed to the `MediaSession`
  24625. * API. If not specified, will be populated via the `poster`, if
  24626. * available.
  24627. *
  24628. * @property {string} [poster]
  24629. * URL to an image that will display before playback.
  24630. *
  24631. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  24632. * A single source object, an array of source objects, or a string
  24633. * referencing a URL to a media source. It is _highly recommended_
  24634. * that an object or array of objects is used here, so that source
  24635. * selection algorithms can take the `type` into account.
  24636. *
  24637. * @property {string} [title]
  24638. * Unused, except if this object is passed to the `MediaSession`
  24639. * API.
  24640. *
  24641. * @property {Object[]} [textTracks]
  24642. * An array of objects to be used to create text tracks, following
  24643. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  24644. * For ease of removal, these will be created as "remote" text
  24645. * tracks and set to automatically clean up on source changes.
  24646. *
  24647. * These objects may have properties like `src`, `kind`, `label`,
  24648. * and `language`, see {@link Tech#createRemoteTextTrack}.
  24649. */
  24650. /**
  24651. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  24652. *
  24653. * @param {Player~MediaObject} media
  24654. * A media object.
  24655. *
  24656. * @param {Function} ready
  24657. * A callback to be called when the player is ready.
  24658. */
  24659. loadMedia(media, ready) {
  24660. if (!media || typeof media !== 'object') {
  24661. return;
  24662. }
  24663. this.reset();
  24664. // Clone the media object so it cannot be mutated from outside.
  24665. this.cache_.media = merge(media);
  24666. const {
  24667. artist,
  24668. artwork,
  24669. description,
  24670. poster,
  24671. src,
  24672. textTracks,
  24673. title
  24674. } = this.cache_.media;
  24675. // If `artwork` is not given, create it using `poster`.
  24676. if (!artwork && poster) {
  24677. this.cache_.media.artwork = [{
  24678. src: poster,
  24679. type: getMimetype(poster)
  24680. }];
  24681. }
  24682. if (src) {
  24683. this.src(src);
  24684. }
  24685. if (poster) {
  24686. this.poster(poster);
  24687. }
  24688. if (Array.isArray(textTracks)) {
  24689. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  24690. }
  24691. if (this.titleBar) {
  24692. this.titleBar.update({
  24693. title,
  24694. description: description || artist || ''
  24695. });
  24696. }
  24697. this.ready(ready);
  24698. }
  24699. /**
  24700. * Get a clone of the current {@link Player~MediaObject} for this player.
  24701. *
  24702. * If the `loadMedia` method has not been used, will attempt to return a
  24703. * {@link Player~MediaObject} based on the current state of the player.
  24704. *
  24705. * @return {Player~MediaObject}
  24706. */
  24707. getMedia() {
  24708. if (!this.cache_.media) {
  24709. const poster = this.poster();
  24710. const src = this.currentSources();
  24711. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  24712. kind: tt.kind,
  24713. label: tt.label,
  24714. language: tt.language,
  24715. src: tt.src
  24716. }));
  24717. const media = {
  24718. src,
  24719. textTracks
  24720. };
  24721. if (poster) {
  24722. media.poster = poster;
  24723. media.artwork = [{
  24724. src: media.poster,
  24725. type: getMimetype(media.poster)
  24726. }];
  24727. }
  24728. return media;
  24729. }
  24730. return merge(this.cache_.media);
  24731. }
  24732. /**
  24733. * Gets tag settings
  24734. *
  24735. * @param {Element} tag
  24736. * The player tag
  24737. *
  24738. * @return {Object}
  24739. * An object containing all of the settings
  24740. * for a player tag
  24741. */
  24742. static getTagSettings(tag) {
  24743. const baseOptions = {
  24744. sources: [],
  24745. tracks: []
  24746. };
  24747. const tagOptions = getAttributes(tag);
  24748. const dataSetup = tagOptions['data-setup'];
  24749. if (hasClass(tag, 'vjs-fill')) {
  24750. tagOptions.fill = true;
  24751. }
  24752. if (hasClass(tag, 'vjs-fluid')) {
  24753. tagOptions.fluid = true;
  24754. }
  24755. // Check if data-setup attr exists.
  24756. if (dataSetup !== null) {
  24757. // Parse options JSON
  24758. // If empty string, make it a parsable json object.
  24759. const [err, data] = tuple(dataSetup || '{}');
  24760. if (err) {
  24761. log.error(err);
  24762. }
  24763. Object.assign(tagOptions, data);
  24764. }
  24765. Object.assign(baseOptions, tagOptions);
  24766. // Get tag children settings
  24767. if (tag.hasChildNodes()) {
  24768. const children = tag.childNodes;
  24769. for (let i = 0, j = children.length; i < j; i++) {
  24770. const child = children[i];
  24771. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  24772. const childName = child.nodeName.toLowerCase();
  24773. if (childName === 'source') {
  24774. baseOptions.sources.push(getAttributes(child));
  24775. } else if (childName === 'track') {
  24776. baseOptions.tracks.push(getAttributes(child));
  24777. }
  24778. }
  24779. }
  24780. return baseOptions;
  24781. }
  24782. /**
  24783. * Set debug mode to enable/disable logs at info level.
  24784. *
  24785. * @param {boolean} enabled
  24786. * @fires Player#debugon
  24787. * @fires Player#debugoff
  24788. */
  24789. debug(enabled) {
  24790. if (enabled === undefined) {
  24791. return this.debugEnabled_;
  24792. }
  24793. if (enabled) {
  24794. this.trigger('debugon');
  24795. this.previousLogLevel_ = this.log.level;
  24796. this.log.level('debug');
  24797. this.debugEnabled_ = true;
  24798. } else {
  24799. this.trigger('debugoff');
  24800. this.log.level(this.previousLogLevel_);
  24801. this.previousLogLevel_ = undefined;
  24802. this.debugEnabled_ = false;
  24803. }
  24804. }
  24805. /**
  24806. * Set or get current playback rates.
  24807. * Takes an array and updates the playback rates menu with the new items.
  24808. * Pass in an empty array to hide the menu.
  24809. * Values other than arrays are ignored.
  24810. *
  24811. * @fires Player#playbackrateschange
  24812. * @param {number[]} newRates
  24813. * The new rates that the playback rates menu should update to.
  24814. * An empty array will hide the menu
  24815. * @return {number[]} When used as a getter will return the current playback rates
  24816. */
  24817. playbackRates(newRates) {
  24818. if (newRates === undefined) {
  24819. return this.cache_.playbackRates;
  24820. }
  24821. // ignore any value that isn't an array
  24822. if (!Array.isArray(newRates)) {
  24823. return;
  24824. }
  24825. // ignore any arrays that don't only contain numbers
  24826. if (!newRates.every(rate => typeof rate === 'number')) {
  24827. return;
  24828. }
  24829. this.cache_.playbackRates = newRates;
  24830. /**
  24831. * fires when the playback rates in a player are changed
  24832. *
  24833. * @event Player#playbackrateschange
  24834. * @type {Event}
  24835. */
  24836. this.trigger('playbackrateschange');
  24837. }
  24838. }
  24839. /**
  24840. * Get the {@link VideoTrackList}
  24841. *
  24842. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  24843. *
  24844. * @return {VideoTrackList}
  24845. * the current video track list
  24846. *
  24847. * @method Player.prototype.videoTracks
  24848. */
  24849. /**
  24850. * Get the {@link AudioTrackList}
  24851. *
  24852. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  24853. *
  24854. * @return {AudioTrackList}
  24855. * the current audio track list
  24856. *
  24857. * @method Player.prototype.audioTracks
  24858. */
  24859. /**
  24860. * Get the {@link TextTrackList}
  24861. *
  24862. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  24863. *
  24864. * @return {TextTrackList}
  24865. * the current text track list
  24866. *
  24867. * @method Player.prototype.textTracks
  24868. */
  24869. /**
  24870. * Get the remote {@link TextTrackList}
  24871. *
  24872. * @return {TextTrackList}
  24873. * The current remote text track list
  24874. *
  24875. * @method Player.prototype.remoteTextTracks
  24876. */
  24877. /**
  24878. * Get the remote {@link HtmlTrackElementList} tracks.
  24879. *
  24880. * @return {HtmlTrackElementList}
  24881. * The current remote text track element list
  24882. *
  24883. * @method Player.prototype.remoteTextTrackEls
  24884. */
  24885. ALL.names.forEach(function (name) {
  24886. const props = ALL[name];
  24887. Player.prototype[props.getterName] = function () {
  24888. if (this.tech_) {
  24889. return this.tech_[props.getterName]();
  24890. }
  24891. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  24892. // these will be passed to the tech during loading
  24893. this[props.privateName] = this[props.privateName] || new props.ListClass();
  24894. return this[props.privateName];
  24895. };
  24896. });
  24897. /**
  24898. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  24899. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  24900. * behavior.
  24901. *
  24902. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  24903. *
  24904. * @param {string} [value]
  24905. * The value to set the `Player`'s crossorigin to. If an argument is
  24906. * given, must be one of `anonymous` or `use-credentials`.
  24907. *
  24908. * @return {string|undefined}
  24909. * - The current crossorigin value of the `Player` when getting.
  24910. * - undefined when setting
  24911. */
  24912. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  24913. /**
  24914. * Global enumeration of players.
  24915. *
  24916. * The keys are the player IDs and the values are either the {@link Player}
  24917. * instance or `null` for disposed players.
  24918. *
  24919. * @type {Object}
  24920. */
  24921. Player.players = {};
  24922. const navigator = window.navigator;
  24923. /*
  24924. * Player instance options, surfaced using options
  24925. * options = Player.prototype.options_
  24926. * Make changes in options, not here.
  24927. *
  24928. * @type {Object}
  24929. * @private
  24930. */
  24931. Player.prototype.options_ = {
  24932. // Default order of fallback technology
  24933. techOrder: Tech.defaultTechOrder_,
  24934. html5: {},
  24935. // enable sourceset by default
  24936. enableSourceset: true,
  24937. // default inactivity timeout
  24938. inactivityTimeout: 2000,
  24939. // default playback rates
  24940. playbackRates: [],
  24941. // Add playback rate selection by adding rates
  24942. // 'playbackRates': [0.5, 1, 1.5, 2],
  24943. liveui: false,
  24944. // Included control sets
  24945. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  24946. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  24947. // locales and their language translations
  24948. languages: {},
  24949. // Default message to show when a video cannot be played.
  24950. notSupportedMessage: 'No compatible source was found for this media.',
  24951. normalizeAutoplay: false,
  24952. fullscreen: {
  24953. options: {
  24954. navigationUI: 'hide'
  24955. }
  24956. },
  24957. breakpoints: {},
  24958. responsive: false,
  24959. audioOnlyMode: false,
  24960. audioPosterMode: false
  24961. };
  24962. [
  24963. /**
  24964. * Returns whether or not the player is in the "ended" state.
  24965. *
  24966. * @return {Boolean} True if the player is in the ended state, false if not.
  24967. * @method Player#ended
  24968. */
  24969. 'ended',
  24970. /**
  24971. * Returns whether or not the player is in the "seeking" state.
  24972. *
  24973. * @return {Boolean} True if the player is in the seeking state, false if not.
  24974. * @method Player#seeking
  24975. */
  24976. 'seeking',
  24977. /**
  24978. * Returns the TimeRanges of the media that are currently available
  24979. * for seeking to.
  24980. *
  24981. * @return {TimeRanges} the seekable intervals of the media timeline
  24982. * @method Player#seekable
  24983. */
  24984. 'seekable',
  24985. /**
  24986. * Returns the current state of network activity for the element, from
  24987. * the codes in the list below.
  24988. * - NETWORK_EMPTY (numeric value 0)
  24989. * The element has not yet been initialised. All attributes are in
  24990. * their initial states.
  24991. * - NETWORK_IDLE (numeric value 1)
  24992. * The element's resource selection algorithm is active and has
  24993. * selected a resource, but it is not actually using the network at
  24994. * this time.
  24995. * - NETWORK_LOADING (numeric value 2)
  24996. * The user agent is actively trying to download data.
  24997. * - NETWORK_NO_SOURCE (numeric value 3)
  24998. * The element's resource selection algorithm is active, but it has
  24999. * not yet found a resource to use.
  25000. *
  25001. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  25002. * @return {number} the current network activity state
  25003. * @method Player#networkState
  25004. */
  25005. 'networkState',
  25006. /**
  25007. * Returns a value that expresses the current state of the element
  25008. * with respect to rendering the current playback position, from the
  25009. * codes in the list below.
  25010. * - HAVE_NOTHING (numeric value 0)
  25011. * No information regarding the media resource is available.
  25012. * - HAVE_METADATA (numeric value 1)
  25013. * Enough of the resource has been obtained that the duration of the
  25014. * resource is available.
  25015. * - HAVE_CURRENT_DATA (numeric value 2)
  25016. * Data for the immediate current playback position is available.
  25017. * - HAVE_FUTURE_DATA (numeric value 3)
  25018. * Data for the immediate current playback position is available, as
  25019. * well as enough data for the user agent to advance the current
  25020. * playback position in the direction of playback.
  25021. * - HAVE_ENOUGH_DATA (numeric value 4)
  25022. * The user agent estimates that enough data is available for
  25023. * playback to proceed uninterrupted.
  25024. *
  25025. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  25026. * @return {number} the current playback rendering state
  25027. * @method Player#readyState
  25028. */
  25029. 'readyState'].forEach(function (fn) {
  25030. Player.prototype[fn] = function () {
  25031. return this.techGet_(fn);
  25032. };
  25033. });
  25034. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  25035. Player.prototype[`handleTech${toTitleCase(event)}_`] = function () {
  25036. return this.trigger(event);
  25037. };
  25038. });
  25039. /**
  25040. * Fired when the player has initial duration and dimension information
  25041. *
  25042. * @event Player#loadedmetadata
  25043. * @type {Event}
  25044. */
  25045. /**
  25046. * Fired when the player has downloaded data at the current playback position
  25047. *
  25048. * @event Player#loadeddata
  25049. * @type {Event}
  25050. */
  25051. /**
  25052. * Fired when the current playback position has changed *
  25053. * During playback this is fired every 15-250 milliseconds, depending on the
  25054. * playback technology in use.
  25055. *
  25056. * @event Player#timeupdate
  25057. * @type {Event}
  25058. */
  25059. /**
  25060. * Fired when the volume changes
  25061. *
  25062. * @event Player#volumechange
  25063. * @type {Event}
  25064. */
  25065. /**
  25066. * Reports whether or not a player has a plugin available.
  25067. *
  25068. * This does not report whether or not the plugin has ever been initialized
  25069. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  25070. *
  25071. * @method Player#hasPlugin
  25072. * @param {string} name
  25073. * The name of a plugin.
  25074. *
  25075. * @return {boolean}
  25076. * Whether or not this player has the requested plugin available.
  25077. */
  25078. /**
  25079. * Reports whether or not a player is using a plugin by name.
  25080. *
  25081. * For basic plugins, this only reports whether the plugin has _ever_ been
  25082. * initialized on this player.
  25083. *
  25084. * @method Player#usingPlugin
  25085. * @param {string} name
  25086. * The name of a plugin.
  25087. *
  25088. * @return {boolean}
  25089. * Whether or not this player is using the requested plugin.
  25090. */
  25091. Component.registerComponent('Player', Player);
  25092. /**
  25093. * @file plugin.js
  25094. */
  25095. /**
  25096. * The base plugin name.
  25097. *
  25098. * @private
  25099. * @constant
  25100. * @type {string}
  25101. */
  25102. const BASE_PLUGIN_NAME = 'plugin';
  25103. /**
  25104. * The key on which a player's active plugins cache is stored.
  25105. *
  25106. * @private
  25107. * @constant
  25108. * @type {string}
  25109. */
  25110. const PLUGIN_CACHE_KEY = 'activePlugins_';
  25111. /**
  25112. * Stores registered plugins in a private space.
  25113. *
  25114. * @private
  25115. * @type {Object}
  25116. */
  25117. const pluginStorage = {};
  25118. /**
  25119. * Reports whether or not a plugin has been registered.
  25120. *
  25121. * @private
  25122. * @param {string} name
  25123. * The name of a plugin.
  25124. *
  25125. * @return {boolean}
  25126. * Whether or not the plugin has been registered.
  25127. */
  25128. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  25129. /**
  25130. * Get a single registered plugin by name.
  25131. *
  25132. * @private
  25133. * @param {string} name
  25134. * The name of a plugin.
  25135. *
  25136. * @return {typeof Plugin|Function|undefined}
  25137. * The plugin (or undefined).
  25138. */
  25139. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  25140. /**
  25141. * Marks a plugin as "active" on a player.
  25142. *
  25143. * Also, ensures that the player has an object for tracking active plugins.
  25144. *
  25145. * @private
  25146. * @param {Player} player
  25147. * A Video.js player instance.
  25148. *
  25149. * @param {string} name
  25150. * The name of a plugin.
  25151. */
  25152. const markPluginAsActive = (player, name) => {
  25153. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  25154. player[PLUGIN_CACHE_KEY][name] = true;
  25155. };
  25156. /**
  25157. * Triggers a pair of plugin setup events.
  25158. *
  25159. * @private
  25160. * @param {Player} player
  25161. * A Video.js player instance.
  25162. *
  25163. * @param {Plugin~PluginEventHash} hash
  25164. * A plugin event hash.
  25165. *
  25166. * @param {boolean} [before]
  25167. * If true, prefixes the event name with "before". In other words,
  25168. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  25169. */
  25170. const triggerSetupEvent = (player, hash, before) => {
  25171. const eventName = (before ? 'before' : '') + 'pluginsetup';
  25172. player.trigger(eventName, hash);
  25173. player.trigger(eventName + ':' + hash.name, hash);
  25174. };
  25175. /**
  25176. * Takes a basic plugin function and returns a wrapper function which marks
  25177. * on the player that the plugin has been activated.
  25178. *
  25179. * @private
  25180. * @param {string} name
  25181. * The name of the plugin.
  25182. *
  25183. * @param {Function} plugin
  25184. * The basic plugin.
  25185. *
  25186. * @return {Function}
  25187. * A wrapper function for the given plugin.
  25188. */
  25189. const createBasicPlugin = function (name, plugin) {
  25190. const basicPluginWrapper = function () {
  25191. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  25192. // regardless, but we want the hash to be consistent with the hash provided
  25193. // for advanced plugins.
  25194. //
  25195. // The only potentially counter-intuitive thing here is the `instance` in
  25196. // the "pluginsetup" event is the value returned by the `plugin` function.
  25197. triggerSetupEvent(this, {
  25198. name,
  25199. plugin,
  25200. instance: null
  25201. }, true);
  25202. const instance = plugin.apply(this, arguments);
  25203. markPluginAsActive(this, name);
  25204. triggerSetupEvent(this, {
  25205. name,
  25206. plugin,
  25207. instance
  25208. });
  25209. return instance;
  25210. };
  25211. Object.keys(plugin).forEach(function (prop) {
  25212. basicPluginWrapper[prop] = plugin[prop];
  25213. });
  25214. return basicPluginWrapper;
  25215. };
  25216. /**
  25217. * Takes a plugin sub-class and returns a factory function for generating
  25218. * instances of it.
  25219. *
  25220. * This factory function will replace itself with an instance of the requested
  25221. * sub-class of Plugin.
  25222. *
  25223. * @private
  25224. * @param {string} name
  25225. * The name of the plugin.
  25226. *
  25227. * @param {Plugin} PluginSubClass
  25228. * The advanced plugin.
  25229. *
  25230. * @return {Function}
  25231. */
  25232. const createPluginFactory = (name, PluginSubClass) => {
  25233. // Add a `name` property to the plugin prototype so that each plugin can
  25234. // refer to itself by name.
  25235. PluginSubClass.prototype.name = name;
  25236. return function (...args) {
  25237. triggerSetupEvent(this, {
  25238. name,
  25239. plugin: PluginSubClass,
  25240. instance: null
  25241. }, true);
  25242. const instance = new PluginSubClass(...[this, ...args]);
  25243. // The plugin is replaced by a function that returns the current instance.
  25244. this[name] = () => instance;
  25245. triggerSetupEvent(this, instance.getEventHash());
  25246. return instance;
  25247. };
  25248. };
  25249. /**
  25250. * Parent class for all advanced plugins.
  25251. *
  25252. * @mixes module:evented~EventedMixin
  25253. * @mixes module:stateful~StatefulMixin
  25254. * @fires Player#beforepluginsetup
  25255. * @fires Player#beforepluginsetup:$name
  25256. * @fires Player#pluginsetup
  25257. * @fires Player#pluginsetup:$name
  25258. * @listens Player#dispose
  25259. * @throws {Error}
  25260. * If attempting to instantiate the base {@link Plugin} class
  25261. * directly instead of via a sub-class.
  25262. */
  25263. class Plugin {
  25264. /**
  25265. * Creates an instance of this class.
  25266. *
  25267. * Sub-classes should call `super` to ensure plugins are properly initialized.
  25268. *
  25269. * @param {Player} player
  25270. * A Video.js player instance.
  25271. */
  25272. constructor(player) {
  25273. if (this.constructor === Plugin) {
  25274. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  25275. }
  25276. this.player = player;
  25277. if (!this.log) {
  25278. this.log = this.player.log.createLogger(this.name);
  25279. }
  25280. // Make this object evented, but remove the added `trigger` method so we
  25281. // use the prototype version instead.
  25282. evented(this);
  25283. delete this.trigger;
  25284. stateful(this, this.constructor.defaultState);
  25285. markPluginAsActive(player, this.name);
  25286. // Auto-bind the dispose method so we can use it as a listener and unbind
  25287. // it later easily.
  25288. this.dispose = this.dispose.bind(this);
  25289. // If the player is disposed, dispose the plugin.
  25290. player.on('dispose', this.dispose);
  25291. }
  25292. /**
  25293. * Get the version of the plugin that was set on <pluginName>.VERSION
  25294. */
  25295. version() {
  25296. return this.constructor.VERSION;
  25297. }
  25298. /**
  25299. * Each event triggered by plugins includes a hash of additional data with
  25300. * conventional properties.
  25301. *
  25302. * This returns that object or mutates an existing hash.
  25303. *
  25304. * @param {Object} [hash={}]
  25305. * An object to be used as event an event hash.
  25306. *
  25307. * @return {Plugin~PluginEventHash}
  25308. * An event hash object with provided properties mixed-in.
  25309. */
  25310. getEventHash(hash = {}) {
  25311. hash.name = this.name;
  25312. hash.plugin = this.constructor;
  25313. hash.instance = this;
  25314. return hash;
  25315. }
  25316. /**
  25317. * Triggers an event on the plugin object and overrides
  25318. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  25319. *
  25320. * @param {string|Object} event
  25321. * An event type or an object with a type property.
  25322. *
  25323. * @param {Object} [hash={}]
  25324. * Additional data hash to merge with a
  25325. * {@link Plugin~PluginEventHash|PluginEventHash}.
  25326. *
  25327. * @return {boolean}
  25328. * Whether or not default was prevented.
  25329. */
  25330. trigger(event, hash = {}) {
  25331. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  25332. }
  25333. /**
  25334. * Handles "statechanged" events on the plugin. No-op by default, override by
  25335. * subclassing.
  25336. *
  25337. * @abstract
  25338. * @param {Event} e
  25339. * An event object provided by a "statechanged" event.
  25340. *
  25341. * @param {Object} e.changes
  25342. * An object describing changes that occurred with the "statechanged"
  25343. * event.
  25344. */
  25345. handleStateChanged(e) {}
  25346. /**
  25347. * Disposes a plugin.
  25348. *
  25349. * Subclasses can override this if they want, but for the sake of safety,
  25350. * it's probably best to subscribe the "dispose" event.
  25351. *
  25352. * @fires Plugin#dispose
  25353. */
  25354. dispose() {
  25355. const {
  25356. name,
  25357. player
  25358. } = this;
  25359. /**
  25360. * Signals that a advanced plugin is about to be disposed.
  25361. *
  25362. * @event Plugin#dispose
  25363. * @type {Event}
  25364. */
  25365. this.trigger('dispose');
  25366. this.off();
  25367. player.off('dispose', this.dispose);
  25368. // Eliminate any possible sources of leaking memory by clearing up
  25369. // references between the player and the plugin instance and nulling out
  25370. // the plugin's state and replacing methods with a function that throws.
  25371. player[PLUGIN_CACHE_KEY][name] = false;
  25372. this.player = this.state = null;
  25373. // Finally, replace the plugin name on the player with a new factory
  25374. // function, so that the plugin is ready to be set up again.
  25375. player[name] = createPluginFactory(name, pluginStorage[name]);
  25376. }
  25377. /**
  25378. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  25379. *
  25380. * @param {string|Function} plugin
  25381. * If a string, matches the name of a plugin. If a function, will be
  25382. * tested directly.
  25383. *
  25384. * @return {boolean}
  25385. * Whether or not a plugin is a basic plugin.
  25386. */
  25387. static isBasic(plugin) {
  25388. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  25389. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  25390. }
  25391. /**
  25392. * Register a Video.js plugin.
  25393. *
  25394. * @param {string} name
  25395. * The name of the plugin to be registered. Must be a string and
  25396. * must not match an existing plugin or a method on the `Player`
  25397. * prototype.
  25398. *
  25399. * @param {typeof Plugin|Function} plugin
  25400. * A sub-class of `Plugin` or a function for basic plugins.
  25401. *
  25402. * @return {typeof Plugin|Function}
  25403. * For advanced plugins, a factory function for that plugin. For
  25404. * basic plugins, a wrapper function that initializes the plugin.
  25405. */
  25406. static registerPlugin(name, plugin) {
  25407. if (typeof name !== 'string') {
  25408. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  25409. }
  25410. if (pluginExists(name)) {
  25411. log.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  25412. } else if (Player.prototype.hasOwnProperty(name)) {
  25413. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  25414. }
  25415. if (typeof plugin !== 'function') {
  25416. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  25417. }
  25418. pluginStorage[name] = plugin;
  25419. // Add a player prototype method for all sub-classed plugins (but not for
  25420. // the base Plugin class).
  25421. if (name !== BASE_PLUGIN_NAME) {
  25422. if (Plugin.isBasic(plugin)) {
  25423. Player.prototype[name] = createBasicPlugin(name, plugin);
  25424. } else {
  25425. Player.prototype[name] = createPluginFactory(name, plugin);
  25426. }
  25427. }
  25428. return plugin;
  25429. }
  25430. /**
  25431. * De-register a Video.js plugin.
  25432. *
  25433. * @param {string} name
  25434. * The name of the plugin to be de-registered. Must be a string that
  25435. * matches an existing plugin.
  25436. *
  25437. * @throws {Error}
  25438. * If an attempt is made to de-register the base plugin.
  25439. */
  25440. static deregisterPlugin(name) {
  25441. if (name === BASE_PLUGIN_NAME) {
  25442. throw new Error('Cannot de-register base plugin.');
  25443. }
  25444. if (pluginExists(name)) {
  25445. delete pluginStorage[name];
  25446. delete Player.prototype[name];
  25447. }
  25448. }
  25449. /**
  25450. * Gets an object containing multiple Video.js plugins.
  25451. *
  25452. * @param {Array} [names]
  25453. * If provided, should be an array of plugin names. Defaults to _all_
  25454. * plugin names.
  25455. *
  25456. * @return {Object|undefined}
  25457. * An object containing plugin(s) associated with their name(s) or
  25458. * `undefined` if no matching plugins exist).
  25459. */
  25460. static getPlugins(names = Object.keys(pluginStorage)) {
  25461. let result;
  25462. names.forEach(name => {
  25463. const plugin = getPlugin(name);
  25464. if (plugin) {
  25465. result = result || {};
  25466. result[name] = plugin;
  25467. }
  25468. });
  25469. return result;
  25470. }
  25471. /**
  25472. * Gets a plugin's version, if available
  25473. *
  25474. * @param {string} name
  25475. * The name of a plugin.
  25476. *
  25477. * @return {string}
  25478. * The plugin's version or an empty string.
  25479. */
  25480. static getPluginVersion(name) {
  25481. const plugin = getPlugin(name);
  25482. return plugin && plugin.VERSION || '';
  25483. }
  25484. }
  25485. /**
  25486. * Gets a plugin by name if it exists.
  25487. *
  25488. * @static
  25489. * @method getPlugin
  25490. * @memberOf Plugin
  25491. * @param {string} name
  25492. * The name of a plugin.
  25493. *
  25494. * @returns {typeof Plugin|Function|undefined}
  25495. * The plugin (or `undefined`).
  25496. */
  25497. Plugin.getPlugin = getPlugin;
  25498. /**
  25499. * The name of the base plugin class as it is registered.
  25500. *
  25501. * @type {string}
  25502. */
  25503. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  25504. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  25505. /**
  25506. * Documented in player.js
  25507. *
  25508. * @ignore
  25509. */
  25510. Player.prototype.usingPlugin = function (name) {
  25511. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  25512. };
  25513. /**
  25514. * Documented in player.js
  25515. *
  25516. * @ignore
  25517. */
  25518. Player.prototype.hasPlugin = function (name) {
  25519. return !!pluginExists(name);
  25520. };
  25521. /**
  25522. * Signals that a plugin is about to be set up on a player.
  25523. *
  25524. * @event Player#beforepluginsetup
  25525. * @type {Plugin~PluginEventHash}
  25526. */
  25527. /**
  25528. * Signals that a plugin is about to be set up on a player - by name. The name
  25529. * is the name of the plugin.
  25530. *
  25531. * @event Player#beforepluginsetup:$name
  25532. * @type {Plugin~PluginEventHash}
  25533. */
  25534. /**
  25535. * Signals that a plugin has just been set up on a player.
  25536. *
  25537. * @event Player#pluginsetup
  25538. * @type {Plugin~PluginEventHash}
  25539. */
  25540. /**
  25541. * Signals that a plugin has just been set up on a player - by name. The name
  25542. * is the name of the plugin.
  25543. *
  25544. * @event Player#pluginsetup:$name
  25545. * @type {Plugin~PluginEventHash}
  25546. */
  25547. /**
  25548. * @typedef {Object} Plugin~PluginEventHash
  25549. *
  25550. * @property {string} instance
  25551. * For basic plugins, the return value of the plugin function. For
  25552. * advanced plugins, the plugin instance on which the event is fired.
  25553. *
  25554. * @property {string} name
  25555. * The name of the plugin.
  25556. *
  25557. * @property {string} plugin
  25558. * For basic plugins, the plugin function. For advanced plugins, the
  25559. * plugin class/constructor.
  25560. */
  25561. /**
  25562. * @file deprecate.js
  25563. * @module deprecate
  25564. */
  25565. /**
  25566. * Decorate a function with a deprecation message the first time it is called.
  25567. *
  25568. * @param {string} message
  25569. * A deprecation message to log the first time the returned function
  25570. * is called.
  25571. *
  25572. * @param {Function} fn
  25573. * The function to be deprecated.
  25574. *
  25575. * @return {Function}
  25576. * A wrapper function that will log a deprecation warning the first
  25577. * time it is called. The return value will be the return value of
  25578. * the wrapped function.
  25579. */
  25580. function deprecate(message, fn) {
  25581. let warned = false;
  25582. return function (...args) {
  25583. if (!warned) {
  25584. log.warn(message);
  25585. }
  25586. warned = true;
  25587. return fn.apply(this, args);
  25588. };
  25589. }
  25590. /**
  25591. * Internal function used to mark a function as deprecated in the next major
  25592. * version with consistent messaging.
  25593. *
  25594. * @param {number} major The major version where it will be removed
  25595. * @param {string} oldName The old function name
  25596. * @param {string} newName The new function name
  25597. * @param {Function} fn The function to deprecate
  25598. * @return {Function} The decorated function
  25599. */
  25600. function deprecateForMajor(major, oldName, newName, fn) {
  25601. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  25602. }
  25603. /**
  25604. * @file video.js
  25605. * @module videojs
  25606. */
  25607. /**
  25608. * Normalize an `id` value by trimming off a leading `#`
  25609. *
  25610. * @private
  25611. * @param {string} id
  25612. * A string, maybe with a leading `#`.
  25613. *
  25614. * @return {string}
  25615. * The string, without any leading `#`.
  25616. */
  25617. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  25618. /**
  25619. * A callback that is called when a component is ready. Does not have any
  25620. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  25621. *
  25622. * @callback ReadyCallback
  25623. */
  25624. /**
  25625. * The `videojs()` function doubles as the main function for users to create a
  25626. * {@link Player} instance as well as the main library namespace.
  25627. *
  25628. * It can also be used as a getter for a pre-existing {@link Player} instance.
  25629. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  25630. * purpose because it avoids any potential for unintended initialization.
  25631. *
  25632. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  25633. * of our JSDoc template, we cannot properly document this as both a function
  25634. * and a namespace, so its function signature is documented here.
  25635. *
  25636. * #### Arguments
  25637. * ##### id
  25638. * string|Element, **required**
  25639. *
  25640. * Video element or video element ID.
  25641. *
  25642. * ##### options
  25643. * Object, optional
  25644. *
  25645. * Options object for providing settings.
  25646. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  25647. *
  25648. * ##### ready
  25649. * {@link Component~ReadyCallback}, optional
  25650. *
  25651. * A function to be called when the {@link Player} and {@link Tech} are ready.
  25652. *
  25653. * #### Return Value
  25654. *
  25655. * The `videojs()` function returns a {@link Player} instance.
  25656. *
  25657. * @namespace
  25658. *
  25659. * @borrows AudioTrack as AudioTrack
  25660. * @borrows Component.getComponent as getComponent
  25661. * @borrows module:events.on as on
  25662. * @borrows module:events.one as one
  25663. * @borrows module:events.off as off
  25664. * @borrows module:events.trigger as trigger
  25665. * @borrows EventTarget as EventTarget
  25666. * @borrows module:middleware.use as use
  25667. * @borrows Player.players as players
  25668. * @borrows Plugin.registerPlugin as registerPlugin
  25669. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  25670. * @borrows Plugin.getPlugins as getPlugins
  25671. * @borrows Plugin.getPlugin as getPlugin
  25672. * @borrows Plugin.getPluginVersion as getPluginVersion
  25673. * @borrows Tech.getTech as getTech
  25674. * @borrows Tech.registerTech as registerTech
  25675. * @borrows TextTrack as TextTrack
  25676. * @borrows VideoTrack as VideoTrack
  25677. *
  25678. * @param {string|Element} id
  25679. * Video element or video element ID.
  25680. *
  25681. * @param {Object} [options]
  25682. * Options object for providing settings.
  25683. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  25684. *
  25685. * @param {ReadyCallback} [ready]
  25686. * A function to be called when the {@link Player} and {@link Tech} are
  25687. * ready.
  25688. *
  25689. * @return {Player}
  25690. * The `videojs()` function returns a {@link Player|Player} instance.
  25691. */
  25692. function videojs(id, options, ready) {
  25693. let player = videojs.getPlayer(id);
  25694. if (player) {
  25695. if (options) {
  25696. log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  25697. }
  25698. if (ready) {
  25699. player.ready(ready);
  25700. }
  25701. return player;
  25702. }
  25703. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  25704. if (!isEl(el)) {
  25705. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  25706. }
  25707. // document.body.contains(el) will only check if el is contained within that one document.
  25708. // This causes problems for elements in iframes.
  25709. // Instead, use the element's ownerDocument instead of the global document.
  25710. // This will make sure that the element is indeed in the dom of that document.
  25711. // Additionally, check that the document in question has a default view.
  25712. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  25713. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  25714. log.warn('The element supplied is not included in the DOM');
  25715. }
  25716. options = options || {};
  25717. // Store a copy of the el before modification, if it is to be restored in destroy()
  25718. // If div ingest, store the parent div
  25719. if (options.restoreEl === true) {
  25720. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  25721. }
  25722. hooks('beforesetup').forEach(hookFunction => {
  25723. const opts = hookFunction(el, merge(options));
  25724. if (!isObject(opts) || Array.isArray(opts)) {
  25725. log.error('please return an object in beforesetup hooks');
  25726. return;
  25727. }
  25728. options = merge(options, opts);
  25729. });
  25730. // We get the current "Player" component here in case an integration has
  25731. // replaced it with a custom player.
  25732. const PlayerComponent = Component.getComponent('Player');
  25733. player = new PlayerComponent(el, options, ready);
  25734. hooks('setup').forEach(hookFunction => hookFunction(player));
  25735. return player;
  25736. }
  25737. videojs.hooks_ = hooks_;
  25738. videojs.hooks = hooks;
  25739. videojs.hook = hook;
  25740. videojs.hookOnce = hookOnce;
  25741. videojs.removeHook = removeHook;
  25742. // Add default styles
  25743. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  25744. let style = $('.vjs-styles-defaults');
  25745. if (!style) {
  25746. style = createStyleElement('vjs-styles-defaults');
  25747. const head = $('head');
  25748. if (head) {
  25749. head.insertBefore(style, head.firstChild);
  25750. }
  25751. setTextContent(style, `
  25752. .video-js {
  25753. width: 300px;
  25754. height: 150px;
  25755. }
  25756. .vjs-fluid:not(.vjs-audio-only-mode) {
  25757. padding-top: 56.25%
  25758. }
  25759. `);
  25760. }
  25761. }
  25762. // Run Auto-load players
  25763. // You have to wait at least once in case this script is loaded after your
  25764. // video in the DOM (weird behavior only with minified version)
  25765. autoSetupTimeout(1, videojs);
  25766. /**
  25767. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  25768. *
  25769. * @type {string}
  25770. */
  25771. videojs.VERSION = version;
  25772. /**
  25773. * The global options object. These are the settings that take effect
  25774. * if no overrides are specified when the player is created.
  25775. *
  25776. * @type {Object}
  25777. */
  25778. videojs.options = Player.prototype.options_;
  25779. /**
  25780. * Get an object with the currently created players, keyed by player ID
  25781. *
  25782. * @return {Object}
  25783. * The created players
  25784. */
  25785. videojs.getPlayers = () => Player.players;
  25786. /**
  25787. * Get a single player based on an ID or DOM element.
  25788. *
  25789. * This is useful if you want to check if an element or ID has an associated
  25790. * Video.js player, but not create one if it doesn't.
  25791. *
  25792. * @param {string|Element} id
  25793. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  25794. * or a string matching the `id` of such an element.
  25795. *
  25796. * @return {Player|undefined}
  25797. * A player instance or `undefined` if there is no player instance
  25798. * matching the argument.
  25799. */
  25800. videojs.getPlayer = id => {
  25801. const players = Player.players;
  25802. let tag;
  25803. if (typeof id === 'string') {
  25804. const nId = normalizeId(id);
  25805. const player = players[nId];
  25806. if (player) {
  25807. return player;
  25808. }
  25809. tag = $('#' + nId);
  25810. } else {
  25811. tag = id;
  25812. }
  25813. if (isEl(tag)) {
  25814. const {
  25815. player,
  25816. playerId
  25817. } = tag;
  25818. // Element may have a `player` property referring to an already created
  25819. // player instance. If so, return that.
  25820. if (player || players[playerId]) {
  25821. return player || players[playerId];
  25822. }
  25823. }
  25824. };
  25825. /**
  25826. * Returns an array of all current players.
  25827. *
  25828. * @return {Array}
  25829. * An array of all players. The array will be in the order that
  25830. * `Object.keys` provides, which could potentially vary between
  25831. * JavaScript engines.
  25832. *
  25833. */
  25834. videojs.getAllPlayers = () =>
  25835. // Disposed players leave a key with a `null` value, so we need to make sure
  25836. // we filter those out.
  25837. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  25838. videojs.players = Player.players;
  25839. videojs.getComponent = Component.getComponent;
  25840. /**
  25841. * Register a component so it can referred to by name. Used when adding to other
  25842. * components, either through addChild `component.addChild('myComponent')` or through
  25843. * default children options `{ children: ['myComponent'] }`.
  25844. *
  25845. * > NOTE: You could also just initialize the component before adding.
  25846. * `component.addChild(new MyComponent());`
  25847. *
  25848. * @param {string} name
  25849. * The class name of the component
  25850. *
  25851. * @param {Component} comp
  25852. * The component class
  25853. *
  25854. * @return {Component}
  25855. * The newly registered component
  25856. */
  25857. videojs.registerComponent = (name, comp) => {
  25858. if (Tech.isTech(comp)) {
  25859. log.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  25860. }
  25861. Component.registerComponent.call(Component, name, comp);
  25862. };
  25863. videojs.getTech = Tech.getTech;
  25864. videojs.registerTech = Tech.registerTech;
  25865. videojs.use = use;
  25866. /**
  25867. * An object that can be returned by a middleware to signify
  25868. * that the middleware is being terminated.
  25869. *
  25870. * @type {object}
  25871. * @property {object} middleware.TERMINATOR
  25872. */
  25873. Object.defineProperty(videojs, 'middleware', {
  25874. value: {},
  25875. writeable: false,
  25876. enumerable: true
  25877. });
  25878. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  25879. value: TERMINATOR,
  25880. writeable: false,
  25881. enumerable: true
  25882. });
  25883. /**
  25884. * A reference to the {@link module:browser|browser utility module} as an object.
  25885. *
  25886. * @type {Object}
  25887. * @see {@link module:browser|browser}
  25888. */
  25889. videojs.browser = browser;
  25890. /**
  25891. * A reference to the {@link module:obj|obj utility module} as an object.
  25892. *
  25893. * @type {Object}
  25894. * @see {@link module:obj|obj}
  25895. */
  25896. videojs.obj = Obj;
  25897. /**
  25898. * Deprecated reference to the {@link module:obj.merge|merge function}
  25899. *
  25900. * @type {Function}
  25901. * @see {@link module:obj.merge|merge}
  25902. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  25903. */
  25904. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge);
  25905. /**
  25906. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  25907. *
  25908. * @type {Function}
  25909. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  25910. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  25911. */
  25912. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  25913. /**
  25914. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  25915. *
  25916. * @type {Function}
  25917. * @see {@link module:fn.bind_|fn.bind_}
  25918. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  25919. */
  25920. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  25921. videojs.registerPlugin = Plugin.registerPlugin;
  25922. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  25923. /**
  25924. * Deprecated method to register a plugin with Video.js
  25925. *
  25926. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  25927. *
  25928. * @param {string} name
  25929. * The plugin name
  25930. *
  25931. * @param {Plugin|Function} plugin
  25932. * The plugin sub-class or function
  25933. */
  25934. videojs.plugin = (name, plugin) => {
  25935. log.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  25936. return Plugin.registerPlugin(name, plugin);
  25937. };
  25938. videojs.getPlugins = Plugin.getPlugins;
  25939. videojs.getPlugin = Plugin.getPlugin;
  25940. videojs.getPluginVersion = Plugin.getPluginVersion;
  25941. /**
  25942. * Adding languages so that they're available to all players.
  25943. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  25944. *
  25945. * @param {string} code
  25946. * The language code or dictionary property
  25947. *
  25948. * @param {Object} data
  25949. * The data values to be translated
  25950. *
  25951. * @return {Object}
  25952. * The resulting language dictionary object
  25953. */
  25954. videojs.addLanguage = function (code, data) {
  25955. code = ('' + code).toLowerCase();
  25956. videojs.options.languages = merge(videojs.options.languages, {
  25957. [code]: data
  25958. });
  25959. return videojs.options.languages[code];
  25960. };
  25961. /**
  25962. * A reference to the {@link module:log|log utility module} as an object.
  25963. *
  25964. * @type {Function}
  25965. * @see {@link module:log|log}
  25966. */
  25967. videojs.log = log;
  25968. videojs.createLogger = createLogger;
  25969. /**
  25970. * A reference to the {@link module:time|time utility module} as an object.
  25971. *
  25972. * @type {Object}
  25973. * @see {@link module:time|time}
  25974. */
  25975. videojs.time = Time;
  25976. /**
  25977. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  25978. *
  25979. * @type {Function}
  25980. * @see {@link module:time.createTimeRanges|createTimeRanges}
  25981. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  25982. */
  25983. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges);
  25984. /**
  25985. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  25986. *
  25987. * @type {Function}
  25988. * @see {@link module:time.createTimeRanges|createTimeRanges}
  25989. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  25990. */
  25991. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges);
  25992. /**
  25993. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  25994. *
  25995. * @type {Function}
  25996. * @see {@link module:time.formatTime|formatTime}
  25997. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  25998. */
  25999. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  26000. /**
  26001. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  26002. *
  26003. * @type {Function}
  26004. * @see {@link module:time.setFormatTime|setFormatTime}
  26005. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  26006. */
  26007. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  26008. /**
  26009. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  26010. *
  26011. * @type {Function}
  26012. * @see {@link module:time.resetFormatTime|resetFormatTime}
  26013. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  26014. */
  26015. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  26016. /**
  26017. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  26018. *
  26019. * @type {Function}
  26020. * @see {@link module:url.parseUrl|parseUrl}
  26021. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  26022. */
  26023. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  26024. /**
  26025. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  26026. *
  26027. * @type {Function}
  26028. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  26029. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  26030. */
  26031. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  26032. videojs.EventTarget = EventTarget;
  26033. videojs.any = any;
  26034. videojs.on = on;
  26035. videojs.one = one;
  26036. videojs.off = off;
  26037. videojs.trigger = trigger;
  26038. /**
  26039. * A cross-browser XMLHttpRequest wrapper.
  26040. *
  26041. * @function
  26042. * @param {Object} options
  26043. * Settings for the request.
  26044. *
  26045. * @return {XMLHttpRequest|XDomainRequest}
  26046. * The request object.
  26047. *
  26048. * @see https://github.com/Raynos/xhr
  26049. */
  26050. videojs.xhr = lib;
  26051. videojs.TextTrack = TextTrack;
  26052. videojs.AudioTrack = AudioTrack;
  26053. videojs.VideoTrack = VideoTrack;
  26054. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  26055. videojs[k] = function () {
  26056. log.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  26057. return Dom[k].apply(null, arguments);
  26058. };
  26059. });
  26060. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  26061. /**
  26062. * A reference to the {@link module:dom|DOM utility module} as an object.
  26063. *
  26064. * @type {Object}
  26065. * @see {@link module:dom|dom}
  26066. */
  26067. videojs.dom = Dom;
  26068. /**
  26069. * A reference to the {@link module:fn|fn utility module} as an object.
  26070. *
  26071. * @type {Object}
  26072. * @see {@link module:fn|fn}
  26073. */
  26074. videojs.fn = Fn;
  26075. /**
  26076. * A reference to the {@link module:num|num utility module} as an object.
  26077. *
  26078. * @type {Object}
  26079. * @see {@link module:num|num}
  26080. */
  26081. videojs.num = Num;
  26082. /**
  26083. * A reference to the {@link module:str|str utility module} as an object.
  26084. *
  26085. * @type {Object}
  26086. * @see {@link module:str|str}
  26087. */
  26088. videojs.str = Str;
  26089. /**
  26090. * A reference to the {@link module:url|URL utility module} as an object.
  26091. *
  26092. * @type {Object}
  26093. * @see {@link module:url|url}
  26094. */
  26095. videojs.url = Url;
  26096. return videojs;
  26097. }));