video.dev.js 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107
  1. /**
  2. * @fileoverview Main function src.
  3. */
  4. // HTML5 Shiv. Must be in <head> to support older browsers.
  5. document.createElement('video');
  6. document.createElement('audio');
  7. document.createElement('track');
  8. /**
  9. * Doubles as the main function for users to create a player instance and also
  10. * the main library object.
  11. *
  12. * **ALIASES** videojs, _V_ (deprecated)
  13. *
  14. * The `vjs` function can be used to initialize or retrieve a player.
  15. *
  16. * var myPlayer = vjs('my_video_id');
  17. *
  18. * @param {String|Element} id Video element or video element ID
  19. * @param {Object=} options Optional options object for config/settings
  20. * @param {Function=} ready Optional ready callback
  21. * @return {vjs.Player} A player instance
  22. * @namespace
  23. */
  24. var vjs = function(id, options, ready){
  25. var tag; // Element of ID
  26. // Allow for element or ID to be passed in
  27. // String ID
  28. if (typeof id === 'string') {
  29. // Adjust for jQuery ID syntax
  30. if (id.indexOf('#') === 0) {
  31. id = id.slice(1);
  32. }
  33. // If a player instance has already been created for this ID return it.
  34. if (vjs.players[id]) {
  35. return vjs.players[id];
  36. // Otherwise get element for ID
  37. } else {
  38. tag = vjs.el(id);
  39. }
  40. // ID is a media element
  41. } else {
  42. tag = id;
  43. }
  44. // Check for a useable element
  45. if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also
  46. throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns
  47. }
  48. // Element may have a player attr referring to an already created player instance.
  49. // If not, set up a new player and return the instance.
  50. return tag['player'] || new vjs.Player(tag, options, ready);
  51. };
  52. // Extended name, also available externally, window.videojs
  53. var videojs = vjs;
  54. window.videojs = window.vjs = vjs;
  55. // CDN Version. Used to target right flash swf.
  56. vjs.CDN_VERSION = '4.3';
  57. vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://');
  58. /**
  59. * Global Player instance options, surfaced from vjs.Player.prototype.options_
  60. * vjs.options = vjs.Player.prototype.options_
  61. * All options should use string keys so they avoid
  62. * renaming by closure compiler
  63. * @type {Object}
  64. */
  65. vjs.options = {
  66. // Default order of fallback technology
  67. 'techOrder': ['html5','flash'],
  68. // techOrder: ['flash','html5'],
  69. 'html5': {},
  70. 'flash': {},
  71. // Default of web browser is 300x150. Should rely on source width/height.
  72. 'width': 300,
  73. 'height': 150,
  74. // defaultVolume: 0.85,
  75. 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy!
  76. // Included control sets
  77. 'children': {
  78. 'mediaLoader': {},
  79. 'posterImage': {},
  80. 'textTrackDisplay': {},
  81. 'loadingSpinner': {},
  82. 'bigPlayButton': {},
  83. 'controlBar': {}
  84. },
  85. // Default message to show when a video cannot be played.
  86. 'notSupportedMessage': 'Sorry, no compatible source and playback ' +
  87. 'technology were found for this video. Try using another browser ' +
  88. 'like <a href="http://bit.ly/ccMUEC">Chrome</a> or download the ' +
  89. 'latest <a href="http://adobe.ly/mwfN1">Adobe Flash Player</a>.'
  90. };
  91. // Set CDN Version of swf
  92. // The added (+) blocks the replace from changing this 4.3 string
  93. if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') {
  94. videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf';
  95. }
  96. /**
  97. * Global player list
  98. * @type {Object}
  99. */
  100. vjs.players = {};
  101. /**
  102. * Core Object/Class for objects that use inheritance + contstructors
  103. *
  104. * To create a class that can be subclassed itself, extend the CoreObject class.
  105. *
  106. * var Animal = CoreObject.extend();
  107. * var Horse = Animal.extend();
  108. *
  109. * The constructor can be defined through the init property of an object argument.
  110. *
  111. * var Animal = CoreObject.extend({
  112. * init: function(name, sound){
  113. * this.name = name;
  114. * }
  115. * });
  116. *
  117. * Other methods and properties can be added the same way, or directly to the
  118. * prototype.
  119. *
  120. * var Animal = CoreObject.extend({
  121. * init: function(name){
  122. * this.name = name;
  123. * },
  124. * getName: function(){
  125. * return this.name;
  126. * },
  127. * sound: '...'
  128. * });
  129. *
  130. * Animal.prototype.makeSound = function(){
  131. * alert(this.sound);
  132. * };
  133. *
  134. * To create an instance of a class, use the create method.
  135. *
  136. * var fluffy = Animal.create('Fluffy');
  137. * fluffy.getName(); // -> Fluffy
  138. *
  139. * Methods and properties can be overridden in subclasses.
  140. *
  141. * var Horse = Animal.extend({
  142. * sound: 'Neighhhhh!'
  143. * });
  144. *
  145. * var horsey = Horse.create('Horsey');
  146. * horsey.getName(); // -> Horsey
  147. * horsey.makeSound(); // -> Alert: Neighhhhh!
  148. *
  149. * @class
  150. * @constructor
  151. */
  152. vjs.CoreObject = vjs['CoreObject'] = function(){};
  153. // Manually exporting vjs['CoreObject'] here for Closure Compiler
  154. // because of the use of the extend/create class methods
  155. // If we didn't do this, those functions would get flattend to something like
  156. // `a = ...` and `this.prototype` would refer to the global object instead of
  157. // CoreObject
  158. /**
  159. * Create a new object that inherits from this Object
  160. *
  161. * var Animal = CoreObject.extend();
  162. * var Horse = Animal.extend();
  163. *
  164. * @param {Object} props Functions and properties to be applied to the
  165. * new object's prototype
  166. * @return {vjs.CoreObject} An object that inherits from CoreObject
  167. * @this {*}
  168. */
  169. vjs.CoreObject.extend = function(props){
  170. var init, subObj;
  171. props = props || {};
  172. // Set up the constructor using the supplied init method
  173. // or using the init of the parent object
  174. // Make sure to check the unobfuscated version for external libs
  175. init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){};
  176. // In Resig's simple class inheritance (previously used) the constructor
  177. // is a function that calls `this.init.apply(arguments)`
  178. // However that would prevent us from using `ParentObject.call(this);`
  179. // in a Child constuctor because the `this` in `this.init`
  180. // would still refer to the Child and cause an inifinite loop.
  181. // We would instead have to do
  182. // `ParentObject.prototype.init.apply(this, argumnents);`
  183. // Bleh. We're not creating a _super() function, so it's good to keep
  184. // the parent constructor reference simple.
  185. subObj = function(){
  186. init.apply(this, arguments);
  187. };
  188. // Inherit from this object's prototype
  189. subObj.prototype = vjs.obj.create(this.prototype);
  190. // Reset the constructor property for subObj otherwise
  191. // instances of subObj would have the constructor of the parent Object
  192. subObj.prototype.constructor = subObj;
  193. // Make the class extendable
  194. subObj.extend = vjs.CoreObject.extend;
  195. // Make a function for creating instances
  196. subObj.create = vjs.CoreObject.create;
  197. // Extend subObj's prototype with functions and other properties from props
  198. for (var name in props) {
  199. if (props.hasOwnProperty(name)) {
  200. subObj.prototype[name] = props[name];
  201. }
  202. }
  203. return subObj;
  204. };
  205. /**
  206. * Create a new instace of this Object class
  207. *
  208. * var myAnimal = Animal.create();
  209. *
  210. * @return {vjs.CoreObject} An instance of a CoreObject subclass
  211. * @this {*}
  212. */
  213. vjs.CoreObject.create = function(){
  214. // Create a new object that inherits from this object's prototype
  215. var inst = vjs.obj.create(this.prototype);
  216. // Apply this constructor function to the new object
  217. this.apply(inst, arguments);
  218. // Return the new object
  219. return inst;
  220. };
  221. /**
  222. * @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  223. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  224. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  225. * robust as jquery's, so there's probably some differences.
  226. */
  227. /**
  228. * Add an event listener to element
  229. * It stores the handler function in a separate cache object
  230. * and adds a generic handler to the element's event,
  231. * along with a unique id (guid) to the element.
  232. * @param {Element|Object} elem Element or object to bind listeners to
  233. * @param {String} type Type of event to bind to.
  234. * @param {Function} fn Event listener.
  235. * @private
  236. */
  237. vjs.on = function(elem, type, fn){
  238. var data = vjs.getData(elem);
  239. // We need a place to store all our handler data
  240. if (!data.handlers) data.handlers = {};
  241. if (!data.handlers[type]) data.handlers[type] = [];
  242. if (!fn.guid) fn.guid = vjs.guid++;
  243. data.handlers[type].push(fn);
  244. if (!data.dispatcher) {
  245. data.disabled = false;
  246. data.dispatcher = function (event){
  247. if (data.disabled) return;
  248. event = vjs.fixEvent(event);
  249. var handlers = data.handlers[event.type];
  250. if (handlers) {
  251. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  252. var handlersCopy = handlers.slice(0);
  253. for (var m = 0, n = handlersCopy.length; m < n; m++) {
  254. if (event.isImmediatePropagationStopped()) {
  255. break;
  256. } else {
  257. handlersCopy[m].call(elem, event);
  258. }
  259. }
  260. }
  261. };
  262. }
  263. if (data.handlers[type].length == 1) {
  264. if (document.addEventListener) {
  265. elem.addEventListener(type, data.dispatcher, false);
  266. } else if (document.attachEvent) {
  267. elem.attachEvent('on' + type, data.dispatcher);
  268. }
  269. }
  270. };
  271. /**
  272. * Removes event listeners from an element
  273. * @param {Element|Object} elem Object to remove listeners from
  274. * @param {String=} type Type of listener to remove. Don't include to remove all events from element.
  275. * @param {Function} fn Specific listener to remove. Don't incldue to remove listeners for an event type.
  276. * @private
  277. */
  278. vjs.off = function(elem, type, fn) {
  279. // Don't want to add a cache object through getData if not needed
  280. if (!vjs.hasData(elem)) return;
  281. var data = vjs.getData(elem);
  282. // If no events exist, nothing to unbind
  283. if (!data.handlers) { return; }
  284. // Utility function
  285. var removeType = function(t){
  286. data.handlers[t] = [];
  287. vjs.cleanUpEvents(elem,t);
  288. };
  289. // Are we removing all bound events?
  290. if (!type) {
  291. for (var t in data.handlers) removeType(t);
  292. return;
  293. }
  294. var handlers = data.handlers[type];
  295. // If no handlers exist, nothing to unbind
  296. if (!handlers) return;
  297. // If no listener was provided, remove all listeners for type
  298. if (!fn) {
  299. removeType(type);
  300. return;
  301. }
  302. // We're only removing a single handler
  303. if (fn.guid) {
  304. for (var n = 0; n < handlers.length; n++) {
  305. if (handlers[n].guid === fn.guid) {
  306. handlers.splice(n--, 1);
  307. }
  308. }
  309. }
  310. vjs.cleanUpEvents(elem, type);
  311. };
  312. /**
  313. * Clean up the listener cache and dispatchers
  314. * @param {Element|Object} elem Element to clean up
  315. * @param {String} type Type of event to clean up
  316. * @private
  317. */
  318. vjs.cleanUpEvents = function(elem, type) {
  319. var data = vjs.getData(elem);
  320. // Remove the events of a particular type if there are none left
  321. if (data.handlers[type].length === 0) {
  322. delete data.handlers[type];
  323. // data.handlers[type] = null;
  324. // Setting to null was causing an error with data.handlers
  325. // Remove the meta-handler from the element
  326. if (document.removeEventListener) {
  327. elem.removeEventListener(type, data.dispatcher, false);
  328. } else if (document.detachEvent) {
  329. elem.detachEvent('on' + type, data.dispatcher);
  330. }
  331. }
  332. // Remove the events object if there are no types left
  333. if (vjs.isEmpty(data.handlers)) {
  334. delete data.handlers;
  335. delete data.dispatcher;
  336. delete data.disabled;
  337. // data.handlers = null;
  338. // data.dispatcher = null;
  339. // data.disabled = null;
  340. }
  341. // Finally remove the expando if there is no data left
  342. if (vjs.isEmpty(data)) {
  343. vjs.removeData(elem);
  344. }
  345. };
  346. /**
  347. * Fix a native event to have standard property values
  348. * @param {Object} event Event object to fix
  349. * @return {Object}
  350. * @private
  351. */
  352. vjs.fixEvent = function(event) {
  353. function returnTrue() { return true; }
  354. function returnFalse() { return false; }
  355. // Test if fixing up is needed
  356. // Used to check if !event.stopPropagation instead of isPropagationStopped
  357. // But native events return true for stopPropagation, but don't have
  358. // other expected methods like isPropagationStopped. Seems to be a problem
  359. // with the Javascript Ninja code. So we're just overriding all events now.
  360. if (!event || !event.isPropagationStopped) {
  361. var old = event || window.event;
  362. event = {};
  363. // Clone the old object so that we can modify the values event = {};
  364. // IE8 Doesn't like when you mess with native event properties
  365. // Firefox returns false for event.hasOwnProperty('type') and other props
  366. // which makes copying more difficult.
  367. // TODO: Probably best to create a whitelist of event props
  368. for (var key in old) {
  369. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  370. if (key !== 'layerX' && key !== 'layerY') {
  371. event[key] = old[key];
  372. }
  373. }
  374. // The event occurred on this element
  375. if (!event.target) {
  376. event.target = event.srcElement || document;
  377. }
  378. // Handle which other element the event is related to
  379. event.relatedTarget = event.fromElement === event.target ?
  380. event.toElement :
  381. event.fromElement;
  382. // Stop the default browser action
  383. event.preventDefault = function () {
  384. if (old.preventDefault) {
  385. old.preventDefault();
  386. }
  387. event.returnValue = false;
  388. event.isDefaultPrevented = returnTrue;
  389. };
  390. event.isDefaultPrevented = returnFalse;
  391. // Stop the event from bubbling
  392. event.stopPropagation = function () {
  393. if (old.stopPropagation) {
  394. old.stopPropagation();
  395. }
  396. event.cancelBubble = true;
  397. event.isPropagationStopped = returnTrue;
  398. };
  399. event.isPropagationStopped = returnFalse;
  400. // Stop the event from bubbling and executing other handlers
  401. event.stopImmediatePropagation = function () {
  402. if (old.stopImmediatePropagation) {
  403. old.stopImmediatePropagation();
  404. }
  405. event.isImmediatePropagationStopped = returnTrue;
  406. event.stopPropagation();
  407. };
  408. event.isImmediatePropagationStopped = returnFalse;
  409. // Handle mouse position
  410. if (event.clientX != null) {
  411. var doc = document.documentElement, body = document.body;
  412. event.pageX = event.clientX +
  413. (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
  414. (doc && doc.clientLeft || body && body.clientLeft || 0);
  415. event.pageY = event.clientY +
  416. (doc && doc.scrollTop || body && body.scrollTop || 0) -
  417. (doc && doc.clientTop || body && body.clientTop || 0);
  418. }
  419. // Handle key presses
  420. event.which = event.charCode || event.keyCode;
  421. // Fix button for mouse clicks:
  422. // 0 == left; 1 == middle; 2 == right
  423. if (event.button != null) {
  424. event.button = (event.button & 1 ? 0 :
  425. (event.button & 4 ? 1 :
  426. (event.button & 2 ? 2 : 0)));
  427. }
  428. }
  429. // Returns fixed-up instance
  430. return event;
  431. };
  432. /**
  433. * Trigger an event for an element
  434. * @param {Element|Object} elem Element to trigger an event on
  435. * @param {String} event Type of event to trigger
  436. * @private
  437. */
  438. vjs.trigger = function(elem, event) {
  439. // Fetches element data and a reference to the parent (for bubbling).
  440. // Don't want to add a data object to cache for every parent,
  441. // so checking hasData first.
  442. var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {};
  443. var parent = elem.parentNode || elem.ownerDocument;
  444. // type = event.type || event,
  445. // handler;
  446. // If an event name was passed as a string, creates an event out of it
  447. if (typeof event === 'string') {
  448. event = { type:event, target:elem };
  449. }
  450. // Normalizes the event properties.
  451. event = vjs.fixEvent(event);
  452. // If the passed element has a dispatcher, executes the established handlers.
  453. if (elemData.dispatcher) {
  454. elemData.dispatcher.call(elem, event);
  455. }
  456. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  457. // recursively calls this function to bubble the event up the DOM.
  458. if (parent && !event.isPropagationStopped() && event.bubbles !== false) {
  459. vjs.trigger(parent, event);
  460. // If at the top of the DOM, triggers the default action unless disabled.
  461. } else if (!parent && !event.isDefaultPrevented()) {
  462. var targetData = vjs.getData(event.target);
  463. // Checks if the target has a default action for this event.
  464. if (event.target[event.type]) {
  465. // Temporarily disables event dispatching on the target as we have already executed the handler.
  466. targetData.disabled = true;
  467. // Executes the default action.
  468. if (typeof event.target[event.type] === 'function') {
  469. event.target[event.type]();
  470. }
  471. // Re-enables event dispatching.
  472. targetData.disabled = false;
  473. }
  474. }
  475. // Inform the triggerer if the default was prevented by returning false
  476. return !event.isDefaultPrevented();
  477. /* Original version of js ninja events wasn't complete.
  478. * We've since updated to the latest version, but keeping this around
  479. * for now just in case.
  480. */
  481. // // Added in attion to book. Book code was broke.
  482. // event = typeof event === 'object' ?
  483. // event[vjs.expando] ?
  484. // event :
  485. // new vjs.Event(type, event) :
  486. // new vjs.Event(type);
  487. // event.type = type;
  488. // if (handler) {
  489. // handler.call(elem, event);
  490. // }
  491. // // Clean up the event in case it is being reused
  492. // event.result = undefined;
  493. // event.target = elem;
  494. };
  495. /**
  496. * Trigger a listener only once for an event
  497. * @param {Element|Object} elem Element or object to
  498. * @param {String} type
  499. * @param {Function} fn
  500. * @private
  501. */
  502. vjs.one = function(elem, type, fn) {
  503. var func = function(){
  504. vjs.off(elem, type, func);
  505. fn.apply(this, arguments);
  506. };
  507. func.guid = fn.guid = fn.guid || vjs.guid++;
  508. vjs.on(elem, type, func);
  509. };
  510. var hasOwnProp = Object.prototype.hasOwnProperty;
  511. /**
  512. * Creates an element and applies properties.
  513. * @param {String=} tagName Name of tag to be created.
  514. * @param {Object=} properties Element properties to be applied.
  515. * @return {Element}
  516. * @private
  517. */
  518. vjs.createEl = function(tagName, properties){
  519. var el, propName;
  520. el = document.createElement(tagName || 'div');
  521. for (propName in properties){
  522. if (hasOwnProp.call(properties, propName)) {
  523. //el[propName] = properties[propName];
  524. // Not remembering why we were checking for dash
  525. // but using setAttribute means you have to use getAttribute
  526. // The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin.
  527. // The additional check for "role" is because the default method for adding attributes does not
  528. // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although
  529. // browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs.
  530. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem.
  531. if (propName.indexOf('aria-') !== -1 || propName=='role') {
  532. el.setAttribute(propName, properties[propName]);
  533. } else {
  534. el[propName] = properties[propName];
  535. }
  536. }
  537. }
  538. return el;
  539. };
  540. /**
  541. * Uppercase the first letter of a string
  542. * @param {String} string String to be uppercased
  543. * @return {String}
  544. * @private
  545. */
  546. vjs.capitalize = function(string){
  547. return string.charAt(0).toUpperCase() + string.slice(1);
  548. };
  549. /**
  550. * Object functions container
  551. * @type {Object}
  552. * @private
  553. */
  554. vjs.obj = {};
  555. /**
  556. * Object.create shim for prototypal inheritance
  557. *
  558. * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  559. *
  560. * @function
  561. * @param {Object} obj Object to use as prototype
  562. * @private
  563. */
  564. vjs.obj.create = Object.create || function(obj){
  565. //Create a new function called 'F' which is just an empty object.
  566. function F() {}
  567. //the prototype of the 'F' function should point to the
  568. //parameter of the anonymous function.
  569. F.prototype = obj;
  570. //create a new constructor function based off of the 'F' function.
  571. return new F();
  572. };
  573. /**
  574. * Loop through each property in an object and call a function
  575. * whose arguments are (key,value)
  576. * @param {Object} obj Object of properties
  577. * @param {Function} fn Function to be called on each property.
  578. * @this {*}
  579. * @private
  580. */
  581. vjs.obj.each = function(obj, fn, context){
  582. for (var key in obj) {
  583. if (hasOwnProp.call(obj, key)) {
  584. fn.call(context || this, key, obj[key]);
  585. }
  586. }
  587. };
  588. /**
  589. * Merge two objects together and return the original.
  590. * @param {Object} obj1
  591. * @param {Object} obj2
  592. * @return {Object}
  593. * @private
  594. */
  595. vjs.obj.merge = function(obj1, obj2){
  596. if (!obj2) { return obj1; }
  597. for (var key in obj2){
  598. if (hasOwnProp.call(obj2, key)) {
  599. obj1[key] = obj2[key];
  600. }
  601. }
  602. return obj1;
  603. };
  604. /**
  605. * Merge two objects, and merge any properties that are objects
  606. * instead of just overwriting one. Uses to merge options hashes
  607. * where deeper default settings are important.
  608. * @param {Object} obj1 Object to override
  609. * @param {Object} obj2 Overriding object
  610. * @return {Object} New object. Obj1 and Obj2 will be untouched.
  611. * @private
  612. */
  613. vjs.obj.deepMerge = function(obj1, obj2){
  614. var key, val1, val2;
  615. // make a copy of obj1 so we're not ovewriting original values.
  616. // like prototype.options_ and all sub options objects
  617. obj1 = vjs.obj.copy(obj1);
  618. for (key in obj2){
  619. if (hasOwnProp.call(obj2, key)) {
  620. val1 = obj1[key];
  621. val2 = obj2[key];
  622. // Check if both properties are pure objects and do a deep merge if so
  623. if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) {
  624. obj1[key] = vjs.obj.deepMerge(val1, val2);
  625. } else {
  626. obj1[key] = obj2[key];
  627. }
  628. }
  629. }
  630. return obj1;
  631. };
  632. /**
  633. * Make a copy of the supplied object
  634. * @param {Object} obj Object to copy
  635. * @return {Object} Copy of object
  636. * @private
  637. */
  638. vjs.obj.copy = function(obj){
  639. return vjs.obj.merge({}, obj);
  640. };
  641. /**
  642. * Check if an object is plain, and not a dom node or any object sub-instance
  643. * @param {Object} obj Object to check
  644. * @return {Boolean} True if plain, false otherwise
  645. * @private
  646. */
  647. vjs.obj.isPlain = function(obj){
  648. return !!obj
  649. && typeof obj === 'object'
  650. && obj.toString() === '[object Object]'
  651. && obj.constructor === Object;
  652. };
  653. /**
  654. * Bind (a.k.a proxy or Context). A simple method for changing the context of a function
  655. It also stores a unique id on the function so it can be easily removed from events
  656. * @param {*} context The object to bind as scope
  657. * @param {Function} fn The function to be bound to a scope
  658. * @param {Number=} uid An optional unique ID for the function to be set
  659. * @return {Function}
  660. * @private
  661. */
  662. vjs.bind = function(context, fn, uid) {
  663. // Make sure the function has a unique ID
  664. if (!fn.guid) { fn.guid = vjs.guid++; }
  665. // Create the new function that changes the context
  666. var ret = function() {
  667. return fn.apply(context, arguments);
  668. };
  669. // Allow for the ability to individualize this function
  670. // Needed in the case where multiple objects might share the same prototype
  671. // IF both items add an event listener with the same function, then you try to remove just one
  672. // it will remove both because they both have the same guid.
  673. // when using this, you need to use the bind method when you remove the listener as well.
  674. // currently used in text tracks
  675. ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid;
  676. return ret;
  677. };
  678. /**
  679. * Element Data Store. Allows for binding data to an element without putting it directly on the element.
  680. * Ex. Event listneres are stored here.
  681. * (also from jsninja.com, slightly modified and updated for closure compiler)
  682. * @type {Object}
  683. * @private
  684. */
  685. vjs.cache = {};
  686. /**
  687. * Unique ID for an element or function
  688. * @type {Number}
  689. * @private
  690. */
  691. vjs.guid = 1;
  692. /**
  693. * Unique attribute name to store an element's guid in
  694. * @type {String}
  695. * @constant
  696. * @private
  697. */
  698. vjs.expando = 'vdata' + (new Date()).getTime();
  699. /**
  700. * Returns the cache object where data for an element is stored
  701. * @param {Element} el Element to store data for.
  702. * @return {Object}
  703. * @private
  704. */
  705. vjs.getData = function(el){
  706. var id = el[vjs.expando];
  707. if (!id) {
  708. id = el[vjs.expando] = vjs.guid++;
  709. vjs.cache[id] = {};
  710. }
  711. return vjs.cache[id];
  712. };
  713. /**
  714. * Returns the cache object where data for an element is stored
  715. * @param {Element} el Element to store data for.
  716. * @return {Object}
  717. * @private
  718. */
  719. vjs.hasData = function(el){
  720. var id = el[vjs.expando];
  721. return !(!id || vjs.isEmpty(vjs.cache[id]));
  722. };
  723. /**
  724. * Delete data for the element from the cache and the guid attr from getElementById
  725. * @param {Element} el Remove data for an element
  726. * @private
  727. */
  728. vjs.removeData = function(el){
  729. var id = el[vjs.expando];
  730. if (!id) { return; }
  731. // Remove all stored data
  732. // Changed to = null
  733. // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
  734. // vjs.cache[id] = null;
  735. delete vjs.cache[id];
  736. // Remove the expando property from the DOM node
  737. try {
  738. delete el[vjs.expando];
  739. } catch(e) {
  740. if (el.removeAttribute) {
  741. el.removeAttribute(vjs.expando);
  742. } else {
  743. // IE doesn't appear to support removeAttribute on the document element
  744. el[vjs.expando] = null;
  745. }
  746. }
  747. };
  748. /**
  749. * Check if an object is empty
  750. * @param {Object} obj The object to check for emptiness
  751. * @return {Boolean}
  752. * @private
  753. */
  754. vjs.isEmpty = function(obj) {
  755. for (var prop in obj) {
  756. // Inlude null properties as empty.
  757. if (obj[prop] !== null) {
  758. return false;
  759. }
  760. }
  761. return true;
  762. };
  763. /**
  764. * Add a CSS class name to an element
  765. * @param {Element} element Element to add class name to
  766. * @param {String} classToAdd Classname to add
  767. * @private
  768. */
  769. vjs.addClass = function(element, classToAdd){
  770. if ((' '+element.className+' ').indexOf(' '+classToAdd+' ') == -1) {
  771. element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd;
  772. }
  773. };
  774. /**
  775. * Remove a CSS class name from an element
  776. * @param {Element} element Element to remove from class name
  777. * @param {String} classToAdd Classname to remove
  778. * @private
  779. */
  780. vjs.removeClass = function(element, classToRemove){
  781. var classNames, i;
  782. if (element.className.indexOf(classToRemove) == -1) { return; }
  783. classNames = element.className.split(' ');
  784. // no arr.indexOf in ie8, and we don't want to add a big shim
  785. for (i = classNames.length - 1; i >= 0; i--) {
  786. if (classNames[i] === classToRemove) {
  787. classNames.splice(i,1);
  788. }
  789. }
  790. element.className = classNames.join(' ');
  791. };
  792. /**
  793. * Element for testing browser HTML5 video capabilities
  794. * @type {Element}
  795. * @constant
  796. * @private
  797. */
  798. vjs.TEST_VID = vjs.createEl('video');
  799. /**
  800. * Useragent for browser testing.
  801. * @type {String}
  802. * @constant
  803. * @private
  804. */
  805. vjs.USER_AGENT = navigator.userAgent;
  806. /**
  807. * Device is an iPhone
  808. * @type {Boolean}
  809. * @constant
  810. * @private
  811. */
  812. vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT);
  813. vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT);
  814. vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT);
  815. vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD;
  816. vjs.IOS_VERSION = (function(){
  817. var match = vjs.USER_AGENT.match(/OS (\d+)_/i);
  818. if (match && match[1]) { return match[1]; }
  819. })();
  820. vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT);
  821. vjs.ANDROID_VERSION = (function() {
  822. // This matches Android Major.Minor.Patch versions
  823. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  824. var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i),
  825. major,
  826. minor;
  827. if (!match) {
  828. return null;
  829. }
  830. major = match[1] && parseFloat(match[1]);
  831. minor = match[2] && parseFloat(match[2]);
  832. if (major && minor) {
  833. return parseFloat(match[1] + '.' + match[2]);
  834. } else if (major) {
  835. return major;
  836. } else {
  837. return null;
  838. }
  839. })();
  840. // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser
  841. vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3;
  842. vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT);
  843. vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT);
  844. vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch);
  845. /**
  846. * Get an element's attribute values, as defined on the HTML tag
  847. * Attributs are not the same as properties. They're defined on the tag
  848. * or with setAttribute (which shouldn't be used with HTML)
  849. * This will return true or false for boolean attributes.
  850. * @param {Element} tag Element from which to get tag attributes
  851. * @return {Object}
  852. * @private
  853. */
  854. vjs.getAttributeValues = function(tag){
  855. var obj, knownBooleans, attrs, attrName, attrVal;
  856. obj = {};
  857. // known boolean attributes
  858. // we can check for matching boolean properties, but older browsers
  859. // won't know about HTML5 boolean attributes that we still read from
  860. knownBooleans = ','+'autoplay,controls,loop,muted,default'+',';
  861. if (tag && tag.attributes && tag.attributes.length > 0) {
  862. attrs = tag.attributes;
  863. for (var i = attrs.length - 1; i >= 0; i--) {
  864. attrName = attrs[i].name;
  865. attrVal = attrs[i].value;
  866. // check for known booleans
  867. // the matching element property will return a value for typeof
  868. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) {
  869. // the value of an included boolean attribute is typically an empty
  870. // string ('') which would equal false if we just check for a false value.
  871. // we also don't want support bad code like autoplay='false'
  872. attrVal = (attrVal !== null) ? true : false;
  873. }
  874. obj[attrName] = attrVal;
  875. }
  876. }
  877. return obj;
  878. };
  879. /**
  880. * Get the computed style value for an element
  881. * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/
  882. * @param {Element} el Element to get style value for
  883. * @param {String} strCssRule Style name
  884. * @return {String} Style value
  885. * @private
  886. */
  887. vjs.getComputedDimension = function(el, strCssRule){
  888. var strValue = '';
  889. if(document.defaultView && document.defaultView.getComputedStyle){
  890. strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule);
  891. } else if(el.currentStyle){
  892. // IE8 Width/Height support
  893. strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px';
  894. }
  895. return strValue;
  896. };
  897. /**
  898. * Insert an element as the first child node of another
  899. * @param {Element} child Element to insert
  900. * @param {[type]} parent Element to insert child into
  901. * @private
  902. */
  903. vjs.insertFirst = function(child, parent){
  904. if (parent.firstChild) {
  905. parent.insertBefore(child, parent.firstChild);
  906. } else {
  907. parent.appendChild(child);
  908. }
  909. };
  910. /**
  911. * Object to hold browser support information
  912. * @type {Object}
  913. * @private
  914. */
  915. vjs.support = {};
  916. /**
  917. * Shorthand for document.getElementById()
  918. * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs.
  919. * @param {String} id Element ID
  920. * @return {Element} Element with supplied ID
  921. * @private
  922. */
  923. vjs.el = function(id){
  924. if (id.indexOf('#') === 0) {
  925. id = id.slice(1);
  926. }
  927. return document.getElementById(id);
  928. };
  929. /**
  930. * Format seconds as a time string, H:MM:SS or M:SS
  931. * Supplying a guide (in seconds) will force a number of leading zeros
  932. * to cover the length of the guide
  933. * @param {Number} seconds Number of seconds to be turned into a string
  934. * @param {Number} guide Number (in seconds) to model the string after
  935. * @return {String} Time formatted as H:MM:SS or M:SS
  936. * @private
  937. */
  938. vjs.formatTime = function(seconds, guide) {
  939. // Default to using seconds as guide
  940. guide = guide || seconds;
  941. var s = Math.floor(seconds % 60),
  942. m = Math.floor(seconds / 60 % 60),
  943. h = Math.floor(seconds / 3600),
  944. gm = Math.floor(guide / 60 % 60),
  945. gh = Math.floor(guide / 3600);
  946. // handle invalid times
  947. if (isNaN(seconds) || seconds === Infinity) {
  948. // '-' is false for all relational operators (e.g. <, >=) so this setting
  949. // will add the minimum number of fields specified by the guide
  950. h = m = s = '-';
  951. }
  952. // Check if we need to show hours
  953. h = (h > 0 || gh > 0) ? h + ':' : '';
  954. // If hours are showing, we may need to add a leading zero.
  955. // Always show at least one digit of minutes.
  956. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':';
  957. // Check if leading zero is need for seconds
  958. s = (s < 10) ? '0' + s : s;
  959. return h + m + s;
  960. };
  961. // Attempt to block the ability to select text while dragging controls
  962. vjs.blockTextSelection = function(){
  963. document.body.focus();
  964. document.onselectstart = function () { return false; };
  965. };
  966. // Turn off text selection blocking
  967. vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; };
  968. /**
  969. * Trim whitespace from the ends of a string.
  970. * @param {String} string String to trim
  971. * @return {String} Trimmed string
  972. * @private
  973. */
  974. vjs.trim = function(str){
  975. return (str+'').replace(/^\s+|\s+$/g, '');
  976. };
  977. /**
  978. * Should round off a number to a decimal place
  979. * @param {Number} num Number to round
  980. * @param {Number} dec Number of decimal places to round to
  981. * @return {Number} Rounded number
  982. * @private
  983. */
  984. vjs.round = function(num, dec) {
  985. if (!dec) { dec = 0; }
  986. return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  987. };
  988. /**
  989. * Should create a fake TimeRange object
  990. * Mimics an HTML5 time range instance, which has functions that
  991. * return the start and end times for a range
  992. * TimeRanges are returned by the buffered() method
  993. * @param {Number} start Start time in seconds
  994. * @param {Number} end End time in seconds
  995. * @return {Object} Fake TimeRange object
  996. * @private
  997. */
  998. vjs.createTimeRange = function(start, end){
  999. return {
  1000. length: 1,
  1001. start: function() { return start; },
  1002. end: function() { return end; }
  1003. };
  1004. };
  1005. /**
  1006. * Simple http request for retrieving external files (e.g. text tracks)
  1007. * @param {String} url URL of resource
  1008. * @param {Function=} onSuccess Success callback
  1009. * @param {Function=} onError Error callback
  1010. * @private
  1011. */
  1012. vjs.get = function(url, onSuccess, onError){
  1013. var local, request;
  1014. if (typeof XMLHttpRequest === 'undefined') {
  1015. window.XMLHttpRequest = function () {
  1016. try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {}
  1017. try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {}
  1018. try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {}
  1019. throw new Error('This browser does not support XMLHttpRequest.');
  1020. };
  1021. }
  1022. request = new XMLHttpRequest();
  1023. try {
  1024. request.open('GET', url);
  1025. } catch(e) {
  1026. onError(e);
  1027. }
  1028. local = (url.indexOf('file:') === 0 || (window.location.href.indexOf('file:') === 0 && url.indexOf('http') === -1));
  1029. request.onreadystatechange = function() {
  1030. if (request.readyState === 4) {
  1031. if (request.status === 200 || local && request.status === 0) {
  1032. onSuccess(request.responseText);
  1033. } else {
  1034. if (onError) {
  1035. onError();
  1036. }
  1037. }
  1038. }
  1039. };
  1040. try {
  1041. request.send();
  1042. } catch(e) {
  1043. if (onError) {
  1044. onError(e);
  1045. }
  1046. }
  1047. };
  1048. /**
  1049. * Add to local storage (may removeable)
  1050. * @private
  1051. */
  1052. vjs.setLocalStorage = function(key, value){
  1053. try {
  1054. // IE was throwing errors referencing the var anywhere without this
  1055. var localStorage = window.localStorage || false;
  1056. if (!localStorage) { return; }
  1057. localStorage[key] = value;
  1058. } catch(e) {
  1059. if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014
  1060. vjs.log('LocalStorage Full (VideoJS)', e);
  1061. } else {
  1062. if (e.code == 18) {
  1063. vjs.log('LocalStorage not allowed (VideoJS)', e);
  1064. } else {
  1065. vjs.log('LocalStorage Error (VideoJS)', e);
  1066. }
  1067. }
  1068. }
  1069. };
  1070. /**
  1071. * Get abosolute version of relative URL. Used to tell flash correct URL.
  1072. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  1073. * @param {String} url URL to make absolute
  1074. * @return {String} Absolute URL
  1075. * @private
  1076. */
  1077. vjs.getAbsoluteURL = function(url){
  1078. // Check if absolute URL
  1079. if (!url.match(/^https?:\/\//)) {
  1080. // Convert to absolute URL. Flash hosted off-site needs an absolute URL.
  1081. url = vjs.createEl('div', {
  1082. innerHTML: '<a href="'+url+'">x</a>'
  1083. }).firstChild.href;
  1084. }
  1085. return url;
  1086. };
  1087. // usage: log('inside coolFunc',this,arguments);
  1088. // http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
  1089. vjs.log = function(){
  1090. vjs.log.history = vjs.log.history || []; // store logs to an array for reference
  1091. vjs.log.history.push(arguments);
  1092. if(window.console){
  1093. window.console.log(Array.prototype.slice.call(arguments));
  1094. }
  1095. };
  1096. // Offset Left
  1097. // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1098. vjs.findPosition = function(el) {
  1099. var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top;
  1100. if (el.getBoundingClientRect && el.parentNode) {
  1101. box = el.getBoundingClientRect();
  1102. }
  1103. if (!box) {
  1104. return {
  1105. left: 0,
  1106. top: 0
  1107. };
  1108. }
  1109. docEl = document.documentElement;
  1110. body = document.body;
  1111. clientLeft = docEl.clientLeft || body.clientLeft || 0;
  1112. scrollLeft = window.pageXOffset || body.scrollLeft;
  1113. left = box.left + scrollLeft - clientLeft;
  1114. clientTop = docEl.clientTop || body.clientTop || 0;
  1115. scrollTop = window.pageYOffset || body.scrollTop;
  1116. top = box.top + scrollTop - clientTop;
  1117. return {
  1118. left: left,
  1119. top: top
  1120. };
  1121. };
  1122. /**
  1123. * @fileoverview Player Component - Base class for all UI objects
  1124. *
  1125. */
  1126. /**
  1127. * Base UI Component class
  1128. *
  1129. * Components are embeddable UI objects that are represented by both a
  1130. * javascript object and an element in the DOM. They can be children of other
  1131. * components, and can have many children themselves.
  1132. *
  1133. * // adding a button to the player
  1134. * var button = player.addChild('button');
  1135. * button.el(); // -> button element
  1136. *
  1137. * <div class="video-js">
  1138. * <div class="vjs-button">Button</div>
  1139. * </div>
  1140. *
  1141. * Components are also event emitters.
  1142. *
  1143. * button.on('click', function(){
  1144. * console.log('Button Clicked!');
  1145. * });
  1146. *
  1147. * button.trigger('customevent');
  1148. *
  1149. * @param {Object} player Main Player
  1150. * @param {Object=} options
  1151. * @class
  1152. * @constructor
  1153. * @extends vjs.CoreObject
  1154. */
  1155. vjs.Component = vjs.CoreObject.extend({
  1156. /**
  1157. * the constructor funciton for the class
  1158. *
  1159. * @constructor
  1160. */
  1161. init: function(player, options, ready){
  1162. this.player_ = player;
  1163. // Make a copy of prototype.options_ to protect against overriding global defaults
  1164. this.options_ = vjs.obj.copy(this.options_);
  1165. // Updated options with supplied options
  1166. options = this.options(options);
  1167. // Get ID from options, element, or create using player ID and unique ID
  1168. this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ );
  1169. this.name_ = options['name'] || null;
  1170. // Create element if one wasn't provided in options
  1171. this.el_ = options['el'] || this.createEl();
  1172. this.children_ = [];
  1173. this.childIndex_ = {};
  1174. this.childNameIndex_ = {};
  1175. // Add any child components in options
  1176. this.initChildren();
  1177. this.ready(ready);
  1178. // Don't want to trigger ready here or it will before init is actually
  1179. // finished for all children that run this constructor
  1180. }
  1181. });
  1182. /**
  1183. * Dispose of the component and all child components
  1184. */
  1185. vjs.Component.prototype.dispose = function(){
  1186. this.trigger('dispose');
  1187. // Dispose all children.
  1188. if (this.children_) {
  1189. for (var i = this.children_.length - 1; i >= 0; i--) {
  1190. if (this.children_[i].dispose) {
  1191. this.children_[i].dispose();
  1192. }
  1193. }
  1194. }
  1195. // Delete child references
  1196. this.children_ = null;
  1197. this.childIndex_ = null;
  1198. this.childNameIndex_ = null;
  1199. // Remove all event listeners.
  1200. this.off();
  1201. // Remove element from DOM
  1202. if (this.el_.parentNode) {
  1203. this.el_.parentNode.removeChild(this.el_);
  1204. }
  1205. vjs.removeData(this.el_);
  1206. this.el_ = null;
  1207. };
  1208. /**
  1209. * Reference to main player instance
  1210. *
  1211. * @type {vjs.Player}
  1212. * @private
  1213. */
  1214. vjs.Component.prototype.player_ = true;
  1215. /**
  1216. * Return the component's player
  1217. *
  1218. * @return {vjs.Player}
  1219. */
  1220. vjs.Component.prototype.player = function(){
  1221. return this.player_;
  1222. };
  1223. /**
  1224. * The component's options object
  1225. *
  1226. * @type {Object}
  1227. * @private
  1228. */
  1229. vjs.Component.prototype.options_;
  1230. /**
  1231. * Deep merge of options objects
  1232. *
  1233. * Whenever a property is an object on both options objects
  1234. * the two properties will be merged using vjs.obj.deepMerge.
  1235. *
  1236. * This is used for merging options for child components. We
  1237. * want it to be easy to override individual options on a child
  1238. * component without having to rewrite all the other default options.
  1239. *
  1240. * Parent.prototype.options_ = {
  1241. * children: {
  1242. * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' },
  1243. * 'childTwo': {},
  1244. * 'childThree': {}
  1245. * }
  1246. * }
  1247. * newOptions = {
  1248. * children: {
  1249. * 'childOne': { 'foo': 'baz', 'abc': '123' }
  1250. * 'childTwo': null,
  1251. * 'childFour': {}
  1252. * }
  1253. * }
  1254. *
  1255. * this.options(newOptions);
  1256. *
  1257. * RESULT
  1258. *
  1259. * {
  1260. * children: {
  1261. * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' },
  1262. * 'childTwo': null, // Disabled. Won't be initialized.
  1263. * 'childThree': {},
  1264. * 'childFour': {}
  1265. * }
  1266. * }
  1267. *
  1268. * @param {Object} obj Object whose values will be overwritten
  1269. * @return {Object} NEW merged object. Does not return obj1.
  1270. */
  1271. vjs.Component.prototype.options = function(obj){
  1272. if (obj === undefined) return this.options_;
  1273. return this.options_ = vjs.obj.deepMerge(this.options_, obj);
  1274. };
  1275. /**
  1276. * The DOM element for the component
  1277. *
  1278. * @type {Element}
  1279. * @private
  1280. */
  1281. vjs.Component.prototype.el_;
  1282. /**
  1283. * Create the component's DOM element
  1284. *
  1285. * @param {String=} tagName Element's node type. e.g. 'div'
  1286. * @param {Object=} attributes An object of element attributes that should be set on the element
  1287. * @return {Element}
  1288. */
  1289. vjs.Component.prototype.createEl = function(tagName, attributes){
  1290. return vjs.createEl(tagName, attributes);
  1291. };
  1292. /**
  1293. * Get the component's DOM element
  1294. *
  1295. * var domEl = myComponent.el();
  1296. *
  1297. * @return {Element}
  1298. */
  1299. vjs.Component.prototype.el = function(){
  1300. return this.el_;
  1301. };
  1302. /**
  1303. * An optional element where, if defined, children will be inserted instead of
  1304. * directly in `el_`
  1305. *
  1306. * @type {Element}
  1307. * @private
  1308. */
  1309. vjs.Component.prototype.contentEl_;
  1310. /**
  1311. * Return the component's DOM element for embedding content.
  1312. * Will either be el_ or a new element defined in createEl.
  1313. *
  1314. * @return {Element}
  1315. */
  1316. vjs.Component.prototype.contentEl = function(){
  1317. return this.contentEl_ || this.el_;
  1318. };
  1319. /**
  1320. * The ID for the component
  1321. *
  1322. * @type {String}
  1323. * @private
  1324. */
  1325. vjs.Component.prototype.id_;
  1326. /**
  1327. * Get the component's ID
  1328. *
  1329. * var id = myComponent.id();
  1330. *
  1331. * @return {String}
  1332. */
  1333. vjs.Component.prototype.id = function(){
  1334. return this.id_;
  1335. };
  1336. /**
  1337. * The name for the component. Often used to reference the component.
  1338. *
  1339. * @type {String}
  1340. * @private
  1341. */
  1342. vjs.Component.prototype.name_;
  1343. /**
  1344. * Get the component's name. The name is often used to reference the component.
  1345. *
  1346. * var name = myComponent.name();
  1347. *
  1348. * @return {String}
  1349. */
  1350. vjs.Component.prototype.name = function(){
  1351. return this.name_;
  1352. };
  1353. /**
  1354. * Array of child components
  1355. *
  1356. * @type {Array}
  1357. * @private
  1358. */
  1359. vjs.Component.prototype.children_;
  1360. /**
  1361. * Get an array of all child components
  1362. *
  1363. * var kids = myComponent.children();
  1364. *
  1365. * @return {Array} The children
  1366. */
  1367. vjs.Component.prototype.children = function(){
  1368. return this.children_;
  1369. };
  1370. /**
  1371. * Object of child components by ID
  1372. *
  1373. * @type {Object}
  1374. * @private
  1375. */
  1376. vjs.Component.prototype.childIndex_;
  1377. /**
  1378. * Returns a child component with the provided ID
  1379. *
  1380. * @return {vjs.Component}
  1381. */
  1382. vjs.Component.prototype.getChildById = function(id){
  1383. return this.childIndex_[id];
  1384. };
  1385. /**
  1386. * Object of child components by name
  1387. *
  1388. * @type {Object}
  1389. * @private
  1390. */
  1391. vjs.Component.prototype.childNameIndex_;
  1392. /**
  1393. * Returns a child component with the provided ID
  1394. *
  1395. * @return {vjs.Component}
  1396. */
  1397. vjs.Component.prototype.getChild = function(name){
  1398. return this.childNameIndex_[name];
  1399. };
  1400. /**
  1401. * Adds a child component inside this component
  1402. *
  1403. * myComponent.el();
  1404. * // -> <div class='my-component'></div>
  1405. * myComonent.children();
  1406. * // [empty array]
  1407. *
  1408. * var myButton = myComponent.addChild('MyButton');
  1409. * // -> <div class='my-component'><div class="my-button">myButton<div></div>
  1410. * // -> myButton === myComonent.children()[0];
  1411. *
  1412. * Pass in options for child constructors and options for children of the child
  1413. *
  1414. * var myButton = myComponent.addChild('MyButton', {
  1415. * text: 'Press Me',
  1416. * children: {
  1417. * buttonChildExample: {
  1418. * buttonChildOption: true
  1419. * }
  1420. * }
  1421. * });
  1422. *
  1423. * @param {String|vjs.Component} child The class name or instance of a child to add
  1424. * @param {Object=} options Options, including options to be passed to children of the child.
  1425. * @return {vjs.Component} The child component (created by this process if a string was used)
  1426. * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility}
  1427. */
  1428. vjs.Component.prototype.addChild = function(child, options){
  1429. var component, componentClass, componentName, componentId;
  1430. // If string, create new component with options
  1431. if (typeof child === 'string') {
  1432. componentName = child;
  1433. // Make sure options is at least an empty object to protect against errors
  1434. options = options || {};
  1435. // Assume name of set is a lowercased name of the UI Class (PlayButton, etc.)
  1436. componentClass = options['componentClass'] || vjs.capitalize(componentName);
  1437. // Set name through options
  1438. options['name'] = componentName;
  1439. // Create a new object & element for this controls set
  1440. // If there's no .player_, this is a player
  1441. // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly.
  1442. // Every class should be exported, so this should never be a problem here.
  1443. component = new window['videojs'][componentClass](this.player_ || this, options);
  1444. // child is a component instance
  1445. } else {
  1446. component = child;
  1447. }
  1448. this.children_.push(component);
  1449. if (typeof component.id === 'function') {
  1450. this.childIndex_[component.id()] = component;
  1451. }
  1452. // If a name wasn't used to create the component, check if we can use the
  1453. // name function of the component
  1454. componentName = componentName || (component.name && component.name());
  1455. if (componentName) {
  1456. this.childNameIndex_[componentName] = component;
  1457. }
  1458. // Add the UI object's element to the container div (box)
  1459. // Having an element is not required
  1460. if (typeof component['el'] === 'function' && component['el']()) {
  1461. this.contentEl().appendChild(component['el']());
  1462. }
  1463. // Return so it can stored on parent object if desired.
  1464. return component;
  1465. };
  1466. /**
  1467. * Remove a child component from this component's list of children, and the
  1468. * child component's element from this component's element
  1469. *
  1470. * @param {vjs.Component} component Component to remove
  1471. */
  1472. vjs.Component.prototype.removeChild = function(component){
  1473. if (typeof component === 'string') {
  1474. component = this.getChild(component);
  1475. }
  1476. if (!component || !this.children_) return;
  1477. var childFound = false;
  1478. for (var i = this.children_.length - 1; i >= 0; i--) {
  1479. if (this.children_[i] === component) {
  1480. childFound = true;
  1481. this.children_.splice(i,1);
  1482. break;
  1483. }
  1484. }
  1485. if (!childFound) return;
  1486. this.childIndex_[component.id] = null;
  1487. this.childNameIndex_[component.name] = null;
  1488. var compEl = component.el();
  1489. if (compEl && compEl.parentNode === this.contentEl()) {
  1490. this.contentEl().removeChild(component.el());
  1491. }
  1492. };
  1493. /**
  1494. * Add and initialize default child components from options
  1495. *
  1496. * // when an instance of MyComponent is created, all children in options
  1497. * // will be added to the instance by their name strings and options
  1498. * MyComponent.prototype.options_.children = {
  1499. * myChildComponent: {
  1500. * myChildOption: true
  1501. * }
  1502. * }
  1503. */
  1504. vjs.Component.prototype.initChildren = function(){
  1505. var options = this.options_;
  1506. if (options && options['children']) {
  1507. var self = this;
  1508. // Loop through components and add them to the player
  1509. vjs.obj.each(options['children'], function(name, opts){
  1510. // Allow for disabling default components
  1511. // e.g. vjs.options['children']['posterImage'] = false
  1512. if (opts === false) return;
  1513. // Allow waiting to add components until a specific event is called
  1514. var tempAdd = function(){
  1515. // Set property name on player. Could cause conflicts with other prop names, but it's worth making refs easy.
  1516. self[name] = self.addChild(name, opts);
  1517. };
  1518. if (opts['loadEvent']) {
  1519. // this.one(opts.loadEvent, tempAdd)
  1520. } else {
  1521. tempAdd();
  1522. }
  1523. });
  1524. }
  1525. };
  1526. /**
  1527. * Allows sub components to stack CSS class names
  1528. *
  1529. * @return {String} The constructed class name
  1530. */
  1531. vjs.Component.prototype.buildCSSClass = function(){
  1532. // Child classes can include a function that does:
  1533. // return 'CLASS NAME' + this._super();
  1534. return '';
  1535. };
  1536. /* Events
  1537. ============================================================================= */
  1538. /**
  1539. * Add an event listener to this component's element
  1540. *
  1541. * var myFunc = function(){
  1542. * var myPlayer = this;
  1543. * // Do something when the event is fired
  1544. * };
  1545. *
  1546. * myPlayer.on("eventName", myFunc);
  1547. *
  1548. * The context will be the component.
  1549. *
  1550. * @param {String} type The event type e.g. 'click'
  1551. * @param {Function} fn The event listener
  1552. * @return {vjs.Component} self
  1553. */
  1554. vjs.Component.prototype.on = function(type, fn){
  1555. vjs.on(this.el_, type, vjs.bind(this, fn));
  1556. return this;
  1557. };
  1558. /**
  1559. * Remove an event listener from the component's element
  1560. *
  1561. * myComponent.off("eventName", myFunc);
  1562. *
  1563. * @param {String=} type Event type. Without type it will remove all listeners.
  1564. * @param {Function=} fn Event listener. Without fn it will remove all listeners for a type.
  1565. * @return {vjs.Component}
  1566. */
  1567. vjs.Component.prototype.off = function(type, fn){
  1568. vjs.off(this.el_, type, fn);
  1569. return this;
  1570. };
  1571. /**
  1572. * Add an event listener to be triggered only once and then removed
  1573. *
  1574. * @param {String} type Event type
  1575. * @param {Function} fn Event listener
  1576. * @return {vjs.Component}
  1577. */
  1578. vjs.Component.prototype.one = function(type, fn) {
  1579. vjs.one(this.el_, type, vjs.bind(this, fn));
  1580. return this;
  1581. };
  1582. /**
  1583. * Trigger an event on an element
  1584. *
  1585. * myComponent.trigger('eventName');
  1586. *
  1587. * @param {String} type The event type to trigger, e.g. 'click'
  1588. * @param {Event|Object} event The event object to be passed to the listener
  1589. * @return {vjs.Component} self
  1590. */
  1591. vjs.Component.prototype.trigger = function(type, event){
  1592. vjs.trigger(this.el_, type, event);
  1593. return this;
  1594. };
  1595. /* Ready
  1596. ================================================================================ */
  1597. /**
  1598. * Is the component loaded
  1599. * This can mean different things depending on the component.
  1600. *
  1601. * @private
  1602. * @type {Boolean}
  1603. */
  1604. vjs.Component.prototype.isReady_;
  1605. /**
  1606. * Trigger ready as soon as initialization is finished
  1607. *
  1608. * Allows for delaying ready. Override on a sub class prototype.
  1609. * If you set this.isReadyOnInitFinish_ it will affect all components.
  1610. * Specially used when waiting for the Flash player to asynchrnously load.
  1611. *
  1612. * @type {Boolean}
  1613. * @private
  1614. */
  1615. vjs.Component.prototype.isReadyOnInitFinish_ = true;
  1616. /**
  1617. * List of ready listeners
  1618. *
  1619. * @type {Array}
  1620. * @private
  1621. */
  1622. vjs.Component.prototype.readyQueue_;
  1623. /**
  1624. * Bind a listener to the component's ready state
  1625. *
  1626. * Different from event listeners in that if the ready event has already happend
  1627. * it will trigger the function immediately.
  1628. *
  1629. * @param {Function} fn Ready listener
  1630. * @return {vjs.Component}
  1631. */
  1632. vjs.Component.prototype.ready = function(fn){
  1633. if (fn) {
  1634. if (this.isReady_) {
  1635. fn.call(this);
  1636. } else {
  1637. if (this.readyQueue_ === undefined) {
  1638. this.readyQueue_ = [];
  1639. }
  1640. this.readyQueue_.push(fn);
  1641. }
  1642. }
  1643. return this;
  1644. };
  1645. /**
  1646. * Trigger the ready listeners
  1647. *
  1648. * @return {vjs.Component}
  1649. */
  1650. vjs.Component.prototype.triggerReady = function(){
  1651. this.isReady_ = true;
  1652. var readyQueue = this.readyQueue_;
  1653. if (readyQueue && readyQueue.length > 0) {
  1654. for (var i = 0, j = readyQueue.length; i < j; i++) {
  1655. readyQueue[i].call(this);
  1656. }
  1657. // Reset Ready Queue
  1658. this.readyQueue_ = [];
  1659. // Allow for using event listeners also, in case you want to do something everytime a source is ready.
  1660. this.trigger('ready');
  1661. }
  1662. };
  1663. /* Display
  1664. ============================================================================= */
  1665. /**
  1666. * Add a CSS class name to the component's element
  1667. *
  1668. * @param {String} classToAdd Classname to add
  1669. * @return {vjs.Component}
  1670. */
  1671. vjs.Component.prototype.addClass = function(classToAdd){
  1672. vjs.addClass(this.el_, classToAdd);
  1673. return this;
  1674. };
  1675. /**
  1676. * Remove a CSS class name from the component's element
  1677. *
  1678. * @param {String} classToRemove Classname to remove
  1679. * @return {vjs.Component}
  1680. */
  1681. vjs.Component.prototype.removeClass = function(classToRemove){
  1682. vjs.removeClass(this.el_, classToRemove);
  1683. return this;
  1684. };
  1685. /**
  1686. * Show the component element if hidden
  1687. *
  1688. * @return {vjs.Component}
  1689. */
  1690. vjs.Component.prototype.show = function(){
  1691. this.el_.style.display = 'block';
  1692. return this;
  1693. };
  1694. /**
  1695. * Hide the component element if hidden
  1696. *
  1697. * @return {vjs.Component}
  1698. */
  1699. vjs.Component.prototype.hide = function(){
  1700. this.el_.style.display = 'none';
  1701. return this;
  1702. };
  1703. /**
  1704. * Lock an item in its visible state
  1705. * To be used with fadeIn/fadeOut.
  1706. *
  1707. * @return {vjs.Component}
  1708. * @private
  1709. */
  1710. vjs.Component.prototype.lockShowing = function(){
  1711. this.addClass('vjs-lock-showing');
  1712. return this;
  1713. };
  1714. /**
  1715. * Unlock an item to be hidden
  1716. * To be used with fadeIn/fadeOut.
  1717. *
  1718. * @return {vjs.Component}
  1719. * @private
  1720. */
  1721. vjs.Component.prototype.unlockShowing = function(){
  1722. this.removeClass('vjs-lock-showing');
  1723. return this;
  1724. };
  1725. /**
  1726. * Disable component by making it unshowable
  1727. */
  1728. vjs.Component.prototype.disable = function(){
  1729. this.hide();
  1730. this.show = function(){};
  1731. };
  1732. /**
  1733. * Set or get the width of the component (CSS values)
  1734. *
  1735. * Video tag width/height only work in pixels. No percents.
  1736. * But allowing limited percents use. e.g. width() will return number+%, not computed width
  1737. *
  1738. * @param {Number|String=} num Optional width number
  1739. * @param {Boolean} skipListeners Skip the 'resize' event trigger
  1740. * @return {vjs.Component} Returns 'this' if width was set
  1741. * @return {Number|String} Returns the width if nothing was set
  1742. */
  1743. vjs.Component.prototype.width = function(num, skipListeners){
  1744. return this.dimension('width', num, skipListeners);
  1745. };
  1746. /**
  1747. * Get or set the height of the component (CSS values)
  1748. *
  1749. * @param {Number|String=} num New component height
  1750. * @param {Boolean=} skipListeners Skip the resize event trigger
  1751. * @return {vjs.Component} The component if the height was set
  1752. * @return {Number|String} The height if it wasn't set
  1753. */
  1754. vjs.Component.prototype.height = function(num, skipListeners){
  1755. return this.dimension('height', num, skipListeners);
  1756. };
  1757. /**
  1758. * Set both width and height at the same time
  1759. *
  1760. * @param {Number|String} width
  1761. * @param {Number|String} height
  1762. * @return {vjs.Component} The component
  1763. */
  1764. vjs.Component.prototype.dimensions = function(width, height){
  1765. // Skip resize listeners on width for optimization
  1766. return this.width(width, true).height(height);
  1767. };
  1768. /**
  1769. * Get or set width or height
  1770. *
  1771. * This is the shared code for the width() and height() methods.
  1772. * All for an integer, integer + 'px' or integer + '%';
  1773. *
  1774. * Known issue: Hidden elements officially have a width of 0. We're defaulting
  1775. * to the style.width value and falling back to computedStyle which has the
  1776. * hidden element issue. Info, but probably not an efficient fix:
  1777. * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/
  1778. *
  1779. * @param {String} widthOrHeight 'width' or 'height'
  1780. * @param {Number|String=} num New dimension
  1781. * @param {Boolean=} skipListeners Skip resize event trigger
  1782. * @return {vjs.Component} The component if a dimension was set
  1783. * @return {Number|String} The dimension if nothing was set
  1784. * @private
  1785. */
  1786. vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){
  1787. if (num !== undefined) {
  1788. // Check if using css width/height (% or px) and adjust
  1789. if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) {
  1790. this.el_.style[widthOrHeight] = num;
  1791. } else if (num === 'auto') {
  1792. this.el_.style[widthOrHeight] = '';
  1793. } else {
  1794. this.el_.style[widthOrHeight] = num+'px';
  1795. }
  1796. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  1797. if (!skipListeners) { this.trigger('resize'); }
  1798. // Return component
  1799. return this;
  1800. }
  1801. // Not setting a value, so getting it
  1802. // Make sure element exists
  1803. if (!this.el_) return 0;
  1804. // Get dimension value from style
  1805. var val = this.el_.style[widthOrHeight];
  1806. var pxIndex = val.indexOf('px');
  1807. if (pxIndex !== -1) {
  1808. // Return the pixel value with no 'px'
  1809. return parseInt(val.slice(0,pxIndex), 10);
  1810. // No px so using % or no style was set, so falling back to offsetWidth/height
  1811. // If component has display:none, offset will return 0
  1812. // TODO: handle display:none and no dimension style using px
  1813. } else {
  1814. return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10);
  1815. // ComputedStyle version.
  1816. // Only difference is if the element is hidden it will return
  1817. // the percent value (e.g. '100%'')
  1818. // instead of zero like offsetWidth returns.
  1819. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight);
  1820. // var pxIndex = val.indexOf('px');
  1821. // if (pxIndex !== -1) {
  1822. // return val.slice(0, pxIndex);
  1823. // } else {
  1824. // return val;
  1825. // }
  1826. }
  1827. };
  1828. /**
  1829. * Fired when the width and/or height of the component changes
  1830. * @event resize
  1831. */
  1832. vjs.Component.prototype.onResize;
  1833. /**
  1834. * Emit 'tap' events when touch events are supported
  1835. *
  1836. * This is used to support toggling the controls through a tap on the video.
  1837. *
  1838. * We're requireing them to be enabled because otherwise every component would
  1839. * have this extra overhead unnecessarily, on mobile devices where extra
  1840. * overhead is especially bad.
  1841. * @private
  1842. */
  1843. vjs.Component.prototype.emitTapEvents = function(){
  1844. var touchStart, touchTime, couldBeTap, noTap;
  1845. // Track the start time so we can determine how long the touch lasted
  1846. touchStart = 0;
  1847. this.on('touchstart', function(event) {
  1848. // Record start time so we can detect a tap vs. "touch and hold"
  1849. touchStart = new Date().getTime();
  1850. // Reset couldBeTap tracking
  1851. couldBeTap = true;
  1852. });
  1853. noTap = function(){
  1854. couldBeTap = false;
  1855. };
  1856. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  1857. this.on('touchmove', noTap);
  1858. this.on('touchleave', noTap);
  1859. this.on('touchcancel', noTap);
  1860. // When the touch ends, measure how long it took and trigger the appropriate
  1861. // event
  1862. this.on('touchend', function() {
  1863. // Proceed only if the touchmove/leave/cancel event didn't happen
  1864. if (couldBeTap === true) {
  1865. // Measure how long the touch lasted
  1866. touchTime = new Date().getTime() - touchStart;
  1867. // The touch needs to be quick in order to consider it a tap
  1868. if (touchTime < 250) {
  1869. this.trigger('tap');
  1870. // It may be good to copy the touchend event object and change the
  1871. // type to tap, if the other event properties aren't exact after
  1872. // vjs.fixEvent runs (e.g. event.target)
  1873. }
  1874. }
  1875. });
  1876. };
  1877. /* Button - Base class for all buttons
  1878. ================================================================================ */
  1879. /**
  1880. * Base class for all buttons
  1881. * @param {vjs.Player|Object} player
  1882. * @param {Object=} options
  1883. * @class
  1884. * @constructor
  1885. */
  1886. vjs.Button = vjs.Component.extend({
  1887. /**
  1888. * @constructor
  1889. * @inheritDoc
  1890. */
  1891. init: function(player, options){
  1892. vjs.Component.call(this, player, options);
  1893. var touchstart = false;
  1894. this.on('touchstart', function(event) {
  1895. // Stop click and other mouse events from triggering also
  1896. event.preventDefault();
  1897. touchstart = true;
  1898. });
  1899. this.on('touchmove', function() {
  1900. touchstart = false;
  1901. });
  1902. var self = this;
  1903. this.on('touchend', function(event) {
  1904. if (touchstart) {
  1905. self.onClick(event);
  1906. }
  1907. event.preventDefault();
  1908. });
  1909. this.on('click', this.onClick);
  1910. this.on('focus', this.onFocus);
  1911. this.on('blur', this.onBlur);
  1912. }
  1913. });
  1914. vjs.Button.prototype.createEl = function(type, props){
  1915. // Add standard Aria and Tabindex info
  1916. props = vjs.obj.merge({
  1917. className: this.buildCSSClass(),
  1918. innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">' + (this.buttonText || 'Need Text') + '</span></div>',
  1919. role: 'button',
  1920. 'aria-live': 'polite', // let the screen reader user know that the text of the button may change
  1921. tabIndex: 0
  1922. }, props);
  1923. return vjs.Component.prototype.createEl.call(this, type, props);
  1924. };
  1925. vjs.Button.prototype.buildCSSClass = function(){
  1926. // TODO: Change vjs-control to vjs-button?
  1927. return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this);
  1928. };
  1929. // Click - Override with specific functionality for button
  1930. vjs.Button.prototype.onClick = function(){};
  1931. // Focus - Add keyboard functionality to element
  1932. vjs.Button.prototype.onFocus = function(){
  1933. vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress));
  1934. };
  1935. // KeyPress (document level) - Trigger click when keys are pressed
  1936. vjs.Button.prototype.onKeyPress = function(event){
  1937. // Check for space bar (32) or enter (13) keys
  1938. if (event.which == 32 || event.which == 13) {
  1939. event.preventDefault();
  1940. this.onClick();
  1941. }
  1942. };
  1943. // Blur - Remove keyboard triggers
  1944. vjs.Button.prototype.onBlur = function(){
  1945. vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress));
  1946. };
  1947. /* Slider
  1948. ================================================================================ */
  1949. /**
  1950. * The base functionality for sliders like the volume bar and seek bar
  1951. *
  1952. * @param {vjs.Player|Object} player
  1953. * @param {Object=} options
  1954. * @constructor
  1955. */
  1956. vjs.Slider = vjs.Component.extend({
  1957. /** @constructor */
  1958. init: function(player, options){
  1959. vjs.Component.call(this, player, options);
  1960. // Set property names to bar and handle to match with the child Slider class is looking for
  1961. this.bar = this.getChild(this.options_['barName']);
  1962. this.handle = this.getChild(this.options_['handleName']);
  1963. player.on(this.playerEvent, vjs.bind(this, this.update));
  1964. this.on('mousedown', this.onMouseDown);
  1965. this.on('touchstart', this.onMouseDown);
  1966. this.on('focus', this.onFocus);
  1967. this.on('blur', this.onBlur);
  1968. this.on('click', this.onClick);
  1969. this.player_.on('controlsvisible', vjs.bind(this, this.update));
  1970. // This is actually to fix the volume handle position. http://twitter.com/#!/gerritvanaaken/status/159046254519787520
  1971. // this.player_.one('timeupdate', vjs.bind(this, this.update));
  1972. player.ready(vjs.bind(this, this.update));
  1973. this.boundEvents = {};
  1974. }
  1975. });
  1976. vjs.Slider.prototype.createEl = function(type, props) {
  1977. props = props || {};
  1978. // Add the slider element class to all sub classes
  1979. props.className = props.className + ' vjs-slider';
  1980. props = vjs.obj.merge({
  1981. role: 'slider',
  1982. 'aria-valuenow': 0,
  1983. 'aria-valuemin': 0,
  1984. 'aria-valuemax': 100,
  1985. tabIndex: 0
  1986. }, props);
  1987. return vjs.Component.prototype.createEl.call(this, type, props);
  1988. };
  1989. vjs.Slider.prototype.onMouseDown = function(event){
  1990. event.preventDefault();
  1991. vjs.blockTextSelection();
  1992. this.boundEvents.move = vjs.bind(this, this.onMouseMove);
  1993. this.boundEvents.end = vjs.bind(this, this.onMouseUp);
  1994. vjs.on(document, 'mousemove', this.boundEvents.move);
  1995. vjs.on(document, 'mouseup', this.boundEvents.end);
  1996. vjs.on(document, 'touchmove', this.boundEvents.move);
  1997. vjs.on(document, 'touchend', this.boundEvents.end);
  1998. this.onMouseMove(event);
  1999. };
  2000. vjs.Slider.prototype.onMouseUp = function() {
  2001. vjs.unblockTextSelection();
  2002. vjs.off(document, 'mousemove', this.boundEvents.move, false);
  2003. vjs.off(document, 'mouseup', this.boundEvents.end, false);
  2004. vjs.off(document, 'touchmove', this.boundEvents.move, false);
  2005. vjs.off(document, 'touchend', this.boundEvents.end, false);
  2006. this.update();
  2007. };
  2008. vjs.Slider.prototype.update = function(){
  2009. // In VolumeBar init we have a setTimeout for update that pops and update to the end of the
  2010. // execution stack. The player is destroyed before then update will cause an error
  2011. if (!this.el_) return;
  2012. // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse.
  2013. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later.
  2014. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration();
  2015. var barProgress,
  2016. progress = this.getPercent(),
  2017. handle = this.handle,
  2018. bar = this.bar;
  2019. // Protect against no duration and other division issues
  2020. if (isNaN(progress)) { progress = 0; }
  2021. barProgress = progress;
  2022. // If there is a handle, we need to account for the handle in our calculation for progress bar
  2023. // so that it doesn't fall short of or extend past the handle.
  2024. if (handle) {
  2025. var box = this.el_,
  2026. boxWidth = box.offsetWidth,
  2027. handleWidth = handle.el().offsetWidth,
  2028. // The width of the handle in percent of the containing box
  2029. // In IE, widths may not be ready yet causing NaN
  2030. handlePercent = (handleWidth) ? handleWidth / boxWidth : 0,
  2031. // Get the adjusted size of the box, considering that the handle's center never touches the left or right side.
  2032. // There is a margin of half the handle's width on both sides.
  2033. boxAdjustedPercent = 1 - handlePercent,
  2034. // Adjust the progress that we'll use to set widths to the new adjusted box width
  2035. adjustedProgress = progress * boxAdjustedPercent;
  2036. // The bar does reach the left side, so we need to account for this in the bar's width
  2037. barProgress = adjustedProgress + (handlePercent / 2);
  2038. // Move the handle from the left based on the adjected progress
  2039. handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%';
  2040. }
  2041. // Set the new bar width
  2042. bar.el().style.width = vjs.round(barProgress * 100, 2) + '%';
  2043. };
  2044. vjs.Slider.prototype.calculateDistance = function(event){
  2045. var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY;
  2046. el = this.el_;
  2047. box = vjs.findPosition(el);
  2048. boxW = boxH = el.offsetWidth;
  2049. handle = this.handle;
  2050. if (this.options_.vertical) {
  2051. boxY = box.top;
  2052. if (event.changedTouches) {
  2053. pageY = event.changedTouches[0].pageY;
  2054. } else {
  2055. pageY = event.pageY;
  2056. }
  2057. if (handle) {
  2058. var handleH = handle.el().offsetHeight;
  2059. // Adjusted X and Width, so handle doesn't go outside the bar
  2060. boxY = boxY + (handleH / 2);
  2061. boxH = boxH - handleH;
  2062. }
  2063. // Percent that the click is through the adjusted area
  2064. return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH));
  2065. } else {
  2066. boxX = box.left;
  2067. if (event.changedTouches) {
  2068. pageX = event.changedTouches[0].pageX;
  2069. } else {
  2070. pageX = event.pageX;
  2071. }
  2072. if (handle) {
  2073. var handleW = handle.el().offsetWidth;
  2074. // Adjusted X and Width, so handle doesn't go outside the bar
  2075. boxX = boxX + (handleW / 2);
  2076. boxW = boxW - handleW;
  2077. }
  2078. // Percent that the click is through the adjusted area
  2079. return Math.max(0, Math.min(1, (pageX - boxX) / boxW));
  2080. }
  2081. };
  2082. vjs.Slider.prototype.onFocus = function(){
  2083. vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress));
  2084. };
  2085. vjs.Slider.prototype.onKeyPress = function(event){
  2086. if (event.which == 37) { // Left Arrow
  2087. event.preventDefault();
  2088. this.stepBack();
  2089. } else if (event.which == 39) { // Right Arrow
  2090. event.preventDefault();
  2091. this.stepForward();
  2092. }
  2093. };
  2094. vjs.Slider.prototype.onBlur = function(){
  2095. vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress));
  2096. };
  2097. /**
  2098. * Listener for click events on slider, used to prevent clicks
  2099. * from bubbling up to parent elements like button menus.
  2100. * @param {Object} event Event object
  2101. */
  2102. vjs.Slider.prototype.onClick = function(event){
  2103. event.stopImmediatePropagation();
  2104. event.preventDefault();
  2105. };
  2106. /**
  2107. * SeekBar Behavior includes play progress bar, and seek handle
  2108. * Needed so it can determine seek position based on handle position/size
  2109. * @param {vjs.Player|Object} player
  2110. * @param {Object=} options
  2111. * @constructor
  2112. */
  2113. vjs.SliderHandle = vjs.Component.extend();
  2114. /**
  2115. * Default value of the slider
  2116. *
  2117. * @type {Number}
  2118. * @private
  2119. */
  2120. vjs.SliderHandle.prototype.defaultValue = 0;
  2121. /** @inheritDoc */
  2122. vjs.SliderHandle.prototype.createEl = function(type, props) {
  2123. props = props || {};
  2124. // Add the slider element class to all sub classes
  2125. props.className = props.className + ' vjs-slider-handle';
  2126. props = vjs.obj.merge({
  2127. innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>'
  2128. }, props);
  2129. return vjs.Component.prototype.createEl.call(this, 'div', props);
  2130. };
  2131. /* Menu
  2132. ================================================================================ */
  2133. /**
  2134. * The Menu component is used to build pop up menus, including subtitle and
  2135. * captions selection menus.
  2136. *
  2137. * @param {vjs.Player|Object} player
  2138. * @param {Object=} options
  2139. * @class
  2140. * @constructor
  2141. */
  2142. vjs.Menu = vjs.Component.extend();
  2143. /**
  2144. * Add a menu item to the menu
  2145. * @param {Object|String} component Component or component type to add
  2146. */
  2147. vjs.Menu.prototype.addItem = function(component){
  2148. this.addChild(component);
  2149. component.on('click', vjs.bind(this, function(){
  2150. this.unlockShowing();
  2151. }));
  2152. };
  2153. /** @inheritDoc */
  2154. vjs.Menu.prototype.createEl = function(){
  2155. var contentElType = this.options().contentElType || 'ul';
  2156. this.contentEl_ = vjs.createEl(contentElType, {
  2157. className: 'vjs-menu-content'
  2158. });
  2159. var el = vjs.Component.prototype.createEl.call(this, 'div', {
  2160. append: this.contentEl_,
  2161. className: 'vjs-menu'
  2162. });
  2163. el.appendChild(this.contentEl_);
  2164. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  2165. // where a click on the parent is significant
  2166. vjs.on(el, 'click', function(event){
  2167. event.preventDefault();
  2168. event.stopImmediatePropagation();
  2169. });
  2170. return el;
  2171. };
  2172. /**
  2173. * The component for a menu item. `<li>`
  2174. *
  2175. * @param {vjs.Player|Object} player
  2176. * @param {Object=} options
  2177. * @class
  2178. * @constructor
  2179. */
  2180. vjs.MenuItem = vjs.Button.extend({
  2181. /** @constructor */
  2182. init: function(player, options){
  2183. vjs.Button.call(this, player, options);
  2184. this.selected(options['selected']);
  2185. }
  2186. });
  2187. /** @inheritDoc */
  2188. vjs.MenuItem.prototype.createEl = function(type, props){
  2189. return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({
  2190. className: 'vjs-menu-item',
  2191. innerHTML: this.options_['label']
  2192. }, props));
  2193. };
  2194. /**
  2195. * Handle a click on the menu item, and set it to selected
  2196. */
  2197. vjs.MenuItem.prototype.onClick = function(){
  2198. this.selected(true);
  2199. };
  2200. /**
  2201. * Set this menu item as selected or not
  2202. * @param {Boolean} selected
  2203. */
  2204. vjs.MenuItem.prototype.selected = function(selected){
  2205. if (selected) {
  2206. this.addClass('vjs-selected');
  2207. this.el_.setAttribute('aria-selected',true);
  2208. } else {
  2209. this.removeClass('vjs-selected');
  2210. this.el_.setAttribute('aria-selected',false);
  2211. }
  2212. };
  2213. /**
  2214. * A button class with a popup menu
  2215. * @param {vjs.Player|Object} player
  2216. * @param {Object=} options
  2217. * @constructor
  2218. */
  2219. vjs.MenuButton = vjs.Button.extend({
  2220. /** @constructor */
  2221. init: function(player, options){
  2222. vjs.Button.call(this, player, options);
  2223. this.menu = this.createMenu();
  2224. // Add list to element
  2225. this.addChild(this.menu);
  2226. // Automatically hide empty menu buttons
  2227. if (this.items && this.items.length === 0) {
  2228. this.hide();
  2229. }
  2230. this.on('keyup', this.onKeyPress);
  2231. this.el_.setAttribute('aria-haspopup', true);
  2232. this.el_.setAttribute('role', 'button');
  2233. }
  2234. });
  2235. /**
  2236. * Track the state of the menu button
  2237. * @type {Boolean}
  2238. * @private
  2239. */
  2240. vjs.MenuButton.prototype.buttonPressed_ = false;
  2241. vjs.MenuButton.prototype.createMenu = function(){
  2242. var menu = new vjs.Menu(this.player_);
  2243. // Add a title list item to the top
  2244. if (this.options().title) {
  2245. menu.el().appendChild(vjs.createEl('li', {
  2246. className: 'vjs-menu-title',
  2247. innerHTML: vjs.capitalize(this.kind_),
  2248. tabindex: -1
  2249. }));
  2250. }
  2251. this.items = this['createItems']();
  2252. if (this.items) {
  2253. // Add menu items to the menu
  2254. for (var i = 0; i < this.items.length; i++) {
  2255. menu.addItem(this.items[i]);
  2256. }
  2257. }
  2258. return menu;
  2259. };
  2260. /**
  2261. * Create the list of menu items. Specific to each subclass.
  2262. */
  2263. vjs.MenuButton.prototype.createItems = function(){};
  2264. /** @inheritDoc */
  2265. vjs.MenuButton.prototype.buildCSSClass = function(){
  2266. return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this);
  2267. };
  2268. // Focus - Add keyboard functionality to element
  2269. // This function is not needed anymore. Instead, the keyboard functionality is handled by
  2270. // treating the button as triggering a submenu. When the button is pressed, the submenu
  2271. // appears. Pressing the button again makes the submenu disappear.
  2272. vjs.MenuButton.prototype.onFocus = function(){};
  2273. // Can't turn off list display that we turned on with focus, because list would go away.
  2274. vjs.MenuButton.prototype.onBlur = function(){};
  2275. vjs.MenuButton.prototype.onClick = function(){
  2276. // When you click the button it adds focus, which will show the menu indefinitely.
  2277. // So we'll remove focus when the mouse leaves the button.
  2278. // Focus is needed for tab navigation.
  2279. this.one('mouseout', vjs.bind(this, function(){
  2280. this.menu.unlockShowing();
  2281. this.el_.blur();
  2282. }));
  2283. if (this.buttonPressed_){
  2284. this.unpressButton();
  2285. } else {
  2286. this.pressButton();
  2287. }
  2288. };
  2289. vjs.MenuButton.prototype.onKeyPress = function(event){
  2290. event.preventDefault();
  2291. // Check for space bar (32) or enter (13) keys
  2292. if (event.which == 32 || event.which == 13) {
  2293. if (this.buttonPressed_){
  2294. this.unpressButton();
  2295. } else {
  2296. this.pressButton();
  2297. }
  2298. // Check for escape (27) key
  2299. } else if (event.which == 27){
  2300. if (this.buttonPressed_){
  2301. this.unpressButton();
  2302. }
  2303. }
  2304. };
  2305. vjs.MenuButton.prototype.pressButton = function(){
  2306. this.buttonPressed_ = true;
  2307. this.menu.lockShowing();
  2308. this.el_.setAttribute('aria-pressed', true);
  2309. if (this.items && this.items.length > 0) {
  2310. this.items[0].el().focus(); // set the focus to the title of the submenu
  2311. }
  2312. };
  2313. vjs.MenuButton.prototype.unpressButton = function(){
  2314. this.buttonPressed_ = false;
  2315. this.menu.unlockShowing();
  2316. this.el_.setAttribute('aria-pressed', false);
  2317. };
  2318. /**
  2319. * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video.
  2320. *
  2321. * ```js
  2322. * var myPlayer = videojs('example_video_1');
  2323. * ```
  2324. *
  2325. * In the follwing example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready.
  2326. *
  2327. * ```html
  2328. * <video id="example_video_1" data-setup='{}' controls>
  2329. * <source src="my-source.mp4" type="video/mp4">
  2330. * </video>
  2331. * ```
  2332. *
  2333. * After an instance has been created it can be accessed globally using `Video('example_video_1')`.
  2334. *
  2335. * @class
  2336. * @extends vjs.Component
  2337. */
  2338. vjs.Player = vjs.Component.extend({
  2339. /**
  2340. * player's constructor function
  2341. *
  2342. * @constructs
  2343. * @method init
  2344. * @param {Element} tag The original video tag used for configuring options
  2345. * @param {Object=} options Player options
  2346. * @param {Function=} ready Ready callback function
  2347. */
  2348. init: function(tag, options, ready){
  2349. this.tag = tag; // Store the original tag used to set options
  2350. // Set Options
  2351. // The options argument overrides options set in the video tag
  2352. // which overrides globally set options.
  2353. // This latter part coincides with the load order
  2354. // (tag must exist before Player)
  2355. options = vjs.obj.merge(this.getTagSettings(tag), options);
  2356. // Cache for video property values.
  2357. this.cache_ = {};
  2358. // Set poster
  2359. this.poster_ = options['poster'];
  2360. // Set controls
  2361. this.controls_ = options['controls'];
  2362. // Original tag settings stored in options
  2363. // now remove immediately so native controls don't flash.
  2364. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  2365. tag.controls = false;
  2366. // Run base component initializing with new options.
  2367. // Builds the element through createEl()
  2368. // Inits and embeds any child components in opts
  2369. vjs.Component.call(this, this, options, ready);
  2370. // Update controls className. Can't do this when the controls are initially
  2371. // set because the element doesn't exist yet.
  2372. if (this.controls()) {
  2373. this.addClass('vjs-controls-enabled');
  2374. } else {
  2375. this.addClass('vjs-controls-disabled');
  2376. }
  2377. // TODO: Make this smarter. Toggle user state between touching/mousing
  2378. // using events, since devices can have both touch and mouse events.
  2379. // if (vjs.TOUCH_ENABLED) {
  2380. // this.addClass('vjs-touch-enabled');
  2381. // }
  2382. // Firstplay event implimentation. Not sold on the event yet.
  2383. // Could probably just check currentTime==0?
  2384. this.one('play', function(e){
  2385. var fpEvent = { type: 'firstplay', target: this.el_ };
  2386. // Using vjs.trigger so we can check if default was prevented
  2387. var keepGoing = vjs.trigger(this.el_, fpEvent);
  2388. if (!keepGoing) {
  2389. e.preventDefault();
  2390. e.stopPropagation();
  2391. e.stopImmediatePropagation();
  2392. }
  2393. });
  2394. this.on('ended', this.onEnded);
  2395. this.on('play', this.onPlay);
  2396. this.on('firstplay', this.onFirstPlay);
  2397. this.on('pause', this.onPause);
  2398. this.on('progress', this.onProgress);
  2399. this.on('durationchange', this.onDurationChange);
  2400. this.on('error', this.onError);
  2401. this.on('fullscreenchange', this.onFullscreenChange);
  2402. // Make player easily findable by ID
  2403. vjs.players[this.id_] = this;
  2404. if (options['plugins']) {
  2405. vjs.obj.each(options['plugins'], function(key, val){
  2406. this[key](val);
  2407. }, this);
  2408. }
  2409. this.listenForUserActivity();
  2410. }
  2411. });
  2412. /**
  2413. * Player instance options, surfaced using vjs.options
  2414. * vjs.options = vjs.Player.prototype.options_
  2415. * Make changes in vjs.options, not here.
  2416. * All options should use string keys so they avoid
  2417. * renaming by closure compiler
  2418. * @type {Object}
  2419. * @private
  2420. */
  2421. vjs.Player.prototype.options_ = vjs.options;
  2422. /**
  2423. * Destroys the video player and does any necessary cleanup
  2424. *
  2425. * myPlayer.dispose();
  2426. *
  2427. * This is especially helpful if you are dynamically adding and removing videos
  2428. * to/from the DOM.
  2429. */
  2430. vjs.Player.prototype.dispose = function(){
  2431. this.trigger('dispose');
  2432. // prevent dispose from being called twice
  2433. this.off('dispose');
  2434. // Kill reference to this player
  2435. vjs.players[this.id_] = null;
  2436. if (this.tag && this.tag['player']) { this.tag['player'] = null; }
  2437. if (this.el_ && this.el_['player']) { this.el_['player'] = null; }
  2438. // Ensure that tracking progress and time progress will stop and plater deleted
  2439. this.stopTrackingProgress();
  2440. this.stopTrackingCurrentTime();
  2441. if (this.tech) { this.tech.dispose(); }
  2442. // Component dispose
  2443. vjs.Component.prototype.dispose.call(this);
  2444. };
  2445. vjs.Player.prototype.getTagSettings = function(tag){
  2446. var options = {
  2447. 'sources': [],
  2448. 'tracks': []
  2449. };
  2450. vjs.obj.merge(options, vjs.getAttributeValues(tag));
  2451. // Get tag children settings
  2452. if (tag.hasChildNodes()) {
  2453. var children, child, childName, i, j;
  2454. children = tag.childNodes;
  2455. for (i=0,j=children.length; i<j; i++) {
  2456. child = children[i];
  2457. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  2458. childName = child.nodeName.toLowerCase();
  2459. if (childName === 'source') {
  2460. options['sources'].push(vjs.getAttributeValues(child));
  2461. } else if (childName === 'track') {
  2462. options['tracks'].push(vjs.getAttributeValues(child));
  2463. }
  2464. }
  2465. }
  2466. return options;
  2467. };
  2468. vjs.Player.prototype.createEl = function(){
  2469. var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div');
  2470. var tag = this.tag;
  2471. // Remove width/height attrs from tag so CSS can make it 100% width/height
  2472. tag.removeAttribute('width');
  2473. tag.removeAttribute('height');
  2474. // Empty video tag tracks so the built-in player doesn't use them also.
  2475. // This may not be fast enough to stop HTML5 browsers from reading the tags
  2476. // so we'll need to turn off any default tracks if we're manually doing
  2477. // captions and subtitles. videoElement.textTracks
  2478. if (tag.hasChildNodes()) {
  2479. var nodes, nodesLength, i, node, nodeName, removeNodes;
  2480. nodes = tag.childNodes;
  2481. nodesLength = nodes.length;
  2482. removeNodes = [];
  2483. while (nodesLength--) {
  2484. node = nodes[nodesLength];
  2485. nodeName = node.nodeName.toLowerCase();
  2486. if (nodeName === 'track') {
  2487. removeNodes.push(node);
  2488. }
  2489. }
  2490. for (i=0; i<removeNodes.length; i++) {
  2491. tag.removeChild(removeNodes[i]);
  2492. }
  2493. }
  2494. // Make sure tag ID exists
  2495. tag.id = tag.id || 'vjs_video_' + vjs.guid++;
  2496. // Give video tag ID and class to player div
  2497. // ID will now reference player box, not the video tag
  2498. el.id = tag.id;
  2499. el.className = tag.className;
  2500. // Update tag id/class for use as HTML5 playback tech
  2501. // Might think we should do this after embedding in container so .vjs-tech class
  2502. // doesn't flash 100% width/height, but class only applies with .video-js parent
  2503. tag.id += '_html5_api';
  2504. tag.className = 'vjs-tech';
  2505. // Make player findable on elements
  2506. tag['player'] = el['player'] = this;
  2507. // Default state of video is paused
  2508. this.addClass('vjs-paused');
  2509. // Make box use width/height of tag, or rely on default implementation
  2510. // Enforce with CSS since width/height attrs don't work on divs
  2511. this.width(this.options_['width'], true); // (true) Skip resize listener on load
  2512. this.height(this.options_['height'], true);
  2513. // Wrap video tag in div (el/box) container
  2514. if (tag.parentNode) {
  2515. tag.parentNode.insertBefore(el, tag);
  2516. }
  2517. vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
  2518. return el;
  2519. };
  2520. // /* Media Technology (tech)
  2521. // ================================================================================ */
  2522. // Load/Create an instance of playback technlogy including element and API methods
  2523. // And append playback element in player div.
  2524. vjs.Player.prototype.loadTech = function(techName, source){
  2525. // Pause and remove current playback technology
  2526. if (this.tech) {
  2527. this.unloadTech();
  2528. // if this is the first time loading, HTML5 tag will exist but won't be initialized
  2529. // so we need to remove it if we're not loading HTML5
  2530. } else if (techName !== 'Html5' && this.tag) {
  2531. vjs.Html5.disposeMediaElement(this.tag);
  2532. this.tag = null;
  2533. }
  2534. this.techName = techName;
  2535. // Turn off API access because we're loading a new tech that might load asynchronously
  2536. this.isReady_ = false;
  2537. var techReady = function(){
  2538. this.player_.triggerReady();
  2539. // Manually track progress in cases where the browser/flash player doesn't report it.
  2540. if (!this.features['progressEvents']) {
  2541. this.player_.manualProgressOn();
  2542. }
  2543. // Manually track timeudpates in cases where the browser/flash player doesn't report it.
  2544. if (!this.features['timeupdateEvents']) {
  2545. this.player_.manualTimeUpdatesOn();
  2546. }
  2547. };
  2548. // Grab tech-specific options from player options and add source and parent element to use.
  2549. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]);
  2550. if (source) {
  2551. if (source.src == this.cache_.src && this.cache_.currentTime > 0) {
  2552. techOptions['startTime'] = this.cache_.currentTime;
  2553. }
  2554. this.cache_.src = source.src;
  2555. }
  2556. // Initialize tech instance
  2557. this.tech = new window['videojs'][techName](this, techOptions);
  2558. this.tech.ready(techReady);
  2559. };
  2560. vjs.Player.prototype.unloadTech = function(){
  2561. this.isReady_ = false;
  2562. this.tech.dispose();
  2563. // Turn off any manual progress or timeupdate tracking
  2564. if (this.manualProgress) { this.manualProgressOff(); }
  2565. if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); }
  2566. this.tech = false;
  2567. };
  2568. // There's many issues around changing the size of a Flash (or other plugin) object.
  2569. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268
  2570. // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen.
  2571. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized.
  2572. // reloadTech: function(betweenFn){
  2573. // vjs.log('unloadingTech')
  2574. // this.unloadTech();
  2575. // vjs.log('unloadedTech')
  2576. // if (betweenFn) { betweenFn.call(); }
  2577. // vjs.log('LoadingTech')
  2578. // this.loadTech(this.techName, { src: this.cache_.src })
  2579. // vjs.log('loadedTech')
  2580. // },
  2581. /* Fallbacks for unsupported event types
  2582. ================================================================================ */
  2583. // Manually trigger progress events based on changes to the buffered amount
  2584. // Many flash players and older HTML5 browsers don't send progress or progress-like events
  2585. vjs.Player.prototype.manualProgressOn = function(){
  2586. this.manualProgress = true;
  2587. // Trigger progress watching when a source begins loading
  2588. this.trackProgress();
  2589. // Watch for a native progress event call on the tech element
  2590. // In HTML5, some older versions don't support the progress event
  2591. // So we're assuming they don't, and turning off manual progress if they do.
  2592. // As opposed to doing user agent detection
  2593. this.tech.one('progress', function(){
  2594. // Update known progress support for this playback technology
  2595. this.features['progressEvents'] = true;
  2596. // Turn off manual progress tracking
  2597. this.player_.manualProgressOff();
  2598. });
  2599. };
  2600. vjs.Player.prototype.manualProgressOff = function(){
  2601. this.manualProgress = false;
  2602. this.stopTrackingProgress();
  2603. };
  2604. vjs.Player.prototype.trackProgress = function(){
  2605. this.progressInterval = setInterval(vjs.bind(this, function(){
  2606. // Don't trigger unless buffered amount is greater than last time
  2607. // log(this.cache_.bufferEnd, this.buffered().end(0), this.duration())
  2608. /* TODO: update for multiple buffered regions */
  2609. if (this.cache_.bufferEnd < this.buffered().end(0)) {
  2610. this.trigger('progress');
  2611. } else if (this.bufferedPercent() == 1) {
  2612. this.stopTrackingProgress();
  2613. this.trigger('progress'); // Last update
  2614. }
  2615. }), 500);
  2616. };
  2617. vjs.Player.prototype.stopTrackingProgress = function(){ clearInterval(this.progressInterval); };
  2618. /*! Time Tracking -------------------------------------------------------------- */
  2619. vjs.Player.prototype.manualTimeUpdatesOn = function(){
  2620. this.manualTimeUpdates = true;
  2621. this.on('play', this.trackCurrentTime);
  2622. this.on('pause', this.stopTrackingCurrentTime);
  2623. // timeupdate is also called by .currentTime whenever current time is set
  2624. // Watch for native timeupdate event
  2625. this.tech.one('timeupdate', function(){
  2626. // Update known progress support for this playback technology
  2627. this.features['timeupdateEvents'] = true;
  2628. // Turn off manual progress tracking
  2629. this.player_.manualTimeUpdatesOff();
  2630. });
  2631. };
  2632. vjs.Player.prototype.manualTimeUpdatesOff = function(){
  2633. this.manualTimeUpdates = false;
  2634. this.stopTrackingCurrentTime();
  2635. this.off('play', this.trackCurrentTime);
  2636. this.off('pause', this.stopTrackingCurrentTime);
  2637. };
  2638. vjs.Player.prototype.trackCurrentTime = function(){
  2639. if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); }
  2640. this.currentTimeInterval = setInterval(vjs.bind(this, function(){
  2641. this.trigger('timeupdate');
  2642. }), 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  2643. };
  2644. // Turn off play progress tracking (when paused or dragging)
  2645. vjs.Player.prototype.stopTrackingCurrentTime = function(){ clearInterval(this.currentTimeInterval); };
  2646. // /* Player event handlers (how the player reacts to certain events)
  2647. // ================================================================================ */
  2648. /**
  2649. * Fired when the user agent begins looking for media data
  2650. * @event loadstart
  2651. */
  2652. vjs.Player.prototype.onLoadStart;
  2653. /**
  2654. * Fired when the player has initial duration and dimension information
  2655. * @event loadedmetadata
  2656. */
  2657. vjs.Player.prototype.onLoadedMetaData;
  2658. /**
  2659. * Fired when the player has downloaded data at the current playback position
  2660. * @event loadeddata
  2661. */
  2662. vjs.Player.prototype.onLoadedData;
  2663. /**
  2664. * Fired when the player has finished downloading the source data
  2665. * @event loadedalldata
  2666. */
  2667. vjs.Player.prototype.onLoadedAllData;
  2668. /**
  2669. * Fired whenever the media begins or resumes playback
  2670. * @event play
  2671. */
  2672. vjs.Player.prototype.onPlay = function(){
  2673. vjs.removeClass(this.el_, 'vjs-paused');
  2674. vjs.addClass(this.el_, 'vjs-playing');
  2675. };
  2676. /**
  2677. * Fired the first time a video is played
  2678. *
  2679. * Not part of the HLS spec, and we're not sure if this is the best
  2680. * implementation yet, so use sparingly. If you don't have a reason to
  2681. * prevent playback, use `myPlayer.one('play');` instead.
  2682. *
  2683. * @event firstplay
  2684. */
  2685. vjs.Player.prototype.onFirstPlay = function(){
  2686. //If the first starttime attribute is specified
  2687. //then we will start at the given offset in seconds
  2688. if(this.options_['starttime']){
  2689. this.currentTime(this.options_['starttime']);
  2690. }
  2691. this.addClass('vjs-has-started');
  2692. };
  2693. /**
  2694. * Fired whenever the media has been paused
  2695. * @event pause
  2696. */
  2697. vjs.Player.prototype.onPause = function(){
  2698. vjs.removeClass(this.el_, 'vjs-playing');
  2699. vjs.addClass(this.el_, 'vjs-paused');
  2700. };
  2701. /**
  2702. * Fired when the current playback position has changed
  2703. *
  2704. * During playback this is fired every 15-250 milliseconds, depnding on the
  2705. * playback technology in use.
  2706. * @event timeupdate
  2707. */
  2708. vjs.Player.prototype.onTimeUpdate;
  2709. /**
  2710. * Fired while the user agent is downloading media data
  2711. * @event progress
  2712. */
  2713. vjs.Player.prototype.onProgress = function(){
  2714. // Add custom event for when source is finished downloading.
  2715. if (this.bufferedPercent() == 1) {
  2716. this.trigger('loadedalldata');
  2717. }
  2718. };
  2719. /**
  2720. * Fired when the end of the media resource is reached (currentTime == duration)
  2721. * @event ended
  2722. */
  2723. vjs.Player.prototype.onEnded = function(){
  2724. if (this.options_['loop']) {
  2725. this.currentTime(0);
  2726. this.play();
  2727. }
  2728. };
  2729. /**
  2730. * Fired when the duration of the media resource is first known or changed
  2731. * @event durationchange
  2732. */
  2733. vjs.Player.prototype.onDurationChange = function(){
  2734. // Allows for cacheing value instead of asking player each time.
  2735. this.duration(this.techGet('duration'));
  2736. };
  2737. /**
  2738. * Fired when the volume changes
  2739. * @event volumechange
  2740. */
  2741. vjs.Player.prototype.onVolumeChange;
  2742. /**
  2743. * Fired when the player switches in or out of fullscreen mode
  2744. * @event fullscreenchange
  2745. */
  2746. vjs.Player.prototype.onFullscreenChange = function() {
  2747. if (this.isFullScreen) {
  2748. this.addClass('vjs-fullscreen');
  2749. } else {
  2750. this.removeClass('vjs-fullscreen');
  2751. }
  2752. };
  2753. /**
  2754. * Fired when there is an error in playback
  2755. * @event error
  2756. */
  2757. vjs.Player.prototype.onError = function(e) {
  2758. vjs.log('Video Error', e);
  2759. };
  2760. // /* Player API
  2761. // ================================================================================ */
  2762. /**
  2763. * Object for cached values.
  2764. * @private
  2765. */
  2766. vjs.Player.prototype.cache_;
  2767. vjs.Player.prototype.getCache = function(){
  2768. return this.cache_;
  2769. };
  2770. // Pass values to the playback tech
  2771. vjs.Player.prototype.techCall = function(method, arg){
  2772. // If it's not ready yet, call method when it is
  2773. if (this.tech && !this.tech.isReady_) {
  2774. this.tech.ready(function(){
  2775. this[method](arg);
  2776. });
  2777. // Otherwise call method now
  2778. } else {
  2779. try {
  2780. this.tech[method](arg);
  2781. } catch(e) {
  2782. vjs.log(e);
  2783. throw e;
  2784. }
  2785. }
  2786. };
  2787. // Get calls can't wait for the tech, and sometimes don't need to.
  2788. vjs.Player.prototype.techGet = function(method){
  2789. if (this.tech && this.tech.isReady_) {
  2790. // Flash likes to die and reload when you hide or reposition it.
  2791. // In these cases the object methods go away and we get errors.
  2792. // When that happens we'll catch the errors and inform tech that it's not ready any more.
  2793. try {
  2794. return this.tech[method]();
  2795. } catch(e) {
  2796. // When building additional tech libs, an expected method may not be defined yet
  2797. if (this.tech[method] === undefined) {
  2798. vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e);
  2799. } else {
  2800. // When a method isn't available on the object it throws a TypeError
  2801. if (e.name == 'TypeError') {
  2802. vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e);
  2803. this.tech.isReady_ = false;
  2804. } else {
  2805. vjs.log(e);
  2806. }
  2807. }
  2808. throw e;
  2809. }
  2810. }
  2811. return;
  2812. };
  2813. /**
  2814. * start media playback
  2815. *
  2816. * myPlayer.play();
  2817. *
  2818. * @return {vjs.Player} self
  2819. */
  2820. vjs.Player.prototype.play = function(){
  2821. this.techCall('play');
  2822. return this;
  2823. };
  2824. /**
  2825. * Pause the video playback
  2826. *
  2827. * myPlayer.pause();
  2828. *
  2829. * @return {vjs.Player} self
  2830. */
  2831. vjs.Player.prototype.pause = function(){
  2832. this.techCall('pause');
  2833. return this;
  2834. };
  2835. /**
  2836. * Check if the player is paused
  2837. *
  2838. * var isPaused = myPlayer.paused();
  2839. * var isPlaying = !myPlayer.paused();
  2840. *
  2841. * @return {Boolean} false if the media is currently playing, or true otherwise
  2842. */
  2843. vjs.Player.prototype.paused = function(){
  2844. // The initial state of paused should be true (in Safari it's actually false)
  2845. return (this.techGet('paused') === false) ? false : true;
  2846. };
  2847. /**
  2848. * Get or set the current time (in seconds)
  2849. *
  2850. * // get
  2851. * var whereYouAt = myPlayer.currentTime();
  2852. *
  2853. * // set
  2854. * myPlayer.currentTime(120); // 2 minutes into the video
  2855. *
  2856. * @param {Number|String=} seconds The time to seek to
  2857. * @return {Number} The time in seconds, when not setting
  2858. * @return {vjs.Player} self, when the current time is set
  2859. */
  2860. vjs.Player.prototype.currentTime = function(seconds){
  2861. if (seconds !== undefined) {
  2862. // cache the last set value for smoother scrubbing
  2863. this.cache_.lastSetCurrentTime = seconds;
  2864. this.techCall('setCurrentTime', seconds);
  2865. // improve the accuracy of manual timeupdates
  2866. if (this.manualTimeUpdates) { this.trigger('timeupdate'); }
  2867. return this;
  2868. }
  2869. // cache last currentTime and return
  2870. // default to 0 seconds
  2871. return this.cache_.currentTime = (this.techGet('currentTime') || 0);
  2872. };
  2873. /**
  2874. * Get the length in time of the video in seconds
  2875. *
  2876. * var lengthOfVideo = myPlayer.duration();
  2877. *
  2878. * **NOTE**: The video must have started loading before the duration can be
  2879. * known, and in the case of Flash, may not be known until the video starts
  2880. * playing.
  2881. *
  2882. * @return {Number} The duration of the video in seconds
  2883. */
  2884. vjs.Player.prototype.duration = function(seconds){
  2885. if (seconds !== undefined) {
  2886. // cache the last set value for optimiized scrubbing (esp. Flash)
  2887. this.cache_.duration = parseFloat(seconds);
  2888. return this;
  2889. }
  2890. if (this.cache_.duration === undefined) {
  2891. this.onDurationChange();
  2892. }
  2893. return this.cache_.duration;
  2894. };
  2895. // Calculates how much time is left. Not in spec, but useful.
  2896. vjs.Player.prototype.remainingTime = function(){
  2897. return this.duration() - this.currentTime();
  2898. };
  2899. // http://dev.w3.org/html5/spec/video.html#dom-media-buffered
  2900. // Buffered returns a timerange object.
  2901. // Kind of like an array of portions of the video that have been downloaded.
  2902. // So far no browsers return more than one range (portion)
  2903. /**
  2904. * Get a TimeRange object with the times of the video that have been downloaded
  2905. *
  2906. * If you just want the percent of the video that's been downloaded,
  2907. * use bufferedPercent.
  2908. *
  2909. * // Number of different ranges of time have been buffered. Usually 1.
  2910. * numberOfRanges = bufferedTimeRange.length,
  2911. *
  2912. * // Time in seconds when the first range starts. Usually 0.
  2913. * firstRangeStart = bufferedTimeRange.start(0),
  2914. *
  2915. * // Time in seconds when the first range ends
  2916. * firstRangeEnd = bufferedTimeRange.end(0),
  2917. *
  2918. * // Length in seconds of the first time range
  2919. * firstRangeLength = firstRangeEnd - firstRangeStart;
  2920. *
  2921. * @return {Object} A mock TimeRange object (following HTML spec)
  2922. */
  2923. vjs.Player.prototype.buffered = function(){
  2924. var buffered = this.techGet('buffered'),
  2925. start = 0,
  2926. buflast = buffered.length - 1,
  2927. // Default end to 0 and store in values
  2928. end = this.cache_.bufferEnd = this.cache_.bufferEnd || 0;
  2929. if (buffered && buflast >= 0 && buffered.end(buflast) !== end) {
  2930. end = buffered.end(buflast);
  2931. // Storing values allows them be overridden by setBufferedFromProgress
  2932. this.cache_.bufferEnd = end;
  2933. }
  2934. return vjs.createTimeRange(start, end);
  2935. };
  2936. /**
  2937. * Get the percent (as a decimal) of the video that's been downloaded
  2938. *
  2939. * var howMuchIsDownloaded = myPlayer.bufferedPercent();
  2940. *
  2941. * 0 means none, 1 means all.
  2942. * (This method isn't in the HTML5 spec, but it's very convenient)
  2943. *
  2944. * @return {Number} A decimal between 0 and 1 representing the percent
  2945. */
  2946. vjs.Player.prototype.bufferedPercent = function(){
  2947. return (this.duration()) ? this.buffered().end(0) / this.duration() : 0;
  2948. };
  2949. /**
  2950. * Get or set the current volume of the media
  2951. *
  2952. * // get
  2953. * var howLoudIsIt = myPlayer.volume();
  2954. *
  2955. * // set
  2956. * myPlayer.volume(0.5); // Set volume to half
  2957. *
  2958. * 0 is off (muted), 1.0 is all the way up, 0.5 is half way.
  2959. *
  2960. * @param {Number} percentAsDecimal The new volume as a decimal percent
  2961. * @return {Number} The current volume, when getting
  2962. * @return {vjs.Player} self, when setting
  2963. */
  2964. vjs.Player.prototype.volume = function(percentAsDecimal){
  2965. var vol;
  2966. if (percentAsDecimal !== undefined) {
  2967. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1
  2968. this.cache_.volume = vol;
  2969. this.techCall('setVolume', vol);
  2970. vjs.setLocalStorage('volume', vol);
  2971. return this;
  2972. }
  2973. // Default to 1 when returning current volume.
  2974. vol = parseFloat(this.techGet('volume'));
  2975. return (isNaN(vol)) ? 1 : vol;
  2976. };
  2977. /**
  2978. * Get the current muted state, or turn mute on or off
  2979. *
  2980. * // get
  2981. * var isVolumeMuted = myPlayer.muted();
  2982. *
  2983. * // set
  2984. * myPlayer.muted(true); // mute the volume
  2985. *
  2986. * @param {Boolean=} muted True to mute, false to unmute
  2987. * @return {Boolean} True if mute is on, false if not, when getting
  2988. * @return {vjs.Player} self, when setting mute
  2989. */
  2990. vjs.Player.prototype.muted = function(muted){
  2991. if (muted !== undefined) {
  2992. this.techCall('setMuted', muted);
  2993. return this;
  2994. }
  2995. return this.techGet('muted') || false; // Default to false
  2996. };
  2997. // Check if current tech can support native fullscreen (e.g. with built in controls lik iOS, so not our flash swf)
  2998. vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; };
  2999. /**
  3000. * Increase the size of the video to full screen
  3001. *
  3002. * myPlayer.requestFullScreen();
  3003. *
  3004. * In some browsers, full screen is not supported natively, so it enters
  3005. * "full window mode", where the video fills the browser window.
  3006. * In browsers and devices that support native full screen, sometimes the
  3007. * browser's default controls will be shown, and not the Video.js custom skin.
  3008. * This includes most mobile devices (iOS, Android) and older versions of
  3009. * Safari.
  3010. *
  3011. * @return {vjs.Player} self
  3012. */
  3013. vjs.Player.prototype.requestFullScreen = function(){
  3014. var requestFullScreen = vjs.support.requestFullScreen;
  3015. this.isFullScreen = true;
  3016. if (requestFullScreen) {
  3017. // the browser supports going fullscreen at the element level so we can
  3018. // take the controls fullscreen as well as the video
  3019. // Trigger fullscreenchange event after change
  3020. // We have to specifically add this each time, and remove
  3021. // when cancelling fullscreen. Otherwise if there's multiple
  3022. // players on a page, they would all be reacting to the same fullscreen
  3023. // events
  3024. vjs.on(document, requestFullScreen.eventName, vjs.bind(this, function(e){
  3025. this.isFullScreen = document[requestFullScreen.isFullScreen];
  3026. // If cancelling fullscreen, remove event listener.
  3027. if (this.isFullScreen === false) {
  3028. vjs.off(document, requestFullScreen.eventName, arguments.callee);
  3029. }
  3030. this.trigger('fullscreenchange');
  3031. }));
  3032. this.el_[requestFullScreen.requestFn]();
  3033. } else if (this.tech.supportsFullScreen()) {
  3034. // we can't take the video.js controls fullscreen but we can go fullscreen
  3035. // with native controls
  3036. this.techCall('enterFullScreen');
  3037. } else {
  3038. // fullscreen isn't supported so we'll just stretch the video element to
  3039. // fill the viewport
  3040. this.enterFullWindow();
  3041. this.trigger('fullscreenchange');
  3042. }
  3043. return this;
  3044. };
  3045. /**
  3046. * Return the video to its normal size after having been in full screen mode
  3047. *
  3048. * myPlayer.cancelFullScreen();
  3049. *
  3050. * @return {vjs.Player} self
  3051. */
  3052. vjs.Player.prototype.cancelFullScreen = function(){
  3053. var requestFullScreen = vjs.support.requestFullScreen;
  3054. this.isFullScreen = false;
  3055. // Check for browser element fullscreen support
  3056. if (requestFullScreen) {
  3057. document[requestFullScreen.cancelFn]();
  3058. } else if (this.tech.supportsFullScreen()) {
  3059. this.techCall('exitFullScreen');
  3060. } else {
  3061. this.exitFullWindow();
  3062. this.trigger('fullscreenchange');
  3063. }
  3064. return this;
  3065. };
  3066. // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
  3067. vjs.Player.prototype.enterFullWindow = function(){
  3068. this.isFullWindow = true;
  3069. // Storing original doc overflow value to return to when fullscreen is off
  3070. this.docOrigOverflow = document.documentElement.style.overflow;
  3071. // Add listener for esc key to exit fullscreen
  3072. vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey));
  3073. // Hide any scroll bars
  3074. document.documentElement.style.overflow = 'hidden';
  3075. // Apply fullscreen styles
  3076. vjs.addClass(document.body, 'vjs-full-window');
  3077. this.trigger('enterFullWindow');
  3078. };
  3079. vjs.Player.prototype.fullWindowOnEscKey = function(event){
  3080. if (event.keyCode === 27) {
  3081. if (this.isFullScreen === true) {
  3082. this.cancelFullScreen();
  3083. } else {
  3084. this.exitFullWindow();
  3085. }
  3086. }
  3087. };
  3088. vjs.Player.prototype.exitFullWindow = function(){
  3089. this.isFullWindow = false;
  3090. vjs.off(document, 'keydown', this.fullWindowOnEscKey);
  3091. // Unhide scroll bars.
  3092. document.documentElement.style.overflow = this.docOrigOverflow;
  3093. // Remove fullscreen styles
  3094. vjs.removeClass(document.body, 'vjs-full-window');
  3095. // Resize the box, controller, and poster to original sizes
  3096. // this.positionAll();
  3097. this.trigger('exitFullWindow');
  3098. };
  3099. vjs.Player.prototype.selectSource = function(sources){
  3100. // Loop through each playback technology in the options order
  3101. for (var i=0,j=this.options_['techOrder'];i<j.length;i++) {
  3102. var techName = vjs.capitalize(j[i]),
  3103. tech = window['videojs'][techName];
  3104. // Check if the browser supports this technology
  3105. if (tech.isSupported()) {
  3106. // Loop through each source object
  3107. for (var a=0,b=sources;a<b.length;a++) {
  3108. var source = b[a];
  3109. // Check if source can be played with this technology
  3110. if (tech['canPlaySource'](source)) {
  3111. return { source: source, tech: techName };
  3112. }
  3113. }
  3114. }
  3115. }
  3116. return false;
  3117. };
  3118. /**
  3119. * The source function updates the video source
  3120. *
  3121. * There are three types of variables you can pass as the argument.
  3122. *
  3123. * **URL String**: A URL to the the video file. Use this method if you are sure
  3124. * the current playback technology (HTML5/Flash) can support the source you
  3125. * provide. Currently only MP4 files can be used in both HTML5 and Flash.
  3126. *
  3127. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  3128. *
  3129. * **Source Object (or element):** A javascript object containing information
  3130. * about the source file. Use this method if you want the player to determine if
  3131. * it can support the file using the type information.
  3132. *
  3133. * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });
  3134. *
  3135. * **Array of Source Objects:** To provide multiple versions of the source so
  3136. * that it can be played using HTML5 across browsers you can use an array of
  3137. * source objects. Video.js will detect which version is supported and load that
  3138. * file.
  3139. *
  3140. * myPlayer.src([
  3141. * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
  3142. * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
  3143. * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
  3144. * ]);
  3145. *
  3146. * @param {String|Object|Array=} source The source URL, object, or array of sources
  3147. * @return {vjs.Player} self
  3148. */
  3149. vjs.Player.prototype.src = function(source){
  3150. // Case: Array of source objects to choose from and pick the best to play
  3151. if (source instanceof Array) {
  3152. var sourceTech = this.selectSource(source),
  3153. techName;
  3154. if (sourceTech) {
  3155. source = sourceTech.source;
  3156. techName = sourceTech.tech;
  3157. // If this technology is already loaded, set source
  3158. if (techName == this.techName) {
  3159. this.src(source); // Passing the source object
  3160. // Otherwise load this technology with chosen source
  3161. } else {
  3162. this.loadTech(techName, source);
  3163. }
  3164. } else {
  3165. this.el_.appendChild(vjs.createEl('p', {
  3166. innerHTML: this.options()['notSupportedMessage']
  3167. }));
  3168. }
  3169. // Case: Source object { src: '', type: '' ... }
  3170. } else if (source instanceof Object) {
  3171. if (window['videojs'][this.techName]['canPlaySource'](source)) {
  3172. this.src(source.src);
  3173. } else {
  3174. // Send through tech loop to check for a compatible technology.
  3175. this.src([source]);
  3176. }
  3177. // Case: URL String (http://myvideo...)
  3178. } else {
  3179. // Cache for getting last set source
  3180. this.cache_.src = source;
  3181. if (!this.isReady_) {
  3182. this.ready(function(){
  3183. this.src(source);
  3184. });
  3185. } else {
  3186. this.techCall('src', source);
  3187. if (this.options_['preload'] == 'auto') {
  3188. this.load();
  3189. }
  3190. if (this.options_['autoplay']) {
  3191. this.play();
  3192. }
  3193. }
  3194. }
  3195. return this;
  3196. };
  3197. // Begin loading the src data
  3198. // http://dev.w3.org/html5/spec/video.html#dom-media-load
  3199. vjs.Player.prototype.load = function(){
  3200. this.techCall('load');
  3201. return this;
  3202. };
  3203. // http://dev.w3.org/html5/spec/video.html#dom-media-currentsrc
  3204. vjs.Player.prototype.currentSrc = function(){
  3205. return this.techGet('currentSrc') || this.cache_.src || '';
  3206. };
  3207. // Attributes/Options
  3208. vjs.Player.prototype.preload = function(value){
  3209. if (value !== undefined) {
  3210. this.techCall('setPreload', value);
  3211. this.options_['preload'] = value;
  3212. return this;
  3213. }
  3214. return this.techGet('preload');
  3215. };
  3216. vjs.Player.prototype.autoplay = function(value){
  3217. if (value !== undefined) {
  3218. this.techCall('setAutoplay', value);
  3219. this.options_['autoplay'] = value;
  3220. return this;
  3221. }
  3222. return this.techGet('autoplay', value);
  3223. };
  3224. vjs.Player.prototype.loop = function(value){
  3225. if (value !== undefined) {
  3226. this.techCall('setLoop', value);
  3227. this.options_['loop'] = value;
  3228. return this;
  3229. }
  3230. return this.techGet('loop');
  3231. };
  3232. /**
  3233. * the url of the poster image source
  3234. * @type {String}
  3235. * @private
  3236. */
  3237. vjs.Player.prototype.poster_;
  3238. /**
  3239. * get or set the poster image source url
  3240. *
  3241. * ##### EXAMPLE:
  3242. *
  3243. * // getting
  3244. * var currentPoster = myPlayer.poster();
  3245. *
  3246. * // setting
  3247. * myPlayer.poster('http://example.com/myImage.jpg');
  3248. *
  3249. * @param {String=} [src] Poster image source URL
  3250. * @return {String} poster URL when getting
  3251. * @return {vjs.Player} self when setting
  3252. */
  3253. vjs.Player.prototype.poster = function(src){
  3254. if (src !== undefined) {
  3255. this.poster_ = src;
  3256. return this;
  3257. }
  3258. return this.poster_;
  3259. };
  3260. /**
  3261. * Whether or not the controls are showing
  3262. * @type {Boolean}
  3263. * @private
  3264. */
  3265. vjs.Player.prototype.controls_;
  3266. /**
  3267. * Get or set whether or not the controls are showing.
  3268. * @param {Boolean} controls Set controls to showing or not
  3269. * @return {Boolean} Controls are showing
  3270. */
  3271. vjs.Player.prototype.controls = function(bool){
  3272. if (bool !== undefined) {
  3273. bool = !!bool; // force boolean
  3274. // Don't trigger a change event unless it actually changed
  3275. if (this.controls_ !== bool) {
  3276. this.controls_ = bool;
  3277. if (bool) {
  3278. this.removeClass('vjs-controls-disabled');
  3279. this.addClass('vjs-controls-enabled');
  3280. this.trigger('controlsenabled');
  3281. } else {
  3282. this.removeClass('vjs-controls-enabled');
  3283. this.addClass('vjs-controls-disabled');
  3284. this.trigger('controlsdisabled');
  3285. }
  3286. }
  3287. return this;
  3288. }
  3289. return this.controls_;
  3290. };
  3291. vjs.Player.prototype.usingNativeControls_;
  3292. /**
  3293. * Toggle native controls on/off. Native controls are the controls built into
  3294. * devices (e.g. default iPhone controls), Flash, or other techs
  3295. * (e.g. Vimeo Controls)
  3296. *
  3297. * **This should only be set by the current tech, because only the tech knows
  3298. * if it can support native controls**
  3299. *
  3300. * @param {Boolean} bool True signals that native controls are on
  3301. * @return {vjs.Player} Returns the player
  3302. * @private
  3303. */
  3304. vjs.Player.prototype.usingNativeControls = function(bool){
  3305. if (bool !== undefined) {
  3306. bool = !!bool; // force boolean
  3307. // Don't trigger a change event unless it actually changed
  3308. if (this.usingNativeControls_ !== bool) {
  3309. this.usingNativeControls_ = bool;
  3310. if (bool) {
  3311. this.addClass('vjs-using-native-controls');
  3312. /**
  3313. * player is using the native device controls
  3314. *
  3315. * @event usingnativecontrols
  3316. * @memberof vjs.Player
  3317. * @instance
  3318. * @private
  3319. */
  3320. this.trigger('usingnativecontrols');
  3321. } else {
  3322. this.removeClass('vjs-using-native-controls');
  3323. /**
  3324. * player is using the custom HTML controls
  3325. *
  3326. * @event usingcustomcontrols
  3327. * @memberof vjs.Player
  3328. * @instance
  3329. * @private
  3330. */
  3331. this.trigger('usingcustomcontrols');
  3332. }
  3333. }
  3334. return this;
  3335. }
  3336. return this.usingNativeControls_;
  3337. };
  3338. vjs.Player.prototype.error = function(){ return this.techGet('error'); };
  3339. vjs.Player.prototype.ended = function(){ return this.techGet('ended'); };
  3340. vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); };
  3341. // When the player is first initialized, trigger activity so components
  3342. // like the control bar show themselves if needed
  3343. vjs.Player.prototype.userActivity_ = true;
  3344. vjs.Player.prototype.reportUserActivity = function(event){
  3345. this.userActivity_ = true;
  3346. };
  3347. vjs.Player.prototype.userActive_ = true;
  3348. vjs.Player.prototype.userActive = function(bool){
  3349. if (bool !== undefined) {
  3350. bool = !!bool;
  3351. if (bool !== this.userActive_) {
  3352. this.userActive_ = bool;
  3353. if (bool) {
  3354. // If the user was inactive and is now active we want to reset the
  3355. // inactivity timer
  3356. this.userActivity_ = true;
  3357. this.removeClass('vjs-user-inactive');
  3358. this.addClass('vjs-user-active');
  3359. this.trigger('useractive');
  3360. } else {
  3361. // We're switching the state to inactive manually, so erase any other
  3362. // activity
  3363. this.userActivity_ = false;
  3364. // Chrome/Safari/IE have bugs where when you change the cursor it can
  3365. // trigger a mousemove event. This causes an issue when you're hiding
  3366. // the cursor when the user is inactive, and a mousemove signals user
  3367. // activity. Making it impossible to go into inactive mode. Specifically
  3368. // this happens in fullscreen when we really need to hide the cursor.
  3369. //
  3370. // When this gets resolved in ALL browsers it can be removed
  3371. // https://code.google.com/p/chromium/issues/detail?id=103041
  3372. this.tech.one('mousemove', function(e){
  3373. e.stopPropagation();
  3374. e.preventDefault();
  3375. });
  3376. this.removeClass('vjs-user-active');
  3377. this.addClass('vjs-user-inactive');
  3378. this.trigger('userinactive');
  3379. }
  3380. }
  3381. return this;
  3382. }
  3383. return this.userActive_;
  3384. };
  3385. vjs.Player.prototype.listenForUserActivity = function(){
  3386. var onMouseActivity, onMouseDown, mouseInProgress, onMouseUp,
  3387. activityCheck, inactivityTimeout;
  3388. onMouseActivity = this.reportUserActivity;
  3389. onMouseDown = function() {
  3390. onMouseActivity();
  3391. // For as long as the they are touching the device or have their mouse down,
  3392. // we consider them active even if they're not moving their finger or mouse.
  3393. // So we want to continue to update that they are active
  3394. clearInterval(mouseInProgress);
  3395. // Setting userActivity=true now and setting the interval to the same time
  3396. // as the activityCheck interval (250) should ensure we never miss the
  3397. // next activityCheck
  3398. mouseInProgress = setInterval(vjs.bind(this, onMouseActivity), 250);
  3399. };
  3400. onMouseUp = function(event) {
  3401. onMouseActivity();
  3402. // Stop the interval that maintains activity if the mouse/touch is down
  3403. clearInterval(mouseInProgress);
  3404. };
  3405. // Any mouse movement will be considered user activity
  3406. this.on('mousedown', onMouseDown);
  3407. this.on('mousemove', onMouseActivity);
  3408. this.on('mouseup', onMouseUp);
  3409. // Listen for keyboard navigation
  3410. // Shouldn't need to use inProgress interval because of key repeat
  3411. this.on('keydown', onMouseActivity);
  3412. this.on('keyup', onMouseActivity);
  3413. // Consider any touch events that bubble up to be activity
  3414. // Certain touches on the tech will be blocked from bubbling because they
  3415. // toggle controls
  3416. this.on('touchstart', onMouseDown);
  3417. this.on('touchmove', onMouseActivity);
  3418. this.on('touchend', onMouseUp);
  3419. this.on('touchcancel', onMouseUp);
  3420. // Run an interval every 250 milliseconds instead of stuffing everything into
  3421. // the mousemove/touchmove function itself, to prevent performance degradation.
  3422. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  3423. // then gets picked up by this loop
  3424. // http://ejohn.org/blog/learning-from-twitter/
  3425. activityCheck = setInterval(vjs.bind(this, function() {
  3426. // Check to see if mouse/touch activity has happened
  3427. if (this.userActivity_) {
  3428. // Reset the activity tracker
  3429. this.userActivity_ = false;
  3430. // If the user state was inactive, set the state to active
  3431. this.userActive(true);
  3432. // Clear any existing inactivity timeout to start the timer over
  3433. clearTimeout(inactivityTimeout);
  3434. // In X seconds, if no more activity has occurred the user will be
  3435. // considered inactive
  3436. inactivityTimeout = setTimeout(vjs.bind(this, function() {
  3437. // Protect against the case where the inactivityTimeout can trigger just
  3438. // before the next user activity is picked up by the activityCheck loop
  3439. // causing a flicker
  3440. if (!this.userActivity_) {
  3441. this.userActive(false);
  3442. }
  3443. }), 2000);
  3444. }
  3445. }), 250);
  3446. // Clean up the intervals when we kill the player
  3447. this.on('dispose', function(){
  3448. clearInterval(activityCheck);
  3449. clearTimeout(inactivityTimeout);
  3450. });
  3451. };
  3452. // Methods to add support for
  3453. // networkState: function(){ return this.techCall('networkState'); },
  3454. // readyState: function(){ return this.techCall('readyState'); },
  3455. // seeking: function(){ return this.techCall('seeking'); },
  3456. // initialTime: function(){ return this.techCall('initialTime'); },
  3457. // startOffsetTime: function(){ return this.techCall('startOffsetTime'); },
  3458. // played: function(){ return this.techCall('played'); },
  3459. // seekable: function(){ return this.techCall('seekable'); },
  3460. // videoTracks: function(){ return this.techCall('videoTracks'); },
  3461. // audioTracks: function(){ return this.techCall('audioTracks'); },
  3462. // videoWidth: function(){ return this.techCall('videoWidth'); },
  3463. // videoHeight: function(){ return this.techCall('videoHeight'); },
  3464. // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); },
  3465. // playbackRate: function(){ return this.techCall('playbackRate'); },
  3466. // mediaGroup: function(){ return this.techCall('mediaGroup'); },
  3467. // controller: function(){ return this.techCall('controller'); },
  3468. // defaultMuted: function(){ return this.techCall('defaultMuted'); }
  3469. // TODO
  3470. // currentSrcList: the array of sources including other formats and bitrates
  3471. // playList: array of source lists in order of playback
  3472. // RequestFullscreen API
  3473. (function(){
  3474. var prefix, requestFS, div;
  3475. div = document.createElement('div');
  3476. requestFS = {};
  3477. // Current W3C Spec
  3478. // http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api
  3479. // Mozilla Draft: https://wiki.mozilla.org/Gecko:FullScreenAPI#fullscreenchange_event
  3480. // New: https://dvcs.w3.org/hg/fullscreen/raw-file/529a67b8d9f3/Overview.html
  3481. if (div.cancelFullscreen !== undefined) {
  3482. requestFS.requestFn = 'requestFullscreen';
  3483. requestFS.cancelFn = 'exitFullscreen';
  3484. requestFS.eventName = 'fullscreenchange';
  3485. requestFS.isFullScreen = 'fullScreen';
  3486. // Webkit (Chrome/Safari) and Mozilla (Firefox) have working implementations
  3487. // that use prefixes and vary slightly from the new W3C spec. Specifically,
  3488. // using 'exit' instead of 'cancel', and lowercasing the 'S' in Fullscreen.
  3489. // Other browsers don't have any hints of which version they might follow yet,
  3490. // so not going to try to predict by looping through all prefixes.
  3491. } else {
  3492. if (document.mozCancelFullScreen) {
  3493. prefix = 'moz';
  3494. requestFS.isFullScreen = prefix + 'FullScreen';
  3495. } else {
  3496. prefix = 'webkit';
  3497. requestFS.isFullScreen = prefix + 'IsFullScreen';
  3498. }
  3499. if (div[prefix + 'RequestFullScreen']) {
  3500. requestFS.requestFn = prefix + 'RequestFullScreen';
  3501. requestFS.cancelFn = prefix + 'CancelFullScreen';
  3502. }
  3503. requestFS.eventName = prefix + 'fullscreenchange';
  3504. }
  3505. if (document[requestFS.cancelFn]) {
  3506. vjs.support.requestFullScreen = requestFS;
  3507. }
  3508. })();
  3509. /**
  3510. * Container of main controls
  3511. * @param {vjs.Player|Object} player
  3512. * @param {Object=} options
  3513. * @class
  3514. * @constructor
  3515. * @extends vjs.Component
  3516. */
  3517. vjs.ControlBar = vjs.Component.extend();
  3518. vjs.ControlBar.prototype.options_ = {
  3519. loadEvent: 'play',
  3520. children: {
  3521. 'playToggle': {},
  3522. 'currentTimeDisplay': {},
  3523. 'timeDivider': {},
  3524. 'durationDisplay': {},
  3525. 'remainingTimeDisplay': {},
  3526. 'progressControl': {},
  3527. 'fullscreenToggle': {},
  3528. 'volumeControl': {},
  3529. 'muteToggle': {}
  3530. // 'volumeMenuButton': {}
  3531. }
  3532. };
  3533. vjs.ControlBar.prototype.createEl = function(){
  3534. return vjs.createEl('div', {
  3535. className: 'vjs-control-bar'
  3536. });
  3537. };
  3538. /**
  3539. * Button to toggle between play and pause
  3540. * @param {vjs.Player|Object} player
  3541. * @param {Object=} options
  3542. * @class
  3543. * @constructor
  3544. */
  3545. vjs.PlayToggle = vjs.Button.extend({
  3546. /** @constructor */
  3547. init: function(player, options){
  3548. vjs.Button.call(this, player, options);
  3549. player.on('play', vjs.bind(this, this.onPlay));
  3550. player.on('pause', vjs.bind(this, this.onPause));
  3551. }
  3552. });
  3553. vjs.PlayToggle.prototype.buttonText = 'Play';
  3554. vjs.PlayToggle.prototype.buildCSSClass = function(){
  3555. return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this);
  3556. };
  3557. // OnClick - Toggle between play and pause
  3558. vjs.PlayToggle.prototype.onClick = function(){
  3559. if (this.player_.paused()) {
  3560. this.player_.play();
  3561. } else {
  3562. this.player_.pause();
  3563. }
  3564. };
  3565. // OnPlay - Add the vjs-playing class to the element so it can change appearance
  3566. vjs.PlayToggle.prototype.onPlay = function(){
  3567. vjs.removeClass(this.el_, 'vjs-paused');
  3568. vjs.addClass(this.el_, 'vjs-playing');
  3569. this.el_.children[0].children[0].innerHTML = 'Pause'; // change the button text to "Pause"
  3570. };
  3571. // OnPause - Add the vjs-paused class to the element so it can change appearance
  3572. vjs.PlayToggle.prototype.onPause = function(){
  3573. vjs.removeClass(this.el_, 'vjs-playing');
  3574. vjs.addClass(this.el_, 'vjs-paused');
  3575. this.el_.children[0].children[0].innerHTML = 'Play'; // change the button text to "Play"
  3576. };
  3577. /**
  3578. * Displays the current time
  3579. * @param {vjs.Player|Object} player
  3580. * @param {Object=} options
  3581. * @constructor
  3582. */
  3583. vjs.CurrentTimeDisplay = vjs.Component.extend({
  3584. /** @constructor */
  3585. init: function(player, options){
  3586. vjs.Component.call(this, player, options);
  3587. player.on('timeupdate', vjs.bind(this, this.updateContent));
  3588. }
  3589. });
  3590. vjs.CurrentTimeDisplay.prototype.createEl = function(){
  3591. var el = vjs.Component.prototype.createEl.call(this, 'div', {
  3592. className: 'vjs-current-time vjs-time-controls vjs-control'
  3593. });
  3594. this.content = vjs.createEl('div', {
  3595. className: 'vjs-current-time-display',
  3596. innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users
  3597. 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
  3598. });
  3599. el.appendChild(vjs.createEl('div').appendChild(this.content));
  3600. return el;
  3601. };
  3602. vjs.CurrentTimeDisplay.prototype.updateContent = function(){
  3603. // Allows for smooth scrubbing, when player can't keep up.
  3604. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
  3605. this.content.innerHTML = '<span class="vjs-control-text">Current Time </span>' + vjs.formatTime(time, this.player_.duration());
  3606. };
  3607. /**
  3608. * Displays the duration
  3609. * @param {vjs.Player|Object} player
  3610. * @param {Object=} options
  3611. * @constructor
  3612. */
  3613. vjs.DurationDisplay = vjs.Component.extend({
  3614. /** @constructor */
  3615. init: function(player, options){
  3616. vjs.Component.call(this, player, options);
  3617. player.on('timeupdate', vjs.bind(this, this.updateContent)); // this might need to be changes to 'durationchange' instead of 'timeupdate' eventually, however the durationchange event fires before this.player_.duration() is set, so the value cannot be written out using this method. Once the order of durationchange and this.player_.duration() being set is figured out, this can be updated.
  3618. }
  3619. });
  3620. vjs.DurationDisplay.prototype.createEl = function(){
  3621. var el = vjs.Component.prototype.createEl.call(this, 'div', {
  3622. className: 'vjs-duration vjs-time-controls vjs-control'
  3623. });
  3624. this.content = vjs.createEl('div', {
  3625. className: 'vjs-duration-display',
  3626. innerHTML: '<span class="vjs-control-text">Duration Time </span>' + '0:00', // label the duration time for screen reader users
  3627. 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
  3628. });
  3629. el.appendChild(vjs.createEl('div').appendChild(this.content));
  3630. return el;
  3631. };
  3632. vjs.DurationDisplay.prototype.updateContent = function(){
  3633. var duration = this.player_.duration();
  3634. if (duration) {
  3635. this.content.innerHTML = '<span class="vjs-control-text">Duration Time </span>' + vjs.formatTime(duration); // label the duration time for screen reader users
  3636. }
  3637. };
  3638. /**
  3639. * The separator between the current time and duration
  3640. *
  3641. * Can be hidden if it's not needed in the design.
  3642. *
  3643. * @param {vjs.Player|Object} player
  3644. * @param {Object=} options
  3645. * @constructor
  3646. */
  3647. vjs.TimeDivider = vjs.Component.extend({
  3648. /** @constructor */
  3649. init: function(player, options){
  3650. vjs.Component.call(this, player, options);
  3651. }
  3652. });
  3653. vjs.TimeDivider.prototype.createEl = function(){
  3654. return vjs.Component.prototype.createEl.call(this, 'div', {
  3655. className: 'vjs-time-divider',
  3656. innerHTML: '<div><span>/</span></div>'
  3657. });
  3658. };
  3659. /**
  3660. * Displays the time left in the video
  3661. * @param {vjs.Player|Object} player
  3662. * @param {Object=} options
  3663. * @constructor
  3664. */
  3665. vjs.RemainingTimeDisplay = vjs.Component.extend({
  3666. /** @constructor */
  3667. init: function(player, options){
  3668. vjs.Component.call(this, player, options);
  3669. player.on('timeupdate', vjs.bind(this, this.updateContent));
  3670. }
  3671. });
  3672. vjs.RemainingTimeDisplay.prototype.createEl = function(){
  3673. var el = vjs.Component.prototype.createEl.call(this, 'div', {
  3674. className: 'vjs-remaining-time vjs-time-controls vjs-control'
  3675. });
  3676. this.content = vjs.createEl('div', {
  3677. className: 'vjs-remaining-time-display',
  3678. innerHTML: '<span class="vjs-control-text">Remaining Time </span>' + '-0:00', // label the remaining time for screen reader users
  3679. 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes
  3680. });
  3681. el.appendChild(vjs.createEl('div').appendChild(this.content));
  3682. return el;
  3683. };
  3684. vjs.RemainingTimeDisplay.prototype.updateContent = function(){
  3685. if (this.player_.duration()) {
  3686. this.content.innerHTML = '<span class="vjs-control-text">Remaining Time </span>' + '-'+ vjs.formatTime(this.player_.remainingTime());
  3687. }
  3688. // Allows for smooth scrubbing, when player can't keep up.
  3689. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
  3690. // this.content.innerHTML = vjs.formatTime(time, this.player_.duration());
  3691. };
  3692. /**
  3693. * Toggle fullscreen video
  3694. * @param {vjs.Player|Object} player
  3695. * @param {Object=} options
  3696. * @class
  3697. * @extends vjs.Button
  3698. */
  3699. vjs.FullscreenToggle = vjs.Button.extend({
  3700. /**
  3701. * @constructor
  3702. * @memberof vjs.FullscreenToggle
  3703. * @instance
  3704. */
  3705. init: function(player, options){
  3706. vjs.Button.call(this, player, options);
  3707. }
  3708. });
  3709. vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen';
  3710. vjs.FullscreenToggle.prototype.buildCSSClass = function(){
  3711. return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this);
  3712. };
  3713. vjs.FullscreenToggle.prototype.onClick = function(){
  3714. if (!this.player_.isFullScreen) {
  3715. this.player_.requestFullScreen();
  3716. this.el_.children[0].children[0].innerHTML = 'Non-Fullscreen'; // change the button text to "Non-Fullscreen"
  3717. } else {
  3718. this.player_.cancelFullScreen();
  3719. this.el_.children[0].children[0].innerHTML = 'Fullscreen'; // change the button to "Fullscreen"
  3720. }
  3721. };
  3722. /**
  3723. * The Progress Control component contains the seek bar, load progress,
  3724. * and play progress
  3725. *
  3726. * @param {vjs.Player|Object} player
  3727. * @param {Object=} options
  3728. * @constructor
  3729. */
  3730. vjs.ProgressControl = vjs.Component.extend({
  3731. /** @constructor */
  3732. init: function(player, options){
  3733. vjs.Component.call(this, player, options);
  3734. }
  3735. });
  3736. vjs.ProgressControl.prototype.options_ = {
  3737. children: {
  3738. 'seekBar': {}
  3739. }
  3740. };
  3741. vjs.ProgressControl.prototype.createEl = function(){
  3742. return vjs.Component.prototype.createEl.call(this, 'div', {
  3743. className: 'vjs-progress-control vjs-control'
  3744. });
  3745. };
  3746. /**
  3747. * Seek Bar and holder for the progress bars
  3748. *
  3749. * @param {vjs.Player|Object} player
  3750. * @param {Object=} options
  3751. * @constructor
  3752. */
  3753. vjs.SeekBar = vjs.Slider.extend({
  3754. /** @constructor */
  3755. init: function(player, options){
  3756. vjs.Slider.call(this, player, options);
  3757. player.on('timeupdate', vjs.bind(this, this.updateARIAAttributes));
  3758. player.ready(vjs.bind(this, this.updateARIAAttributes));
  3759. }
  3760. });
  3761. vjs.SeekBar.prototype.options_ = {
  3762. children: {
  3763. 'loadProgressBar': {},
  3764. 'playProgressBar': {},
  3765. 'seekHandle': {}
  3766. },
  3767. 'barName': 'playProgressBar',
  3768. 'handleName': 'seekHandle'
  3769. };
  3770. vjs.SeekBar.prototype.playerEvent = 'timeupdate';
  3771. vjs.SeekBar.prototype.createEl = function(){
  3772. return vjs.Slider.prototype.createEl.call(this, 'div', {
  3773. className: 'vjs-progress-holder',
  3774. 'aria-label': 'video progress bar'
  3775. });
  3776. };
  3777. vjs.SeekBar.prototype.updateARIAAttributes = function(){
  3778. // Allows for smooth scrubbing, when player can't keep up.
  3779. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime();
  3780. this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete)
  3781. this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete)
  3782. };
  3783. vjs.SeekBar.prototype.getPercent = function(){
  3784. var currentTime;
  3785. // Flash RTMP provider will not report the correct time
  3786. // immediately after a seek. This isn't noticeable if you're
  3787. // seeking while the video is playing, but it is if you seek
  3788. // while the video is paused.
  3789. if (this.player_.techName === 'Flash' && this.player_.seeking()) {
  3790. var cache = this.player_.getCache();
  3791. if (cache.lastSetCurrentTime) {
  3792. currentTime = cache.lastSetCurrentTime;
  3793. }
  3794. else {
  3795. currentTime = this.player_.currentTime();
  3796. }
  3797. }
  3798. else {
  3799. currentTime = this.player_.currentTime();
  3800. }
  3801. return currentTime / this.player_.duration();
  3802. };
  3803. vjs.SeekBar.prototype.onMouseDown = function(event){
  3804. vjs.Slider.prototype.onMouseDown.call(this, event);
  3805. this.player_.scrubbing = true;
  3806. this.videoWasPlaying = !this.player_.paused();
  3807. this.player_.pause();
  3808. };
  3809. vjs.SeekBar.prototype.onMouseMove = function(event){
  3810. var newTime = this.calculateDistance(event) * this.player_.duration();
  3811. // Don't let video end while scrubbing.
  3812. if (newTime == this.player_.duration()) { newTime = newTime - 0.1; }
  3813. // Set new time (tell player to seek to new time)
  3814. this.player_.currentTime(newTime);
  3815. };
  3816. vjs.SeekBar.prototype.onMouseUp = function(event){
  3817. vjs.Slider.prototype.onMouseUp.call(this, event);
  3818. this.player_.scrubbing = false;
  3819. if (this.videoWasPlaying) {
  3820. debugger
  3821. this.player_.play();
  3822. }
  3823. };
  3824. vjs.SeekBar.prototype.stepForward = function(){
  3825. this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
  3826. };
  3827. vjs.SeekBar.prototype.stepBack = function(){
  3828. this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
  3829. };
  3830. /**
  3831. * Shows load progress
  3832. *
  3833. * @param {vjs.Player|Object} player
  3834. * @param {Object=} options
  3835. * @constructor
  3836. */
  3837. vjs.LoadProgressBar = vjs.Component.extend({
  3838. /** @constructor */
  3839. init: function(player, options){
  3840. vjs.Component.call(this, player, options);
  3841. player.on('progress', vjs.bind(this, this.update));
  3842. }
  3843. });
  3844. vjs.LoadProgressBar.prototype.createEl = function(){
  3845. return vjs.Component.prototype.createEl.call(this, 'div', {
  3846. className: 'vjs-load-progress',
  3847. innerHTML: '<span class="vjs-control-text">Loaded: 0%</span>'
  3848. });
  3849. };
  3850. vjs.LoadProgressBar.prototype.update = function(){
  3851. if (this.el_.style) { this.el_.style.width = vjs.round(this.player_.bufferedPercent() * 100, 2) + '%'; }
  3852. };
  3853. /**
  3854. * Shows play progress
  3855. *
  3856. * @param {vjs.Player|Object} player
  3857. * @param {Object=} options
  3858. * @constructor
  3859. */
  3860. vjs.PlayProgressBar = vjs.Component.extend({
  3861. /** @constructor */
  3862. init: function(player, options){
  3863. vjs.Component.call(this, player, options);
  3864. }
  3865. });
  3866. vjs.PlayProgressBar.prototype.createEl = function(){
  3867. return vjs.Component.prototype.createEl.call(this, 'div', {
  3868. className: 'vjs-play-progress',
  3869. innerHTML: '<span class="vjs-control-text">Progress: 0%</span>'
  3870. });
  3871. };
  3872. /**
  3873. * The Seek Handle shows the current position of the playhead during playback,
  3874. * and can be dragged to adjust the playhead.
  3875. *
  3876. * @param {vjs.Player|Object} player
  3877. * @param {Object=} options
  3878. * @constructor
  3879. */
  3880. vjs.SeekHandle = vjs.SliderHandle.extend();
  3881. /**
  3882. * The default value for the handle content, which may be read by screen readers
  3883. *
  3884. * @type {String}
  3885. * @private
  3886. */
  3887. vjs.SeekHandle.prototype.defaultValue = '00:00';
  3888. /** @inheritDoc */
  3889. vjs.SeekHandle.prototype.createEl = function(){
  3890. return vjs.SliderHandle.prototype.createEl.call(this, 'div', {
  3891. className: 'vjs-seek-handle'
  3892. });
  3893. };
  3894. /**
  3895. * The component for controlling the volume level
  3896. *
  3897. * @param {vjs.Player|Object} player
  3898. * @param {Object=} options
  3899. * @constructor
  3900. */
  3901. vjs.VolumeControl = vjs.Component.extend({
  3902. /** @constructor */
  3903. init: function(player, options){
  3904. vjs.Component.call(this, player, options);
  3905. // hide volume controls when they're not supported by the current tech
  3906. if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) {
  3907. this.addClass('vjs-hidden');
  3908. }
  3909. player.on('loadstart', vjs.bind(this, function(){
  3910. if (player.tech.features && player.tech.features['volumeControl'] === false) {
  3911. this.addClass('vjs-hidden');
  3912. } else {
  3913. this.removeClass('vjs-hidden');
  3914. }
  3915. }));
  3916. }
  3917. });
  3918. vjs.VolumeControl.prototype.options_ = {
  3919. children: {
  3920. 'volumeBar': {}
  3921. }
  3922. };
  3923. vjs.VolumeControl.prototype.createEl = function(){
  3924. return vjs.Component.prototype.createEl.call(this, 'div', {
  3925. className: 'vjs-volume-control vjs-control'
  3926. });
  3927. };
  3928. /**
  3929. * The bar that contains the volume level and can be clicked on to adjust the level
  3930. *
  3931. * @param {vjs.Player|Object} player
  3932. * @param {Object=} options
  3933. * @constructor
  3934. */
  3935. vjs.VolumeBar = vjs.Slider.extend({
  3936. /** @constructor */
  3937. init: function(player, options){
  3938. vjs.Slider.call(this, player, options);
  3939. player.on('volumechange', vjs.bind(this, this.updateARIAAttributes));
  3940. player.ready(vjs.bind(this, this.updateARIAAttributes));
  3941. setTimeout(vjs.bind(this, this.update), 0); // update when elements is in DOM
  3942. }
  3943. });
  3944. vjs.VolumeBar.prototype.updateARIAAttributes = function(){
  3945. // Current value of volume bar as a percentage
  3946. this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2));
  3947. this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%');
  3948. };
  3949. vjs.VolumeBar.prototype.options_ = {
  3950. children: {
  3951. 'volumeLevel': {},
  3952. 'volumeHandle': {}
  3953. },
  3954. 'barName': 'volumeLevel',
  3955. 'handleName': 'volumeHandle'
  3956. };
  3957. vjs.VolumeBar.prototype.playerEvent = 'volumechange';
  3958. vjs.VolumeBar.prototype.createEl = function(){
  3959. return vjs.Slider.prototype.createEl.call(this, 'div', {
  3960. className: 'vjs-volume-bar',
  3961. 'aria-label': 'volume level'
  3962. });
  3963. };
  3964. vjs.VolumeBar.prototype.onMouseMove = function(event) {
  3965. if (this.player_.muted()) {
  3966. this.player_.muted(false);
  3967. }
  3968. this.player_.volume(this.calculateDistance(event));
  3969. };
  3970. vjs.VolumeBar.prototype.getPercent = function(){
  3971. if (this.player_.muted()) {
  3972. return 0;
  3973. } else {
  3974. return this.player_.volume();
  3975. }
  3976. };
  3977. vjs.VolumeBar.prototype.stepForward = function(){
  3978. this.player_.volume(this.player_.volume() + 0.1);
  3979. };
  3980. vjs.VolumeBar.prototype.stepBack = function(){
  3981. this.player_.volume(this.player_.volume() - 0.1);
  3982. };
  3983. /**
  3984. * Shows volume level
  3985. *
  3986. * @param {vjs.Player|Object} player
  3987. * @param {Object=} options
  3988. * @constructor
  3989. */
  3990. vjs.VolumeLevel = vjs.Component.extend({
  3991. /** @constructor */
  3992. init: function(player, options){
  3993. vjs.Component.call(this, player, options);
  3994. }
  3995. });
  3996. vjs.VolumeLevel.prototype.createEl = function(){
  3997. return vjs.Component.prototype.createEl.call(this, 'div', {
  3998. className: 'vjs-volume-level',
  3999. innerHTML: '<span class="vjs-control-text"></span>'
  4000. });
  4001. };
  4002. /**
  4003. * The volume handle can be dragged to adjust the volume level
  4004. *
  4005. * @param {vjs.Player|Object} player
  4006. * @param {Object=} options
  4007. * @constructor
  4008. */
  4009. vjs.VolumeHandle = vjs.SliderHandle.extend();
  4010. vjs.VolumeHandle.prototype.defaultValue = '00:00';
  4011. /** @inheritDoc */
  4012. vjs.VolumeHandle.prototype.createEl = function(){
  4013. return vjs.SliderHandle.prototype.createEl.call(this, 'div', {
  4014. className: 'vjs-volume-handle'
  4015. });
  4016. };
  4017. /**
  4018. * A button component for muting the audio
  4019. *
  4020. * @param {vjs.Player|Object} player
  4021. * @param {Object=} options
  4022. * @constructor
  4023. */
  4024. vjs.MuteToggle = vjs.Button.extend({
  4025. /** @constructor */
  4026. init: function(player, options){
  4027. vjs.Button.call(this, player, options);
  4028. player.on('volumechange', vjs.bind(this, this.update));
  4029. // hide mute toggle if the current tech doesn't support volume control
  4030. if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) {
  4031. this.addClass('vjs-hidden');
  4032. }
  4033. player.on('loadstart', vjs.bind(this, function(){
  4034. if (player.tech.features && player.tech.features['volumeControl'] === false) {
  4035. this.addClass('vjs-hidden');
  4036. } else {
  4037. this.removeClass('vjs-hidden');
  4038. }
  4039. }));
  4040. }
  4041. });
  4042. vjs.MuteToggle.prototype.createEl = function(){
  4043. return vjs.Button.prototype.createEl.call(this, 'div', {
  4044. className: 'vjs-mute-control vjs-control',
  4045. innerHTML: '<div><span class="vjs-control-text">Mute</span></div>'
  4046. });
  4047. };
  4048. vjs.MuteToggle.prototype.onClick = function(){
  4049. this.player_.muted( this.player_.muted() ? false : true );
  4050. };
  4051. vjs.MuteToggle.prototype.update = function(){
  4052. var vol = this.player_.volume(),
  4053. level = 3;
  4054. if (vol === 0 || this.player_.muted()) {
  4055. level = 0;
  4056. } else if (vol < 0.33) {
  4057. level = 1;
  4058. } else if (vol < 0.67) {
  4059. level = 2;
  4060. }
  4061. // Don't rewrite the button text if the actual text doesn't change.
  4062. // This causes unnecessary and confusing information for screen reader users.
  4063. // This check is needed because this function gets called every time the volume level is changed.
  4064. if(this.player_.muted()){
  4065. if(this.el_.children[0].children[0].innerHTML!='Unmute'){
  4066. this.el_.children[0].children[0].innerHTML = 'Unmute'; // change the button text to "Unmute"
  4067. }
  4068. } else {
  4069. if(this.el_.children[0].children[0].innerHTML!='Mute'){
  4070. this.el_.children[0].children[0].innerHTML = 'Mute'; // change the button text to "Mute"
  4071. }
  4072. }
  4073. /* TODO improve muted icon classes */
  4074. for (var i = 0; i < 4; i++) {
  4075. vjs.removeClass(this.el_, 'vjs-vol-'+i);
  4076. }
  4077. vjs.addClass(this.el_, 'vjs-vol-'+level);
  4078. };
  4079. /**
  4080. * Menu button with a popup for showing the volume slider.
  4081. * @constructor
  4082. */
  4083. vjs.VolumeMenuButton = vjs.MenuButton.extend({
  4084. /** @constructor */
  4085. init: function(player, options){
  4086. vjs.MenuButton.call(this, player, options);
  4087. // Same listeners as MuteToggle
  4088. player.on('volumechange', vjs.bind(this, this.update));
  4089. // hide mute toggle if the current tech doesn't support volume control
  4090. if (player.tech && player.tech.features && player.tech.features.volumeControl === false) {
  4091. this.addClass('vjs-hidden');
  4092. }
  4093. player.on('loadstart', vjs.bind(this, function(){
  4094. if (player.tech.features && player.tech.features.volumeControl === false) {
  4095. this.addClass('vjs-hidden');
  4096. } else {
  4097. this.removeClass('vjs-hidden');
  4098. }
  4099. }));
  4100. this.addClass('vjs-menu-button');
  4101. }
  4102. });
  4103. vjs.VolumeMenuButton.prototype.createMenu = function(){
  4104. var menu = new vjs.Menu(this.player_, {
  4105. contentElType: 'div'
  4106. });
  4107. var vc = new vjs.VolumeBar(this.player_, vjs.obj.merge({vertical: true}, this.options_.volumeBar));
  4108. menu.addChild(vc);
  4109. return menu;
  4110. };
  4111. vjs.VolumeMenuButton.prototype.onClick = function(){
  4112. vjs.MuteToggle.prototype.onClick.call(this);
  4113. vjs.MenuButton.prototype.onClick.call(this);
  4114. };
  4115. vjs.VolumeMenuButton.prototype.createEl = function(){
  4116. return vjs.Button.prototype.createEl.call(this, 'div', {
  4117. className: 'vjs-volume-menu-button vjs-menu-button vjs-control',
  4118. innerHTML: '<div><span class="vjs-control-text">Mute</span></div>'
  4119. });
  4120. };
  4121. vjs.VolumeMenuButton.prototype.update = vjs.MuteToggle.prototype.update;
  4122. /* Poster Image
  4123. ================================================================================ */
  4124. /**
  4125. * The component that handles showing the poster image.
  4126. *
  4127. * @param {vjs.Player|Object} player
  4128. * @param {Object=} options
  4129. * @constructor
  4130. */
  4131. vjs.PosterImage = vjs.Button.extend({
  4132. /** @constructor */
  4133. init: function(player, options){
  4134. vjs.Button.call(this, player, options);
  4135. if (!player.poster() || !player.controls()) {
  4136. this.hide();
  4137. }
  4138. player.on('play', vjs.bind(this, this.hide));
  4139. }
  4140. });
  4141. vjs.PosterImage.prototype.createEl = function(){
  4142. var el = vjs.createEl('div', {
  4143. className: 'vjs-poster',
  4144. // Don't want poster to be tabbable.
  4145. tabIndex: -1
  4146. }),
  4147. poster = this.player_.poster();
  4148. if (poster) {
  4149. if ('backgroundSize' in el.style) {
  4150. el.style.backgroundImage = 'url("' + poster + '")';
  4151. } else {
  4152. el.appendChild(vjs.createEl('img', { src: poster }));
  4153. }
  4154. }
  4155. return el;
  4156. };
  4157. vjs.PosterImage.prototype.onClick = function(){
  4158. // Only accept clicks when controls are enabled
  4159. if (this.player().controls()) {
  4160. this.player_.play();
  4161. }
  4162. };
  4163. /* Loading Spinner
  4164. ================================================================================ */
  4165. /**
  4166. * Loading spinner for waiting events
  4167. * @param {vjs.Player|Object} player
  4168. * @param {Object=} options
  4169. * @class
  4170. * @constructor
  4171. */
  4172. vjs.LoadingSpinner = vjs.Component.extend({
  4173. /** @constructor */
  4174. init: function(player, options){
  4175. vjs.Component.call(this, player, options);
  4176. player.on('canplay', vjs.bind(this, this.hide));
  4177. player.on('canplaythrough', vjs.bind(this, this.hide));
  4178. player.on('playing', vjs.bind(this, this.hide));
  4179. player.on('seeked', vjs.bind(this, this.hide));
  4180. player.on('seeking', vjs.bind(this, this.show));
  4181. // in some browsers seeking does not trigger the 'playing' event,
  4182. // so we also need to trap 'seeked' if we are going to set a
  4183. // 'seeking' event
  4184. player.on('seeked', vjs.bind(this, this.hide));
  4185. player.on('error', vjs.bind(this, this.show));
  4186. // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner.
  4187. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing
  4188. // player.on('stalled', vjs.bind(this, this.show));
  4189. player.on('waiting', vjs.bind(this, this.show));
  4190. }
  4191. });
  4192. vjs.LoadingSpinner.prototype.createEl = function(){
  4193. return vjs.Component.prototype.createEl.call(this, 'div', {
  4194. className: 'vjs-loading-spinner'
  4195. });
  4196. };
  4197. /* Big Play Button
  4198. ================================================================================ */
  4199. /**
  4200. * Initial play button. Shows before the video has played. The hiding of the
  4201. * big play button is done via CSS and player states.
  4202. * @param {vjs.Player|Object} player
  4203. * @param {Object=} options
  4204. * @class
  4205. * @constructor
  4206. */
  4207. vjs.BigPlayButton = vjs.Button.extend();
  4208. vjs.BigPlayButton.prototype.createEl = function(){
  4209. return vjs.Button.prototype.createEl.call(this, 'div', {
  4210. className: 'vjs-big-play-button',
  4211. innerHTML: '<span aria-hidden="true"></span>',
  4212. 'aria-label': 'play video'
  4213. });
  4214. };
  4215. vjs.BigPlayButton.prototype.onClick = function(){
  4216. this.player_.play();
  4217. };
  4218. /**
  4219. * @fileoverview Media Technology Controller - Base class for media playback
  4220. * technology controllers like Flash and HTML5
  4221. */
  4222. /**
  4223. * Base class for media (HTML5 Video, Flash) controllers
  4224. * @param {vjs.Player|Object} player Central player instance
  4225. * @param {Object=} options Options object
  4226. * @constructor
  4227. */
  4228. vjs.MediaTechController = vjs.Component.extend({
  4229. /** @constructor */
  4230. init: function(player, options, ready){
  4231. vjs.Component.call(this, player, options, ready);
  4232. this.initControlsListeners();
  4233. }
  4234. });
  4235. /**
  4236. * Set up click and touch listeners for the playback element
  4237. * On desktops, a click on the video itself will toggle playback,
  4238. * on a mobile device a click on the video toggles controls.
  4239. * (toggling controls is done by toggling the user state between active and
  4240. * inactive)
  4241. *
  4242. * A tap can signal that a user has become active, or has become inactive
  4243. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  4244. * quick tap should hide them again (signaling the user is in an inactive
  4245. * viewing state)
  4246. *
  4247. * In addition to this, we still want the user to be considered inactive after
  4248. * a few seconds of inactivity.
  4249. *
  4250. * Note: the only part of iOS interaction we can't mimic with this setup
  4251. * is a touch and hold on the video element counting as activity in order to
  4252. * keep the controls showing, but that shouldn't be an issue. A touch and hold on
  4253. * any controls will still keep the user active
  4254. */
  4255. vjs.MediaTechController.prototype.initControlsListeners = function(){
  4256. var player, tech, activateControls, deactivateControls;
  4257. tech = this;
  4258. player = this.player();
  4259. var activateControls = function(){
  4260. if (player.controls() && !player.usingNativeControls()) {
  4261. tech.addControlsListeners();
  4262. }
  4263. };
  4264. deactivateControls = vjs.bind(tech, tech.removeControlsListeners);
  4265. // Set up event listeners once the tech is ready and has an element to apply
  4266. // listeners to
  4267. this.ready(activateControls);
  4268. player.on('controlsenabled', activateControls);
  4269. player.on('controlsdisabled', deactivateControls);
  4270. };
  4271. vjs.MediaTechController.prototype.addControlsListeners = function(){
  4272. var preventBubble, userWasActive;
  4273. // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
  4274. // trigger mousedown/up.
  4275. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
  4276. // Any touch events are set to block the mousedown event from happening
  4277. this.on('mousedown', this.onClick);
  4278. // We need to block touch events on the video element from bubbling up,
  4279. // otherwise they'll signal activity prematurely. The specific use case is
  4280. // when the video is playing and the controls have faded out. In this case
  4281. // only a tap (fast touch) should toggle the user active state and turn the
  4282. // controls back on. A touch and move or touch and hold should not trigger
  4283. // the controls (per iOS as an example at least)
  4284. //
  4285. // We always want to stop propagation on touchstart because touchstart
  4286. // at the player level starts the touchInProgress interval. We can still
  4287. // report activity on the other events, but won't let them bubble for
  4288. // consistency. We don't want to bubble a touchend without a touchstart.
  4289. this.on('touchstart', function(event) {
  4290. // Stop the mouse events from also happening
  4291. event.preventDefault();
  4292. event.stopPropagation();
  4293. // Record if the user was active now so we don't have to keep polling it
  4294. userWasActive = this.player_.userActive();
  4295. });
  4296. preventBubble = function(event){
  4297. event.stopPropagation();
  4298. if (userWasActive) {
  4299. this.player_.reportUserActivity();
  4300. }
  4301. };
  4302. // Treat all touch events the same for consistency
  4303. this.on('touchmove', preventBubble);
  4304. this.on('touchleave', preventBubble);
  4305. this.on('touchcancel', preventBubble);
  4306. this.on('touchend', preventBubble);
  4307. // Turn on component tap events
  4308. this.emitTapEvents();
  4309. // The tap listener needs to come after the touchend listener because the tap
  4310. // listener cancels out any reportedUserActivity when setting userActive(false)
  4311. this.on('tap', this.onTap);
  4312. };
  4313. /**
  4314. * Remove the listeners used for click and tap controls. This is needed for
  4315. * toggling to controls disabled, where a tap/touch should do nothing.
  4316. */
  4317. vjs.MediaTechController.prototype.removeControlsListeners = function(){
  4318. // We don't want to just use `this.off()` because there might be other needed
  4319. // listeners added by techs that extend this.
  4320. this.off('tap');
  4321. this.off('touchstart');
  4322. this.off('touchmove');
  4323. this.off('touchleave');
  4324. this.off('touchcancel');
  4325. this.off('touchend');
  4326. this.off('click');
  4327. this.off('mousedown');
  4328. };
  4329. /**
  4330. * Handle a click on the media element. By default will play/pause the media.
  4331. */
  4332. vjs.MediaTechController.prototype.onClick = function(event){
  4333. // We're using mousedown to detect clicks thanks to Flash, but mousedown
  4334. // will also be triggered with right-clicks, so we need to prevent that
  4335. if (event.button !== 0) return;
  4336. // When controls are disabled a click should not toggle playback because
  4337. // the click is considered a control
  4338. if (this.player().controls()) {
  4339. if (this.player().paused()) {
  4340. this.player().play();
  4341. } else {
  4342. this.player().pause();
  4343. }
  4344. }
  4345. };
  4346. /**
  4347. * Handle a tap on the media element. By default it will toggle the user
  4348. * activity state, which hides and shows the controls.
  4349. */
  4350. vjs.MediaTechController.prototype.onTap = function(){
  4351. this.player().userActive(!this.player().userActive());
  4352. };
  4353. vjs.MediaTechController.prototype.features = {
  4354. 'volumeControl': true,
  4355. // Resizing plugins using request fullscreen reloads the plugin
  4356. 'fullscreenResize': false,
  4357. // Optional events that we can manually mimic with timers
  4358. // currently not triggered by video-js-swf
  4359. 'progressEvents': false,
  4360. 'timeupdateEvents': false
  4361. };
  4362. vjs.media = {};
  4363. /**
  4364. * List of default API methods for any MediaTechController
  4365. * @type {String}
  4366. */
  4367. vjs.media.ApiMethods = 'play,pause,paused,currentTime,setCurrentTime,duration,buffered,volume,setVolume,muted,setMuted,width,height,supportsFullScreen,enterFullScreen,src,load,currentSrc,preload,setPreload,autoplay,setAutoplay,loop,setLoop,error,networkState,readyState,seeking,initialTime,startOffsetTime,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks,defaultPlaybackRate,playbackRate,mediaGroup,controller,controls,defaultMuted'.split(',');
  4368. // Create placeholder methods for each that warn when a method isn't supported by the current playback technology
  4369. function createMethod(methodName){
  4370. return function(){
  4371. throw new Error('The "'+methodName+'" method is not available on the playback technology\'s API');
  4372. };
  4373. }
  4374. for (var i = vjs.media.ApiMethods.length - 1; i >= 0; i--) {
  4375. var methodName = vjs.media.ApiMethods[i];
  4376. vjs.MediaTechController.prototype[vjs.media.ApiMethods[i]] = createMethod(methodName);
  4377. }
  4378. /**
  4379. * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API
  4380. */
  4381. /**
  4382. * HTML5 Media Controller - Wrapper for HTML5 Media API
  4383. * @param {vjs.Player|Object} player
  4384. * @param {Object=} options
  4385. * @param {Function=} ready
  4386. * @constructor
  4387. */
  4388. vjs.Html5 = vjs.MediaTechController.extend({
  4389. /** @constructor */
  4390. init: function(player, options, ready){
  4391. // volume cannot be changed from 1 on iOS
  4392. this.features['volumeControl'] = vjs.Html5.canControlVolume();
  4393. // In iOS, if you move a video element in the DOM, it breaks video playback.
  4394. this.features['movingMediaElementInDOM'] = !vjs.IS_IOS;
  4395. // HTML video is able to automatically resize when going to fullscreen
  4396. this.features['fullscreenResize'] = true;
  4397. vjs.MediaTechController.call(this, player, options, ready);
  4398. var source = options['source'];
  4399. // If the element source is already set, we may have missed the loadstart event, and want to trigger it.
  4400. // We don't want to set the source again and interrupt playback.
  4401. if (source && this.el_.currentSrc === source.src && this.el_.networkState > 0) {
  4402. player.trigger('loadstart');
  4403. // Otherwise set the source if one was provided.
  4404. } else if (source) {
  4405. this.el_.src = source.src;
  4406. }
  4407. // Determine if native controls should be used
  4408. // Our goal should be to get the custom controls on mobile solid everywhere
  4409. // so we can remove this all together. Right now this will block custom
  4410. // controls on touch enabled laptops like the Chrome Pixel
  4411. if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] !== false) {
  4412. this.useNativeControls();
  4413. }
  4414. // Chrome and Safari both have issues with autoplay.
  4415. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work.
  4416. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays)
  4417. // This fixes both issues. Need to wait for API, so it updates displays correctly
  4418. player.ready(function(){
  4419. if (this.tag && this.options_['autoplay'] && this.paused()) {
  4420. delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16.
  4421. this.play();
  4422. }
  4423. });
  4424. this.setupTriggers();
  4425. this.triggerReady();
  4426. }
  4427. });
  4428. vjs.Html5.prototype.dispose = function(){
  4429. vjs.MediaTechController.prototype.dispose.call(this);
  4430. };
  4431. vjs.Html5.prototype.createEl = function(){
  4432. var player = this.player_,
  4433. // If possible, reuse original tag for HTML5 playback technology element
  4434. el = player.tag,
  4435. newEl,
  4436. clone;
  4437. // Check if this browser supports moving the element into the box.
  4438. // On the iPhone video will break if you move the element,
  4439. // So we have to create a brand new element.
  4440. if (!el || this.features['movingMediaElementInDOM'] === false) {
  4441. // If the original tag is still there, clone and remove it.
  4442. if (el) {
  4443. clone = el.cloneNode(false);
  4444. vjs.Html5.disposeMediaElement(el);
  4445. el = clone;
  4446. player.tag = null;
  4447. } else {
  4448. el = vjs.createEl('video', {
  4449. id:player.id() + '_html5_api',
  4450. className:'vjs-tech'
  4451. });
  4452. }
  4453. // associate the player with the new tag
  4454. el['player'] = player;
  4455. vjs.insertFirst(el, player.el());
  4456. }
  4457. // Update specific tag settings, in case they were overridden
  4458. var attrs = ['autoplay','preload','loop','muted'];
  4459. for (var i = attrs.length - 1; i >= 0; i--) {
  4460. var attr = attrs[i];
  4461. if (player.options_[attr] !== null) {
  4462. el[attr] = player.options_[attr];
  4463. }
  4464. }
  4465. return el;
  4466. // jenniisawesome = true;
  4467. };
  4468. // Make video events trigger player events
  4469. // May seem verbose here, but makes other APIs possible.
  4470. vjs.Html5.prototype.setupTriggers = function(){
  4471. for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) {
  4472. vjs.on(this.el_, vjs.Html5.Events[i], vjs.bind(this.player_, this.eventHandler));
  4473. }
  4474. };
  4475. // Triggers removed using this.off when disposed
  4476. vjs.Html5.prototype.eventHandler = function(e){
  4477. this.trigger(e);
  4478. // No need for media events to bubble up.
  4479. e.stopPropagation();
  4480. };
  4481. vjs.Html5.prototype.useNativeControls = function(){
  4482. var tech, player, controlsOn, controlsOff, cleanUp;
  4483. tech = this;
  4484. player = this.player();
  4485. // If the player controls are enabled turn on the native controls
  4486. tech.setControls(player.controls());
  4487. // Update the native controls when player controls state is updated
  4488. controlsOn = function(){
  4489. tech.setControls(true);
  4490. };
  4491. controlsOff = function(){
  4492. tech.setControls(false);
  4493. };
  4494. player.on('controlsenabled', controlsOn);
  4495. player.on('controlsdisabled', controlsOff);
  4496. // Clean up when not using native controls anymore
  4497. cleanUp = function(){
  4498. player.off('controlsenabled', controlsOn);
  4499. player.off('controlsdisabled', controlsOff);
  4500. };
  4501. tech.on('dispose', cleanUp);
  4502. player.on('usingcustomcontrols', cleanUp);
  4503. // Update the state of the player to using native controls
  4504. player.usingNativeControls(true);
  4505. };
  4506. vjs.Html5.prototype.play = function(){ this.el_.play(); };
  4507. vjs.Html5.prototype.pause = function(){ this.el_.pause(); };
  4508. vjs.Html5.prototype.paused = function(){ return this.el_.paused; };
  4509. vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; };
  4510. vjs.Html5.prototype.setCurrentTime = function(seconds){
  4511. try {
  4512. this.el_.currentTime = seconds;
  4513. } catch(e) {
  4514. vjs.log(e, 'Video is not ready. (Video.js)');
  4515. // this.warning(VideoJS.warnings.videoNotReady);
  4516. }
  4517. };
  4518. vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; };
  4519. vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; };
  4520. vjs.Html5.prototype.volume = function(){ return this.el_.volume; };
  4521. vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; };
  4522. vjs.Html5.prototype.muted = function(){ return this.el_.muted; };
  4523. vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; };
  4524. vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; };
  4525. vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; };
  4526. vjs.Html5.prototype.supportsFullScreen = function(){
  4527. if (typeof this.el_.webkitEnterFullScreen == 'function') {
  4528. // Seems to be broken in Chromium/Chrome && Safari in Leopard
  4529. if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) {
  4530. return true;
  4531. }
  4532. }
  4533. return false;
  4534. };
  4535. vjs.Html5.prototype.enterFullScreen = function(){
  4536. var video = this.el_;
  4537. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  4538. // attempt to prime the video element for programmatic access
  4539. // this isn't necessary on the desktop but shouldn't hurt
  4540. this.el_.play();
  4541. // playing and pausing synchronously during the transition to fullscreen
  4542. // can get iOS ~6.1 devices into a play/pause loop
  4543. setTimeout(function(){
  4544. video.pause();
  4545. video.webkitEnterFullScreen();
  4546. }, 0);
  4547. } else {
  4548. video.webkitEnterFullScreen();
  4549. }
  4550. };
  4551. vjs.Html5.prototype.exitFullScreen = function(){
  4552. this.el_.webkitExitFullScreen();
  4553. };
  4554. vjs.Html5.prototype.src = function(src){ this.el_.src = src; };
  4555. vjs.Html5.prototype.load = function(){ this.el_.load(); };
  4556. vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; };
  4557. vjs.Html5.prototype.preload = function(){ return this.el_.preload; };
  4558. vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; };
  4559. vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; };
  4560. vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; };
  4561. vjs.Html5.prototype.controls = function(){ return this.el_.controls; }
  4562. vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; }
  4563. vjs.Html5.prototype.loop = function(){ return this.el_.loop; };
  4564. vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; };
  4565. vjs.Html5.prototype.error = function(){ return this.el_.error; };
  4566. vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; };
  4567. vjs.Html5.prototype.ended = function(){ return this.el_.ended; };
  4568. vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; };
  4569. /* HTML5 Support Testing ---------------------------------------------------- */
  4570. vjs.Html5.isSupported = function(){
  4571. return !!vjs.TEST_VID.canPlayType;
  4572. };
  4573. vjs.Html5.canPlaySource = function(srcObj){
  4574. // IE9 on Windows 7 without MediaPlayer throws an error here
  4575. // https://github.com/videojs/video.js/issues/519
  4576. try {
  4577. return !!vjs.TEST_VID.canPlayType(srcObj.type);
  4578. } catch(e) {
  4579. return '';
  4580. }
  4581. // TODO: Check Type
  4582. // If no Type, check ext
  4583. // Check Media Type
  4584. };
  4585. vjs.Html5.canControlVolume = function(){
  4586. var volume = vjs.TEST_VID.volume;
  4587. vjs.TEST_VID.volume = (volume / 2) + 0.1;
  4588. return volume !== vjs.TEST_VID.volume;
  4589. };
  4590. // List of all HTML5 events (various uses).
  4591. vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(',');
  4592. vjs.Html5.disposeMediaElement = function(el){
  4593. if (!el) { return; }
  4594. el['player'] = null;
  4595. if (el.parentNode) {
  4596. el.parentNode.removeChild(el);
  4597. }
  4598. // remove any child track or source nodes to prevent their loading
  4599. while(el.hasChildNodes()) {
  4600. el.removeChild(el.firstChild);
  4601. }
  4602. // remove any src reference. not setting `src=''` because that causes a warning
  4603. // in firefox
  4604. el.removeAttribute('src');
  4605. // force the media element to update its loading state by calling load()
  4606. if (typeof el.load === 'function') {
  4607. el.load();
  4608. }
  4609. };
  4610. // HTML5 Feature detection and Device Fixes --------------------------------- //
  4611. // Override Android 2.2 and less canPlayType method which is broken
  4612. if (vjs.IS_OLD_ANDROID) {
  4613. document.createElement('video').constructor.prototype.canPlayType = function(type){
  4614. return (type && type.toLowerCase().indexOf('video/mp4') != -1) ? 'maybe' : '';
  4615. };
  4616. }
  4617. /**
  4618. * @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API
  4619. * https://github.com/zencoder/video-js-swf
  4620. * Not using setupTriggers. Using global onEvent func to distribute events
  4621. */
  4622. /**
  4623. * Flash Media Controller - Wrapper for fallback SWF API
  4624. *
  4625. * @param {vjs.Player} player
  4626. * @param {Object=} options
  4627. * @param {Function=} ready
  4628. * @constructor
  4629. */
  4630. vjs.Flash = vjs.MediaTechController.extend({
  4631. /** @constructor */
  4632. init: function(player, options, ready){
  4633. vjs.MediaTechController.call(this, player, options, ready);
  4634. var source = options['source'],
  4635. // Which element to embed in
  4636. parentEl = options['parentEl'],
  4637. // Create a temporary element to be replaced by swf object
  4638. placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }),
  4639. // Generate ID for swf object
  4640. objId = player.id()+'_flash_api',
  4641. // Store player options in local var for optimization
  4642. // TODO: switch to using player methods instead of options
  4643. // e.g. player.autoplay();
  4644. playerOptions = player.options_,
  4645. // Merge default flashvars with ones passed in to init
  4646. flashVars = vjs.obj.merge({
  4647. // SWF Callback Functions
  4648. 'readyFunction': 'videojs.Flash.onReady',
  4649. 'eventProxyFunction': 'videojs.Flash.onEvent',
  4650. 'errorEventProxyFunction': 'videojs.Flash.onError',
  4651. // Player Settings
  4652. 'autoplay': playerOptions.autoplay,
  4653. 'preload': playerOptions.preload,
  4654. 'loop': playerOptions.loop,
  4655. 'muted': playerOptions.muted
  4656. }, options['flashVars']),
  4657. // Merge default parames with ones passed in
  4658. params = vjs.obj.merge({
  4659. 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance
  4660. 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading
  4661. }, options['params']),
  4662. // Merge default attributes with ones passed in
  4663. attributes = vjs.obj.merge({
  4664. 'id': objId,
  4665. 'name': objId, // Both ID and Name needed or swf to identifty itself
  4666. 'class': 'vjs-tech'
  4667. }, options['attributes'])
  4668. ;
  4669. // If source was supplied pass as a flash var.
  4670. if (source) {
  4671. if (source.type && vjs.Flash.isStreamingType(source.type)) {
  4672. var parts = vjs.Flash.streamToParts(source.src);
  4673. flashVars['rtmpConnection'] = encodeURIComponent(parts.connection);
  4674. flashVars['rtmpStream'] = encodeURIComponent(parts.stream);
  4675. }
  4676. else {
  4677. flashVars['src'] = encodeURIComponent(vjs.getAbsoluteURL(source.src));
  4678. }
  4679. }
  4680. // Add placeholder to player div
  4681. vjs.insertFirst(placeHolder, parentEl);
  4682. // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers
  4683. // This allows resetting the playhead when we catch the reload
  4684. if (options['startTime']) {
  4685. this.ready(function(){
  4686. this.load();
  4687. this.play();
  4688. this.currentTime(options['startTime']);
  4689. });
  4690. }
  4691. // Flash iFrame Mode
  4692. // In web browsers there are multiple instances where changing the parent element or visibility of a plugin causes the plugin to reload.
  4693. // - Firefox just about always. https://bugzilla.mozilla.org/show_bug.cgi?id=90268 (might be fixed by version 13)
  4694. // - Webkit when hiding the plugin
  4695. // - Webkit and Firefox when using requestFullScreen on a parent element
  4696. // Loading the flash plugin into a dynamically generated iFrame gets around most of these issues.
  4697. // Issues that remain include hiding the element and requestFullScreen in Firefox specifically
  4698. // There's on particularly annoying issue with this method which is that Firefox throws a security error on an offsite Flash object loaded into a dynamically created iFrame.
  4699. // Even though the iframe was inserted into a page on the web, Firefox + Flash considers it a local app trying to access an internet file.
  4700. // I tried mulitple ways of setting the iframe src attribute but couldn't find a src that worked well. Tried a real/fake source, in/out of domain.
  4701. // Also tried a method from stackoverflow that caused a security error in all browsers. http://stackoverflow.com/questions/2486901/how-to-set-document-domain-for-a-dynamically-generated-iframe
  4702. // In the end the solution I found to work was setting the iframe window.location.href right before doing a document.write of the Flash object.
  4703. // The only downside of this it seems to trigger another http request to the original page (no matter what's put in the href). Not sure why that is.
  4704. // NOTE (2012-01-29): Cannot get Firefox to load the remote hosted SWF into a dynamically created iFrame
  4705. // Firefox 9 throws a security error, unleess you call location.href right before doc.write.
  4706. // Not sure why that even works, but it causes the browser to look like it's continuously trying to load the page.
  4707. // Firefox 3.6 keeps calling the iframe onload function anytime I write to it, causing an endless loop.
  4708. if (options['iFrameMode'] === true && !vjs.IS_FIREFOX) {
  4709. // Create iFrame with vjs-tech class so it's 100% width/height
  4710. var iFrm = vjs.createEl('iframe', {
  4711. 'id': objId + '_iframe',
  4712. 'name': objId + '_iframe',
  4713. 'className': 'vjs-tech',
  4714. 'scrolling': 'no',
  4715. 'marginWidth': 0,
  4716. 'marginHeight': 0,
  4717. 'frameBorder': 0
  4718. });
  4719. // Update ready function names in flash vars for iframe window
  4720. flashVars['readyFunction'] = 'ready';
  4721. flashVars['eventProxyFunction'] = 'events';
  4722. flashVars['errorEventProxyFunction'] = 'errors';
  4723. // Tried multiple methods to get this to work in all browsers
  4724. // Tried embedding the flash object in the page first, and then adding a place holder to the iframe, then replacing the placeholder with the page object.
  4725. // The goal here was to try to load the swf URL in the parent page first and hope that got around the firefox security error
  4726. // var newObj = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes);
  4727. // (in onload)
  4728. // var temp = vjs.createEl('a', { id:'asdf', innerHTML: 'asdf' } );
  4729. // iDoc.body.appendChild(temp);
  4730. // Tried embedding the flash object through javascript in the iframe source.
  4731. // This works in webkit but still triggers the firefox security error
  4732. // iFrm.src = 'javascript: document.write('"+vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes)+"');";
  4733. // Tried an actual local iframe just to make sure that works, but it kills the easiness of the CDN version if you require the user to host an iframe
  4734. // We should add an option to host the iframe locally though, because it could help a lot of issues.
  4735. // iFrm.src = "iframe.html";
  4736. // Wait until iFrame has loaded to write into it.
  4737. vjs.on(iFrm, 'load', vjs.bind(this, function(){
  4738. var iDoc,
  4739. iWin = iFrm.contentWindow;
  4740. // The one working method I found was to use the iframe's document.write() to create the swf object
  4741. // This got around the security issue in all browsers except firefox.
  4742. // I did find a hack where if I call the iframe's window.location.href='', it would get around the security error
  4743. // However, the main page would look like it was loading indefinitely (URL bar loading spinner would never stop)
  4744. // Plus Firefox 3.6 didn't work no matter what I tried.
  4745. // if (vjs.USER_AGENT.match('Firefox')) {
  4746. // iWin.location.href = '';
  4747. // }
  4748. // Get the iFrame's document depending on what the browser supports
  4749. iDoc = iFrm.contentDocument ? iFrm.contentDocument : iFrm.contentWindow.document;
  4750. // Tried ensuring both document domains were the same, but they already were, so that wasn't the issue.
  4751. // Even tried adding /. that was mentioned in a browser security writeup
  4752. // document.domain = document.domain+'/.';
  4753. // iDoc.domain = document.domain+'/.';
  4754. // Tried adding the object to the iframe doc's innerHTML. Security error in all browsers.
  4755. // iDoc.body.innerHTML = swfObjectHTML;
  4756. // Tried appending the object to the iframe doc's body. Security error in all browsers.
  4757. // iDoc.body.appendChild(swfObject);
  4758. // Using document.write actually got around the security error that browsers were throwing.
  4759. // Again, it's a dynamically generated (same domain) iframe, loading an external Flash swf.
  4760. // Not sure why that's a security issue, but apparently it is.
  4761. iDoc.write(vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes));
  4762. // Setting variables on the window needs to come after the doc write because otherwise they can get reset in some browsers
  4763. // So far no issues with swf ready event being called before it's set on the window.
  4764. iWin['player'] = this.player_;
  4765. // Create swf ready function for iFrame window
  4766. iWin['ready'] = vjs.bind(this.player_, function(currSwf){
  4767. var el = iDoc.getElementById(currSwf),
  4768. player = this,
  4769. tech = player.tech;
  4770. // Update reference to playback technology element
  4771. tech.el_ = el;
  4772. // Make sure swf is actually ready. Sometimes the API isn't actually yet.
  4773. vjs.Flash.checkReady(tech);
  4774. });
  4775. // Create event listener for all swf events
  4776. iWin['events'] = vjs.bind(this.player_, function(swfID, eventName){
  4777. var player = this;
  4778. if (player && player.techName === 'flash') {
  4779. player.trigger(eventName);
  4780. }
  4781. });
  4782. // Create error listener for all swf errors
  4783. iWin['errors'] = vjs.bind(this.player_, function(swfID, eventName){
  4784. vjs.log('Flash Error', eventName);
  4785. });
  4786. }));
  4787. // Replace placeholder with iFrame (it will load now)
  4788. placeHolder.parentNode.replaceChild(iFrm, placeHolder);
  4789. // If not using iFrame mode, embed as normal object
  4790. } else {
  4791. vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes);
  4792. }
  4793. }
  4794. });
  4795. vjs.Flash.prototype.dispose = function(){
  4796. vjs.MediaTechController.prototype.dispose.call(this);
  4797. };
  4798. vjs.Flash.prototype.play = function(){
  4799. this.el_.vjs_play();
  4800. };
  4801. vjs.Flash.prototype.pause = function(){
  4802. this.el_.vjs_pause();
  4803. };
  4804. vjs.Flash.prototype.src = function(src){
  4805. if (vjs.Flash.isStreamingSrc(src)) {
  4806. src = vjs.Flash.streamToParts(src);
  4807. this.setRtmpConnection(src.connection);
  4808. this.setRtmpStream(src.stream);
  4809. }
  4810. else {
  4811. // Make sure source URL is abosolute.
  4812. src = vjs.getAbsoluteURL(src);
  4813. this.el_.vjs_src(src);
  4814. }
  4815. // Currently the SWF doesn't autoplay if you load a source later.
  4816. // e.g. Load player w/ no source, wait 2s, set src.
  4817. if (this.player_.autoplay()) {
  4818. var tech = this;
  4819. setTimeout(function(){ tech.play(); }, 0);
  4820. }
  4821. };
  4822. vjs.Flash.prototype.currentSrc = function(){
  4823. var src = this.el_.vjs_getProperty('currentSrc');
  4824. // no src, check and see if RTMP
  4825. if (src == null) {
  4826. var connection = this.rtmpConnection(),
  4827. stream = this.rtmpStream();
  4828. if (connection && stream) {
  4829. src = vjs.Flash.streamFromParts(connection, stream);
  4830. }
  4831. }
  4832. return src;
  4833. };
  4834. vjs.Flash.prototype.load = function(){
  4835. this.el_.vjs_load();
  4836. };
  4837. vjs.Flash.prototype.poster = function(){
  4838. this.el_.vjs_getProperty('poster');
  4839. };
  4840. vjs.Flash.prototype.buffered = function(){
  4841. return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered'));
  4842. };
  4843. vjs.Flash.prototype.supportsFullScreen = function(){
  4844. return false; // Flash does not allow fullscreen through javascript
  4845. };
  4846. vjs.Flash.prototype.enterFullScreen = function(){
  4847. return false;
  4848. };
  4849. // Create setters and getters for attributes
  4850. var api = vjs.Flash.prototype,
  4851. readWrite = 'rtmpConnection,rtmpStream,preload,currentTime,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','),
  4852. readOnly = 'error,currentSrc,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks'.split(',');
  4853. // Overridden: buffered
  4854. /**
  4855. * @this {*}
  4856. * @private
  4857. */
  4858. var createSetter = function(attr){
  4859. var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
  4860. api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); };
  4861. };
  4862. /**
  4863. * @this {*}
  4864. * @private
  4865. */
  4866. var createGetter = function(attr){
  4867. api[attr] = function(){ return this.el_.vjs_getProperty(attr); };
  4868. };
  4869. (function(){
  4870. var i;
  4871. // Create getter and setters for all read/write attributes
  4872. for (i = 0; i < readWrite.length; i++) {
  4873. createGetter(readWrite[i]);
  4874. createSetter(readWrite[i]);
  4875. }
  4876. // Create getters for read-only attributes
  4877. for (i = 0; i < readOnly.length; i++) {
  4878. createGetter(readOnly[i]);
  4879. }
  4880. })();
  4881. /* Flash Support Testing -------------------------------------------------------- */
  4882. vjs.Flash.isSupported = function(){
  4883. return vjs.Flash.version()[0] >= 10;
  4884. // return swfobject.hasFlashPlayerVersion('10');
  4885. };
  4886. vjs.Flash.canPlaySource = function(srcObj){
  4887. var type;
  4888. if (!srcObj.type) {
  4889. return '';
  4890. }
  4891. type = srcObj.type.replace(/;.*/,'').toLowerCase();
  4892. if (type in vjs.Flash.formats || type in vjs.Flash.streamingFormats) {
  4893. return 'maybe';
  4894. }
  4895. };
  4896. vjs.Flash.formats = {
  4897. 'video/flv': 'FLV',
  4898. 'video/x-flv': 'FLV',
  4899. 'video/mp4': 'MP4',
  4900. 'video/m4v': 'MP4'
  4901. };
  4902. vjs.Flash.streamingFormats = {
  4903. 'rtmp/mp4': 'MP4',
  4904. 'rtmp/flv': 'FLV'
  4905. };
  4906. vjs.Flash['onReady'] = function(currSwf){
  4907. var el = vjs.el(currSwf);
  4908. // Get player from box
  4909. // On firefox reloads, el might already have a player
  4910. var player = el['player'] || el.parentNode['player'],
  4911. tech = player.tech;
  4912. // Reference player on tech element
  4913. el['player'] = player;
  4914. // Update reference to playback technology element
  4915. tech.el_ = el;
  4916. vjs.Flash.checkReady(tech);
  4917. };
  4918. // The SWF isn't alwasy ready when it says it is. Sometimes the API functions still need to be added to the object.
  4919. // If it's not ready, we set a timeout to check again shortly.
  4920. vjs.Flash.checkReady = function(tech){
  4921. // Check if API property exists
  4922. if (tech.el().vjs_getProperty) {
  4923. // If so, tell tech it's ready
  4924. tech.triggerReady();
  4925. // Otherwise wait longer.
  4926. } else {
  4927. setTimeout(function(){
  4928. vjs.Flash.checkReady(tech);
  4929. }, 50);
  4930. }
  4931. };
  4932. // Trigger events from the swf on the player
  4933. vjs.Flash['onEvent'] = function(swfID, eventName){
  4934. var player = vjs.el(swfID)['player'];
  4935. player.trigger(eventName);
  4936. };
  4937. // Log errors from the swf
  4938. vjs.Flash['onError'] = function(swfID, err){
  4939. var player = vjs.el(swfID)['player'];
  4940. player.trigger('error');
  4941. vjs.log('Flash Error', err, swfID);
  4942. };
  4943. // Flash Version Check
  4944. vjs.Flash.version = function(){
  4945. var version = '0,0,0';
  4946. // IE
  4947. try {
  4948. version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  4949. // other browsers
  4950. } catch(e) {
  4951. try {
  4952. if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){
  4953. version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  4954. }
  4955. } catch(err) {}
  4956. }
  4957. return version.split(',');
  4958. };
  4959. // Flash embedding method. Only used in non-iframe mode
  4960. vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){
  4961. var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes),
  4962. // Get element by embedding code and retrieving created element
  4963. obj = vjs.createEl('div', { innerHTML: code }).childNodes[0],
  4964. par = placeHolder.parentNode
  4965. ;
  4966. placeHolder.parentNode.replaceChild(obj, placeHolder);
  4967. // IE6 seems to have an issue where it won't initialize the swf object after injecting it.
  4968. // This is a dumb fix
  4969. var newObj = par.childNodes[0];
  4970. setTimeout(function(){
  4971. newObj.style.display = 'block';
  4972. }, 1000);
  4973. return obj;
  4974. };
  4975. vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){
  4976. var objTag = '<object type="application/x-shockwave-flash"',
  4977. flashVarsString = '',
  4978. paramsString = '',
  4979. attrsString = '';
  4980. // Convert flash vars to string
  4981. if (flashVars) {
  4982. vjs.obj.each(flashVars, function(key, val){
  4983. flashVarsString += (key + '=' + val + '&amp;');
  4984. });
  4985. }
  4986. // Add swf, flashVars, and other default params
  4987. params = vjs.obj.merge({
  4988. 'movie': swf,
  4989. 'flashvars': flashVarsString,
  4990. 'allowScriptAccess': 'always', // Required to talk to swf
  4991. 'allowNetworking': 'all' // All should be default, but having security issues.
  4992. }, params);
  4993. // Create param tags string
  4994. vjs.obj.each(params, function(key, val){
  4995. paramsString += '<param name="'+key+'" value="'+val+'" />';
  4996. });
  4997. attributes = vjs.obj.merge({
  4998. // Add swf to attributes (need both for IE and Others to work)
  4999. 'data': swf,
  5000. // Default to 100% width/height
  5001. 'width': '100%',
  5002. 'height': '100%'
  5003. }, attributes);
  5004. // Create Attributes string
  5005. vjs.obj.each(attributes, function(key, val){
  5006. attrsString += (key + '="' + val + '" ');
  5007. });
  5008. return objTag + attrsString + '>' + paramsString + '</object>';
  5009. };
  5010. vjs.Flash.streamFromParts = function(connection, stream) {
  5011. return connection + '&' + stream;
  5012. };
  5013. vjs.Flash.streamToParts = function(src) {
  5014. var parts = {
  5015. connection: '',
  5016. stream: ''
  5017. };
  5018. if (! src) {
  5019. return parts;
  5020. }
  5021. // Look for the normal URL separator we expect, '&'.
  5022. // If found, we split the URL into two pieces around the
  5023. // first '&'.
  5024. var connEnd = src.indexOf('&');
  5025. var streamBegin;
  5026. if (connEnd !== -1) {
  5027. streamBegin = connEnd + 1;
  5028. }
  5029. else {
  5030. // If there's not a '&', we use the last '/' as the delimiter.
  5031. connEnd = streamBegin = src.lastIndexOf('/') + 1;
  5032. if (connEnd === 0) {
  5033. // really, there's not a '/'?
  5034. connEnd = streamBegin = src.length;
  5035. }
  5036. }
  5037. parts.connection = src.substring(0, connEnd);
  5038. parts.stream = src.substring(streamBegin, src.length);
  5039. return parts;
  5040. };
  5041. vjs.Flash.isStreamingType = function(srcType) {
  5042. return srcType in vjs.Flash.streamingFormats;
  5043. };
  5044. // RTMP has four variations, any string starting
  5045. // with one of these protocols should be valid
  5046. vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
  5047. vjs.Flash.isStreamingSrc = function(src) {
  5048. return vjs.Flash.RTMP_RE.test(src);
  5049. };
  5050. /**
  5051. * The Media Loader is the component that decides which playback technology to load
  5052. * when the player is initialized.
  5053. *
  5054. * @constructor
  5055. */
  5056. vjs.MediaLoader = vjs.Component.extend({
  5057. /** @constructor */
  5058. init: function(player, options, ready){
  5059. vjs.Component.call(this, player, options, ready);
  5060. // If there are no sources when the player is initialized,
  5061. // load the first supported playback technology.
  5062. if (!player.options_['sources'] || player.options_['sources'].length === 0) {
  5063. for (var i=0,j=player.options_['techOrder']; i<j.length; i++) {
  5064. var techName = vjs.capitalize(j[i]),
  5065. tech = window['videojs'][techName];
  5066. // Check if the browser supports this technology
  5067. if (tech && tech.isSupported()) {
  5068. player.loadTech(techName);
  5069. break;
  5070. }
  5071. }
  5072. } else {
  5073. // // Loop through playback technologies (HTML5, Flash) and check for support.
  5074. // // Then load the best source.
  5075. // // A few assumptions here:
  5076. // // All playback technologies respect preload false.
  5077. player.src(player.options_['sources']);
  5078. }
  5079. }
  5080. });
  5081. /**
  5082. * @fileoverview Text Tracks
  5083. * Text tracks are tracks of timed text events.
  5084. * Captions - text displayed over the video for the hearing impared
  5085. * Subtitles - text displayed over the video for those who don't understand langauge in the video
  5086. * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video
  5087. * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device
  5088. */
  5089. // Player Additions - Functions add to the player object for easier access to tracks
  5090. /**
  5091. * List of associated text tracks
  5092. * @type {Array}
  5093. * @private
  5094. */
  5095. vjs.Player.prototype.textTracks_;
  5096. /**
  5097. * Get an array of associated text tracks. captions, subtitles, chapters, descriptions
  5098. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  5099. * @return {Array} Array of track objects
  5100. * @private
  5101. */
  5102. vjs.Player.prototype.textTracks = function(){
  5103. this.textTracks_ = this.textTracks_ || [];
  5104. return this.textTracks_;
  5105. };
  5106. /**
  5107. * Add a text track
  5108. * In addition to the W3C settings we allow adding additional info through options.
  5109. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  5110. * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata
  5111. * @param {String=} label Optional label
  5112. * @param {String=} language Optional language
  5113. * @param {Object=} options Additional track options, like src
  5114. * @private
  5115. */
  5116. vjs.Player.prototype.addTextTrack = function(kind, label, language, options){
  5117. var tracks = this.textTracks_ = this.textTracks_ || [];
  5118. options = options || {};
  5119. options['kind'] = kind;
  5120. options['label'] = label;
  5121. options['language'] = language;
  5122. // HTML5 Spec says default to subtitles.
  5123. // Uppercase first letter to match class names
  5124. var Kind = vjs.capitalize(kind || 'subtitles');
  5125. // Create correct texttrack class. CaptionsTrack, etc.
  5126. var track = new window['videojs'][Kind + 'Track'](this, options);
  5127. tracks.push(track);
  5128. // If track.dflt() is set, start showing immediately
  5129. // TODO: Add a process to deterime the best track to show for the specific kind
  5130. // Incase there are mulitple defaulted tracks of the same kind
  5131. // Or the user has a set preference of a specific language that should override the default
  5132. // if (track.dflt()) {
  5133. // this.ready(vjs.bind(track, track.show));
  5134. // }
  5135. return track;
  5136. };
  5137. /**
  5138. * Add an array of text tracks. captions, subtitles, chapters, descriptions
  5139. * Track objects will be stored in the player.textTracks() array
  5140. * @param {Array} trackList Array of track elements or objects (fake track elements)
  5141. * @private
  5142. */
  5143. vjs.Player.prototype.addTextTracks = function(trackList){
  5144. var trackObj;
  5145. for (var i = 0; i < trackList.length; i++) {
  5146. trackObj = trackList[i];
  5147. this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj);
  5148. }
  5149. return this;
  5150. };
  5151. // Show a text track
  5152. // disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.)
  5153. vjs.Player.prototype.showTextTrack = function(id, disableSameKind){
  5154. var tracks = this.textTracks_,
  5155. i = 0,
  5156. j = tracks.length,
  5157. track, showTrack, kind;
  5158. // Find Track with same ID
  5159. for (;i<j;i++) {
  5160. track = tracks[i];
  5161. if (track.id() === id) {
  5162. track.show();
  5163. showTrack = track;
  5164. // Disable tracks of the same kind
  5165. } else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 0) {
  5166. track.disable();
  5167. }
  5168. }
  5169. // Get track kind from shown track or disableSameKind
  5170. kind = (showTrack) ? showTrack.kind() : ((disableSameKind) ? disableSameKind : false);
  5171. // Trigger trackchange event, captionstrackchange, subtitlestrackchange, etc.
  5172. if (kind) {
  5173. this.trigger(kind+'trackchange');
  5174. }
  5175. return this;
  5176. };
  5177. /**
  5178. * The base class for all text tracks
  5179. *
  5180. * Handles the parsing, hiding, and showing of text track cues
  5181. *
  5182. * @param {vjs.Player|Object} player
  5183. * @param {Object=} options
  5184. * @constructor
  5185. */
  5186. vjs.TextTrack = vjs.Component.extend({
  5187. /** @constructor */
  5188. init: function(player, options){
  5189. vjs.Component.call(this, player, options);
  5190. // Apply track info to track object
  5191. // Options will often be a track element
  5192. // Build ID if one doesn't exist
  5193. this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++);
  5194. this.src_ = options['src'];
  5195. // 'default' is a reserved keyword in js so we use an abbreviated version
  5196. this.dflt_ = options['default'] || options['dflt'];
  5197. this.title_ = options['title'];
  5198. this.language_ = options['srclang'];
  5199. this.label_ = options['label'];
  5200. this.cues_ = [];
  5201. this.activeCues_ = [];
  5202. this.readyState_ = 0;
  5203. this.mode_ = 0;
  5204. this.player_.on('fullscreenchange', vjs.bind(this, this.adjustFontSize));
  5205. }
  5206. });
  5207. /**
  5208. * Track kind value. Captions, subtitles, etc.
  5209. * @private
  5210. */
  5211. vjs.TextTrack.prototype.kind_;
  5212. /**
  5213. * Get the track kind value
  5214. * @return {String}
  5215. */
  5216. vjs.TextTrack.prototype.kind = function(){
  5217. return this.kind_;
  5218. };
  5219. /**
  5220. * Track src value
  5221. * @private
  5222. */
  5223. vjs.TextTrack.prototype.src_;
  5224. /**
  5225. * Get the track src value
  5226. * @return {String}
  5227. */
  5228. vjs.TextTrack.prototype.src = function(){
  5229. return this.src_;
  5230. };
  5231. /**
  5232. * Track default value
  5233. * If default is used, subtitles/captions to start showing
  5234. * @private
  5235. */
  5236. vjs.TextTrack.prototype.dflt_;
  5237. /**
  5238. * Get the track default value. ('default' is a reserved keyword)
  5239. * @return {Boolean}
  5240. */
  5241. vjs.TextTrack.prototype.dflt = function(){
  5242. return this.dflt_;
  5243. };
  5244. /**
  5245. * Track title value
  5246. * @private
  5247. */
  5248. vjs.TextTrack.prototype.title_;
  5249. /**
  5250. * Get the track title value
  5251. * @return {String}
  5252. */
  5253. vjs.TextTrack.prototype.title = function(){
  5254. return this.title_;
  5255. };
  5256. /**
  5257. * Language - two letter string to represent track language, e.g. 'en' for English
  5258. * Spec def: readonly attribute DOMString language;
  5259. * @private
  5260. */
  5261. vjs.TextTrack.prototype.language_;
  5262. /**
  5263. * Get the track language value
  5264. * @return {String}
  5265. */
  5266. vjs.TextTrack.prototype.language = function(){
  5267. return this.language_;
  5268. };
  5269. /**
  5270. * Track label e.g. 'English'
  5271. * Spec def: readonly attribute DOMString label;
  5272. * @private
  5273. */
  5274. vjs.TextTrack.prototype.label_;
  5275. /**
  5276. * Get the track label value
  5277. * @return {String}
  5278. */
  5279. vjs.TextTrack.prototype.label = function(){
  5280. return this.label_;
  5281. };
  5282. /**
  5283. * All cues of the track. Cues have a startTime, endTime, text, and other properties.
  5284. * Spec def: readonly attribute TextTrackCueList cues;
  5285. * @private
  5286. */
  5287. vjs.TextTrack.prototype.cues_;
  5288. /**
  5289. * Get the track cues
  5290. * @return {Array}
  5291. */
  5292. vjs.TextTrack.prototype.cues = function(){
  5293. return this.cues_;
  5294. };
  5295. /**
  5296. * ActiveCues is all cues that are currently showing
  5297. * Spec def: readonly attribute TextTrackCueList activeCues;
  5298. * @private
  5299. */
  5300. vjs.TextTrack.prototype.activeCues_;
  5301. /**
  5302. * Get the track active cues
  5303. * @return {Array}
  5304. */
  5305. vjs.TextTrack.prototype.activeCues = function(){
  5306. return this.activeCues_;
  5307. };
  5308. /**
  5309. * ReadyState describes if the text file has been loaded
  5310. * const unsigned short NONE = 0;
  5311. * const unsigned short LOADING = 1;
  5312. * const unsigned short LOADED = 2;
  5313. * const unsigned short ERROR = 3;
  5314. * readonly attribute unsigned short readyState;
  5315. * @private
  5316. */
  5317. vjs.TextTrack.prototype.readyState_;
  5318. /**
  5319. * Get the track readyState
  5320. * @return {Number}
  5321. */
  5322. vjs.TextTrack.prototype.readyState = function(){
  5323. return this.readyState_;
  5324. };
  5325. /**
  5326. * Mode describes if the track is showing, hidden, or disabled
  5327. * const unsigned short OFF = 0;
  5328. * const unsigned short HIDDEN = 1; (still triggering cuechange events, but not visible)
  5329. * const unsigned short SHOWING = 2;
  5330. * attribute unsigned short mode;
  5331. * @private
  5332. */
  5333. vjs.TextTrack.prototype.mode_;
  5334. /**
  5335. * Get the track mode
  5336. * @return {Number}
  5337. */
  5338. vjs.TextTrack.prototype.mode = function(){
  5339. return this.mode_;
  5340. };
  5341. /**
  5342. * Change the font size of the text track to make it larger when playing in fullscreen mode
  5343. * and restore it to its normal size when not in fullscreen mode.
  5344. */
  5345. vjs.TextTrack.prototype.adjustFontSize = function(){
  5346. if (this.player_.isFullScreen) {
  5347. // Scale the font by the same factor as increasing the video width to the full screen window width.
  5348. // Additionally, multiply that factor by 1.4, which is the default font size for
  5349. // the caption track (from the CSS)
  5350. this.el_.style.fontSize = screen.width / this.player_.width() * 1.4 * 100 + '%';
  5351. } else {
  5352. // Change the font size of the text track back to its original non-fullscreen size
  5353. this.el_.style.fontSize = '';
  5354. }
  5355. };
  5356. /**
  5357. * Create basic div to hold cue text
  5358. * @return {Element}
  5359. */
  5360. vjs.TextTrack.prototype.createEl = function(){
  5361. return vjs.Component.prototype.createEl.call(this, 'div', {
  5362. className: 'vjs-' + this.kind_ + ' vjs-text-track'
  5363. });
  5364. };
  5365. /**
  5366. * Show: Mode Showing (2)
  5367. * Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily.
  5368. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly.
  5369. * In addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate;
  5370. * for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion;
  5371. * and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue.
  5372. * The showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute.
  5373. * This allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences.
  5374. */
  5375. vjs.TextTrack.prototype.show = function(){
  5376. this.activate();
  5377. this.mode_ = 2;
  5378. // Show element.
  5379. vjs.Component.prototype.show.call(this);
  5380. };
  5381. /**
  5382. * Hide: Mode Hidden (1)
  5383. * Indicates that the text track is active, but that the user agent is not actively displaying the cues.
  5384. * If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily.
  5385. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly.
  5386. */
  5387. vjs.TextTrack.prototype.hide = function(){
  5388. // When hidden, cues are still triggered. Disable to stop triggering.
  5389. this.activate();
  5390. this.mode_ = 1;
  5391. // Hide element.
  5392. vjs.Component.prototype.hide.call(this);
  5393. };
  5394. /**
  5395. * Disable: Mode Off/Disable (0)
  5396. * Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track.
  5397. * No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues.
  5398. */
  5399. vjs.TextTrack.prototype.disable = function(){
  5400. // If showing, hide.
  5401. if (this.mode_ == 2) { this.hide(); }
  5402. // Stop triggering cues
  5403. this.deactivate();
  5404. // Switch Mode to Off
  5405. this.mode_ = 0;
  5406. };
  5407. /**
  5408. * Turn on cue tracking. Tracks that are showing OR hidden are active.
  5409. */
  5410. vjs.TextTrack.prototype.activate = function(){
  5411. // Load text file if it hasn't been yet.
  5412. if (this.readyState_ === 0) { this.load(); }
  5413. // Only activate if not already active.
  5414. if (this.mode_ === 0) {
  5415. // Update current cue on timeupdate
  5416. // Using unique ID for bind function so other tracks don't remove listener
  5417. this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_));
  5418. // Reset cue time on media end
  5419. this.player_.on('ended', vjs.bind(this, this.reset, this.id_));
  5420. // Add to display
  5421. if (this.kind_ === 'captions' || this.kind_ === 'subtitles') {
  5422. this.player_.getChild('textTrackDisplay').addChild(this);
  5423. }
  5424. }
  5425. };
  5426. /**
  5427. * Turn off cue tracking.
  5428. */
  5429. vjs.TextTrack.prototype.deactivate = function(){
  5430. // Using unique ID for bind function so other tracks don't remove listener
  5431. this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_));
  5432. this.player_.off('ended', vjs.bind(this, this.reset, this.id_));
  5433. this.reset(); // Reset
  5434. // Remove from display
  5435. this.player_.getChild('textTrackDisplay').removeChild(this);
  5436. };
  5437. // A readiness state
  5438. // One of the following:
  5439. //
  5440. // Not loaded
  5441. // Indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained.
  5442. //
  5443. // Loading
  5444. // Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track.
  5445. //
  5446. // Loaded
  5447. // Indicates that the text track has been loaded with no fatal errors. No new cues will be added to the track except if the text track corresponds to a MutableTextTrack object.
  5448. //
  5449. // Failed to load
  5450. // Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained.
  5451. vjs.TextTrack.prototype.load = function(){
  5452. // Only load if not loaded yet.
  5453. if (this.readyState_ === 0) {
  5454. this.readyState_ = 1;
  5455. vjs.get(this.src_, vjs.bind(this, this.parseCues), vjs.bind(this, this.onError));
  5456. }
  5457. };
  5458. vjs.TextTrack.prototype.onError = function(err){
  5459. this.error = err;
  5460. this.readyState_ = 3;
  5461. this.trigger('error');
  5462. };
  5463. // Parse the WebVTT text format for cue times.
  5464. // TODO: Separate parser into own class so alternative timed text formats can be used. (TTML, DFXP)
  5465. vjs.TextTrack.prototype.parseCues = function(srcContent) {
  5466. var cue, time, text,
  5467. lines = srcContent.split('\n'),
  5468. line = '', id;
  5469. for (var i=1, j=lines.length; i<j; i++) {
  5470. // Line 0 should be 'WEBVTT', so skipping i=0
  5471. line = vjs.trim(lines[i]); // Trim whitespace and linebreaks
  5472. if (line) { // Loop until a line with content
  5473. // First line could be an optional cue ID
  5474. // Check if line has the time separator
  5475. if (line.indexOf('-->') == -1) {
  5476. id = line;
  5477. // Advance to next line for timing.
  5478. line = vjs.trim(lines[++i]);
  5479. } else {
  5480. id = this.cues_.length;
  5481. }
  5482. // First line - Number
  5483. cue = {
  5484. id: id, // Cue Number
  5485. index: this.cues_.length // Position in Array
  5486. };
  5487. // Timing line
  5488. time = line.split(' --> ');
  5489. cue.startTime = this.parseCueTime(time[0]);
  5490. cue.endTime = this.parseCueTime(time[1]);
  5491. // Additional lines - Cue Text
  5492. text = [];
  5493. // Loop until a blank line or end of lines
  5494. // Assumeing trim('') returns false for blank lines
  5495. while (lines[++i] && (line = vjs.trim(lines[i]))) {
  5496. text.push(line);
  5497. }
  5498. cue.text = text.join('<br/>');
  5499. // Add this cue
  5500. this.cues_.push(cue);
  5501. }
  5502. }
  5503. this.readyState_ = 2;
  5504. this.trigger('loaded');
  5505. };
  5506. vjs.TextTrack.prototype.parseCueTime = function(timeText) {
  5507. var parts = timeText.split(':'),
  5508. time = 0,
  5509. hours, minutes, other, seconds, ms;
  5510. // Check if optional hours place is included
  5511. // 00:00:00.000 vs. 00:00.000
  5512. if (parts.length == 3) {
  5513. hours = parts[0];
  5514. minutes = parts[1];
  5515. other = parts[2];
  5516. } else {
  5517. hours = 0;
  5518. minutes = parts[0];
  5519. other = parts[1];
  5520. }
  5521. // Break other (seconds, milliseconds, and flags) by spaces
  5522. // TODO: Make additional cue layout settings work with flags
  5523. other = other.split(/\s+/);
  5524. // Remove seconds. Seconds is the first part before any spaces.
  5525. seconds = other.splice(0,1)[0];
  5526. // Could use either . or , for decimal
  5527. seconds = seconds.split(/\.|,/);
  5528. // Get milliseconds
  5529. ms = parseFloat(seconds[1]);
  5530. seconds = seconds[0];
  5531. // hours => seconds
  5532. time += parseFloat(hours) * 3600;
  5533. // minutes => seconds
  5534. time += parseFloat(minutes) * 60;
  5535. // Add seconds
  5536. time += parseFloat(seconds);
  5537. // Add milliseconds
  5538. if (ms) { time += ms/1000; }
  5539. return time;
  5540. };
  5541. // Update active cues whenever timeupdate events are triggered on the player.
  5542. vjs.TextTrack.prototype.update = function(){
  5543. if (this.cues_.length > 0) {
  5544. // Get curent player time
  5545. var time = this.player_.currentTime();
  5546. // Check if the new time is outside the time box created by the the last update.
  5547. if (this.prevChange === undefined || time < this.prevChange || this.nextChange <= time) {
  5548. var cues = this.cues_,
  5549. // Create a new time box for this state.
  5550. newNextChange = this.player_.duration(), // Start at beginning of the timeline
  5551. newPrevChange = 0, // Start at end
  5552. reverse = false, // Set the direction of the loop through the cues. Optimized the cue check.
  5553. newCues = [], // Store new active cues.
  5554. // Store where in the loop the current active cues are, to provide a smart starting point for the next loop.
  5555. firstActiveIndex, lastActiveIndex,
  5556. cue, i; // Loop vars
  5557. // Check if time is going forwards or backwards (scrubbing/rewinding)
  5558. // If we know the direction we can optimize the starting position and direction of the loop through the cues array.
  5559. if (time >= this.nextChange || this.nextChange === undefined) { // NextChange should happen
  5560. // Forwards, so start at the index of the first active cue and loop forward
  5561. i = (this.firstActiveIndex !== undefined) ? this.firstActiveIndex : 0;
  5562. } else {
  5563. // Backwards, so start at the index of the last active cue and loop backward
  5564. reverse = true;
  5565. i = (this.lastActiveIndex !== undefined) ? this.lastActiveIndex : cues.length - 1;
  5566. }
  5567. while (true) { // Loop until broken
  5568. cue = cues[i];
  5569. // Cue ended at this point
  5570. if (cue.endTime <= time) {
  5571. newPrevChange = Math.max(newPrevChange, cue.endTime);
  5572. if (cue.active) {
  5573. cue.active = false;
  5574. }
  5575. // No earlier cues should have an active start time.
  5576. // Nevermind. Assume first cue could have a duration the same as the video.
  5577. // In that case we need to loop all the way back to the beginning.
  5578. // if (reverse && cue.startTime) { break; }
  5579. // Cue hasn't started
  5580. } else if (time < cue.startTime) {
  5581. newNextChange = Math.min(newNextChange, cue.startTime);
  5582. if (cue.active) {
  5583. cue.active = false;
  5584. }
  5585. // No later cues should have an active start time.
  5586. if (!reverse) { break; }
  5587. // Cue is current
  5588. } else {
  5589. if (reverse) {
  5590. // Add cue to front of array to keep in time order
  5591. newCues.splice(0,0,cue);
  5592. // If in reverse, the first current cue is our lastActiveCue
  5593. if (lastActiveIndex === undefined) { lastActiveIndex = i; }
  5594. firstActiveIndex = i;
  5595. } else {
  5596. // Add cue to end of array
  5597. newCues.push(cue);
  5598. // If forward, the first current cue is our firstActiveIndex
  5599. if (firstActiveIndex === undefined) { firstActiveIndex = i; }
  5600. lastActiveIndex = i;
  5601. }
  5602. newNextChange = Math.min(newNextChange, cue.endTime);
  5603. newPrevChange = Math.max(newPrevChange, cue.startTime);
  5604. cue.active = true;
  5605. }
  5606. if (reverse) {
  5607. // Reverse down the array of cues, break if at first
  5608. if (i === 0) { break; } else { i--; }
  5609. } else {
  5610. // Walk up the array fo cues, break if at last
  5611. if (i === cues.length - 1) { break; } else { i++; }
  5612. }
  5613. }
  5614. this.activeCues_ = newCues;
  5615. this.nextChange = newNextChange;
  5616. this.prevChange = newPrevChange;
  5617. this.firstActiveIndex = firstActiveIndex;
  5618. this.lastActiveIndex = lastActiveIndex;
  5619. this.updateDisplay();
  5620. this.trigger('cuechange');
  5621. }
  5622. }
  5623. };
  5624. // Add cue HTML to display
  5625. vjs.TextTrack.prototype.updateDisplay = function(){
  5626. var cues = this.activeCues_,
  5627. html = '',
  5628. i=0,j=cues.length;
  5629. for (;i<j;i++) {
  5630. html += '<span class="vjs-tt-cue">'+cues[i].text+'</span>';
  5631. }
  5632. this.el_.innerHTML = html;
  5633. };
  5634. // Set all loop helper values back
  5635. vjs.TextTrack.prototype.reset = function(){
  5636. this.nextChange = 0;
  5637. this.prevChange = this.player_.duration();
  5638. this.firstActiveIndex = 0;
  5639. this.lastActiveIndex = 0;
  5640. };
  5641. // Create specific track types
  5642. /**
  5643. * The track component for managing the hiding and showing of captions
  5644. *
  5645. * @constructor
  5646. */
  5647. vjs.CaptionsTrack = vjs.TextTrack.extend();
  5648. vjs.CaptionsTrack.prototype.kind_ = 'captions';
  5649. // Exporting here because Track creation requires the track kind
  5650. // to be available on global object. e.g. new window['videojs'][Kind + 'Track']
  5651. /**
  5652. * The track component for managing the hiding and showing of subtitles
  5653. *
  5654. * @constructor
  5655. */
  5656. vjs.SubtitlesTrack = vjs.TextTrack.extend();
  5657. vjs.SubtitlesTrack.prototype.kind_ = 'subtitles';
  5658. /**
  5659. * The track component for managing the hiding and showing of chapters
  5660. *
  5661. * @constructor
  5662. */
  5663. vjs.ChaptersTrack = vjs.TextTrack.extend();
  5664. vjs.ChaptersTrack.prototype.kind_ = 'chapters';
  5665. /* Text Track Display
  5666. ============================================================================= */
  5667. // Global container for both subtitle and captions text. Simple div container.
  5668. /**
  5669. * The component for displaying text track cues
  5670. *
  5671. * @constructor
  5672. */
  5673. vjs.TextTrackDisplay = vjs.Component.extend({
  5674. /** @constructor */
  5675. init: function(player, options, ready){
  5676. vjs.Component.call(this, player, options, ready);
  5677. // This used to be called during player init, but was causing an error
  5678. // if a track should show by default and the display hadn't loaded yet.
  5679. // Should probably be moved to an external track loader when we support
  5680. // tracks that don't need a display.
  5681. if (player.options_['tracks'] && player.options_['tracks'].length > 0) {
  5682. this.player_.addTextTracks(player.options_['tracks']);
  5683. }
  5684. }
  5685. });
  5686. vjs.TextTrackDisplay.prototype.createEl = function(){
  5687. return vjs.Component.prototype.createEl.call(this, 'div', {
  5688. className: 'vjs-text-track-display'
  5689. });
  5690. };
  5691. /**
  5692. * The specific menu item type for selecting a language within a text track kind
  5693. *
  5694. * @constructor
  5695. */
  5696. vjs.TextTrackMenuItem = vjs.MenuItem.extend({
  5697. /** @constructor */
  5698. init: function(player, options){
  5699. var track = this.track = options['track'];
  5700. // Modify options for parent MenuItem class's init.
  5701. options['label'] = track.label();
  5702. options['selected'] = track.dflt();
  5703. vjs.MenuItem.call(this, player, options);
  5704. this.player_.on(track.kind() + 'trackchange', vjs.bind(this, this.update));
  5705. }
  5706. });
  5707. vjs.TextTrackMenuItem.prototype.onClick = function(){
  5708. vjs.MenuItem.prototype.onClick.call(this);
  5709. this.player_.showTextTrack(this.track.id_, this.track.kind());
  5710. };
  5711. vjs.TextTrackMenuItem.prototype.update = function(){
  5712. this.selected(this.track.mode() == 2);
  5713. };
  5714. /**
  5715. * A special menu item for turning of a specific type of text track
  5716. *
  5717. * @constructor
  5718. */
  5719. vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({
  5720. /** @constructor */
  5721. init: function(player, options){
  5722. // Create pseudo track info
  5723. // Requires options['kind']
  5724. options['track'] = {
  5725. kind: function() { return options['kind']; },
  5726. player: player,
  5727. label: function(){ return options['kind'] + ' off'; },
  5728. dflt: function(){ return false; },
  5729. mode: function(){ return false; }
  5730. };
  5731. vjs.TextTrackMenuItem.call(this, player, options);
  5732. this.selected(true);
  5733. }
  5734. });
  5735. vjs.OffTextTrackMenuItem.prototype.onClick = function(){
  5736. vjs.TextTrackMenuItem.prototype.onClick.call(this);
  5737. this.player_.showTextTrack(this.track.id_, this.track.kind());
  5738. };
  5739. vjs.OffTextTrackMenuItem.prototype.update = function(){
  5740. var tracks = this.player_.textTracks(),
  5741. i=0, j=tracks.length, track,
  5742. off = true;
  5743. for (;i<j;i++) {
  5744. track = tracks[i];
  5745. if (track.kind() == this.track.kind() && track.mode() == 2) {
  5746. off = false;
  5747. }
  5748. }
  5749. this.selected(off);
  5750. };
  5751. /**
  5752. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  5753. *
  5754. * @constructor
  5755. */
  5756. vjs.TextTrackButton = vjs.MenuButton.extend({
  5757. /** @constructor */
  5758. init: function(player, options){
  5759. vjs.MenuButton.call(this, player, options);
  5760. if (this.items.length <= 1) {
  5761. this.hide();
  5762. }
  5763. }
  5764. });
  5765. // vjs.TextTrackButton.prototype.buttonPressed = false;
  5766. // vjs.TextTrackButton.prototype.createMenu = function(){
  5767. // var menu = new vjs.Menu(this.player_);
  5768. // // Add a title list item to the top
  5769. // // menu.el().appendChild(vjs.createEl('li', {
  5770. // // className: 'vjs-menu-title',
  5771. // // innerHTML: vjs.capitalize(this.kind_),
  5772. // // tabindex: -1
  5773. // // }));
  5774. // this.items = this.createItems();
  5775. // // Add menu items to the menu
  5776. // for (var i = 0; i < this.items.length; i++) {
  5777. // menu.addItem(this.items[i]);
  5778. // }
  5779. // // Add list to element
  5780. // this.addChild(menu);
  5781. // return menu;
  5782. // };
  5783. // Create a menu item for each text track
  5784. vjs.TextTrackButton.prototype.createItems = function(){
  5785. var items = [], track;
  5786. // Add an OFF menu item to turn all tracks off
  5787. items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ }));
  5788. for (var i = 0; i < this.player_.textTracks().length; i++) {
  5789. track = this.player_.textTracks()[i];
  5790. if (track.kind() === this.kind_) {
  5791. items.push(new vjs.TextTrackMenuItem(this.player_, {
  5792. 'track': track
  5793. }));
  5794. }
  5795. }
  5796. return items;
  5797. };
  5798. /**
  5799. * The button component for toggling and selecting captions
  5800. *
  5801. * @constructor
  5802. */
  5803. vjs.CaptionsButton = vjs.TextTrackButton.extend({
  5804. /** @constructor */
  5805. init: function(player, options, ready){
  5806. vjs.TextTrackButton.call(this, player, options, ready);
  5807. this.el_.setAttribute('aria-label','Captions Menu');
  5808. }
  5809. });
  5810. vjs.CaptionsButton.prototype.kind_ = 'captions';
  5811. vjs.CaptionsButton.prototype.buttonText = 'Captions';
  5812. vjs.CaptionsButton.prototype.className = 'vjs-captions-button';
  5813. /**
  5814. * The button component for toggling and selecting subtitles
  5815. *
  5816. * @constructor
  5817. */
  5818. vjs.SubtitlesButton = vjs.TextTrackButton.extend({
  5819. /** @constructor */
  5820. init: function(player, options, ready){
  5821. vjs.TextTrackButton.call(this, player, options, ready);
  5822. this.el_.setAttribute('aria-label','Subtitles Menu');
  5823. }
  5824. });
  5825. vjs.SubtitlesButton.prototype.kind_ = 'subtitles';
  5826. vjs.SubtitlesButton.prototype.buttonText = 'Subtitles';
  5827. vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button';
  5828. // Chapters act much differently than other text tracks
  5829. // Cues are navigation vs. other tracks of alternative languages
  5830. /**
  5831. * The button component for toggling and selecting chapters
  5832. *
  5833. * @constructor
  5834. */
  5835. vjs.ChaptersButton = vjs.TextTrackButton.extend({
  5836. /** @constructor */
  5837. init: function(player, options, ready){
  5838. vjs.TextTrackButton.call(this, player, options, ready);
  5839. this.el_.setAttribute('aria-label','Chapters Menu');
  5840. }
  5841. });
  5842. vjs.ChaptersButton.prototype.kind_ = 'chapters';
  5843. vjs.ChaptersButton.prototype.buttonText = 'Chapters';
  5844. vjs.ChaptersButton.prototype.className = 'vjs-chapters-button';
  5845. // Create a menu item for each text track
  5846. vjs.ChaptersButton.prototype.createItems = function(){
  5847. var items = [], track;
  5848. for (var i = 0; i < this.player_.textTracks().length; i++) {
  5849. track = this.player_.textTracks()[i];
  5850. if (track.kind() === this.kind_) {
  5851. items.push(new vjs.TextTrackMenuItem(this.player_, {
  5852. 'track': track
  5853. }));
  5854. }
  5855. }
  5856. return items;
  5857. };
  5858. vjs.ChaptersButton.prototype.createMenu = function(){
  5859. var tracks = this.player_.textTracks(),
  5860. i = 0,
  5861. j = tracks.length,
  5862. track, chaptersTrack,
  5863. items = this.items = [];
  5864. for (;i<j;i++) {
  5865. track = tracks[i];
  5866. if (track.kind() == this.kind_ && track.dflt()) {
  5867. if (track.readyState() < 2) {
  5868. this.chaptersTrack = track;
  5869. track.on('loaded', vjs.bind(this, this.createMenu));
  5870. return;
  5871. } else {
  5872. chaptersTrack = track;
  5873. break;
  5874. }
  5875. }
  5876. }
  5877. var menu = this.menu = new vjs.Menu(this.player_);
  5878. menu.el_.appendChild(vjs.createEl('li', {
  5879. className: 'vjs-menu-title',
  5880. innerHTML: vjs.capitalize(this.kind_),
  5881. tabindex: -1
  5882. }));
  5883. if (chaptersTrack) {
  5884. var cues = chaptersTrack.cues_, cue, mi;
  5885. i = 0;
  5886. j = cues.length;
  5887. for (;i<j;i++) {
  5888. cue = cues[i];
  5889. mi = new vjs.ChaptersTrackMenuItem(this.player_, {
  5890. 'track': chaptersTrack,
  5891. 'cue': cue
  5892. });
  5893. items.push(mi);
  5894. menu.addChild(mi);
  5895. }
  5896. }
  5897. if (this.items.length > 0) {
  5898. this.show();
  5899. }
  5900. return menu;
  5901. };
  5902. /**
  5903. * @constructor
  5904. */
  5905. vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({
  5906. /** @constructor */
  5907. init: function(player, options){
  5908. var track = this.track = options['track'],
  5909. cue = this.cue = options['cue'],
  5910. currentTime = player.currentTime();
  5911. // Modify options for parent MenuItem class's init.
  5912. options['label'] = cue.text;
  5913. options['selected'] = (cue.startTime <= currentTime && currentTime < cue.endTime);
  5914. vjs.MenuItem.call(this, player, options);
  5915. track.on('cuechange', vjs.bind(this, this.update));
  5916. }
  5917. });
  5918. vjs.ChaptersTrackMenuItem.prototype.onClick = function(){
  5919. vjs.MenuItem.prototype.onClick.call(this);
  5920. this.player_.currentTime(this.cue.startTime);
  5921. this.update(this.cue.startTime);
  5922. };
  5923. vjs.ChaptersTrackMenuItem.prototype.update = function(){
  5924. var cue = this.cue,
  5925. currentTime = this.player_.currentTime();
  5926. // vjs.log(currentTime, cue.startTime);
  5927. this.selected(cue.startTime <= currentTime && currentTime < cue.endTime);
  5928. };
  5929. // Add Buttons to controlBar
  5930. vjs.obj.merge(vjs.ControlBar.prototype.options_['children'], {
  5931. 'subtitlesButton': {},
  5932. 'captionsButton': {},
  5933. 'chaptersButton': {}
  5934. });
  5935. // vjs.Cue = vjs.Component.extend({
  5936. // /** @constructor */
  5937. // init: function(player, options){
  5938. // vjs.Component.call(this, player, options);
  5939. // }
  5940. // });
  5941. /**
  5942. * @fileoverview Add JSON support
  5943. * @suppress {undefinedVars}
  5944. * (Compiler doesn't like JSON not being declared)
  5945. */
  5946. /**
  5947. * Javascript JSON implementation
  5948. * (Parse Method Only)
  5949. * https://github.com/douglascrockford/JSON-js/blob/master/json2.js
  5950. * Only using for parse method when parsing data-setup attribute JSON.
  5951. * @suppress {undefinedVars}
  5952. * @namespace
  5953. * @private
  5954. */
  5955. vjs.JSON;
  5956. if (typeof window.JSON !== 'undefined' && window.JSON.parse === 'function') {
  5957. vjs.JSON = window.JSON;
  5958. } else {
  5959. vjs.JSON = {};
  5960. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  5961. /**
  5962. * parse the json
  5963. *
  5964. * @memberof vjs.JSON
  5965. * @return {Object|Array} The parsed JSON
  5966. */
  5967. vjs.JSON.parse = function (text, reviver) {
  5968. var j;
  5969. function walk(holder, key) {
  5970. var k, v, value = holder[key];
  5971. if (value && typeof value === 'object') {
  5972. for (k in value) {
  5973. if (Object.prototype.hasOwnProperty.call(value, k)) {
  5974. v = walk(value, k);
  5975. if (v !== undefined) {
  5976. value[k] = v;
  5977. } else {
  5978. delete value[k];
  5979. }
  5980. }
  5981. }
  5982. }
  5983. return reviver.call(holder, key, value);
  5984. }
  5985. text = String(text);
  5986. cx.lastIndex = 0;
  5987. if (cx.test(text)) {
  5988. text = text.replace(cx, function (a) {
  5989. return '\\u' +
  5990. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  5991. });
  5992. }
  5993. if (/^[\],:{}\s]*$/
  5994. .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  5995. .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  5996. .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  5997. j = eval('(' + text + ')');
  5998. return typeof reviver === 'function' ?
  5999. walk({'': j}, '') : j;
  6000. }
  6001. throw new SyntaxError('JSON.parse(): invalid or malformed JSON data');
  6002. };
  6003. }
  6004. /**
  6005. * @fileoverview Functions for automatically setting up a player
  6006. * based on the data-setup attribute of the video tag
  6007. */
  6008. // Automatically set up any tags that have a data-setup attribute
  6009. vjs.autoSetup = function(){
  6010. var options, vid, player,
  6011. vids = document.getElementsByTagName('video');
  6012. // Check if any media elements exist
  6013. if (vids && vids.length > 0) {
  6014. for (var i=0,j=vids.length; i<j; i++) {
  6015. vid = vids[i];
  6016. // Check if element exists, has getAttribute func.
  6017. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately.
  6018. if (vid && vid.getAttribute) {
  6019. // Make sure this player hasn't already been set up.
  6020. if (vid['player'] === undefined) {
  6021. options = vid.getAttribute('data-setup');
  6022. // Check if data-setup attr exists.
  6023. // We only auto-setup if they've added the data-setup attr.
  6024. if (options !== null) {
  6025. // Parse options JSON
  6026. // If empty string, make it a parsable json object.
  6027. options = vjs.JSON.parse(options || '{}');
  6028. // Create new video.js instance.
  6029. player = videojs(vid, options);
  6030. }
  6031. }
  6032. // If getAttribute isn't defined, we need to wait for the DOM.
  6033. } else {
  6034. vjs.autoSetupTimeout(1);
  6035. break;
  6036. }
  6037. }
  6038. // No videos were found, so keep looping unless page is finisehd loading.
  6039. } else if (!vjs.windowLoaded) {
  6040. vjs.autoSetupTimeout(1);
  6041. }
  6042. };
  6043. // Pause to let the DOM keep processing
  6044. vjs.autoSetupTimeout = function(wait){
  6045. setTimeout(vjs.autoSetup, wait);
  6046. };
  6047. if (document.readyState === 'complete') {
  6048. vjs.windowLoaded = true;
  6049. } else {
  6050. vjs.one(window, 'load', function(){
  6051. vjs.windowLoaded = true;
  6052. });
  6053. }
  6054. // Run Auto-load players
  6055. // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
  6056. vjs.autoSetupTimeout(1);
  6057. /**
  6058. * the method for registering a video.js plugin
  6059. *
  6060. * @param {String} name The name of the plugin
  6061. * @param {Function} init The function that is run when the player inits
  6062. */
  6063. vjs.plugin = function(name, init){
  6064. vjs.Player.prototype[name] = init;
  6065. };