video.cjs.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799
  1. /**
  2. * @license
  3. * Video.js 8.3.0 <http://videojs.com/>
  4. * Copyright Brightcove, Inc. <https://www.brightcove.com/>
  5. * Available under Apache License Version 2.0
  6. * <https://github.com/videojs/video.js/blob/main/LICENSE>
  7. *
  8. * Includes vtt.js <https://github.com/mozilla/vtt.js>
  9. * Available under Apache License Version 2.0
  10. * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
  11. */
  12. 'use strict';
  13. var window$1 = require('global/window');
  14. var document = require('global/document');
  15. var keycode = require('keycode');
  16. var safeParseTuple = require('safe-json-parse/tuple');
  17. var XHR = require('@videojs/xhr');
  18. var vtt = require('videojs-vtt.js');
  19. var _resolveUrl = require('@videojs/vhs-utils/cjs/resolve-url.js');
  20. var _extends = require('@babel/runtime/helpers/extends');
  21. var m3u8Parser = require('m3u8-parser');
  22. var codecs_js = require('@videojs/vhs-utils/cjs/codecs.js');
  23. var mediaTypes_js = require('@videojs/vhs-utils/cjs/media-types.js');
  24. var byteHelpers = require('@videojs/vhs-utils/cjs/byte-helpers');
  25. var mpdParser = require('mpd-parser');
  26. var parseSidx = require('mux.js/lib/tools/parse-sidx');
  27. var id3Helpers = require('@videojs/vhs-utils/cjs/id3-helpers');
  28. var containers = require('@videojs/vhs-utils/cjs/containers');
  29. var clock = require('mux.js/lib/utils/clock');
  30. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  31. var window__default = /*#__PURE__*/_interopDefaultLegacy(window$1);
  32. var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
  33. var keycode__default = /*#__PURE__*/_interopDefaultLegacy(keycode);
  34. var safeParseTuple__default = /*#__PURE__*/_interopDefaultLegacy(safeParseTuple);
  35. var XHR__default = /*#__PURE__*/_interopDefaultLegacy(XHR);
  36. var vtt__default = /*#__PURE__*/_interopDefaultLegacy(vtt);
  37. var _resolveUrl__default = /*#__PURE__*/_interopDefaultLegacy(_resolveUrl);
  38. var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);
  39. var parseSidx__default = /*#__PURE__*/_interopDefaultLegacy(parseSidx);
  40. var version$6 = "8.3.0";
  41. /**
  42. * An Object that contains lifecycle hooks as keys which point to an array
  43. * of functions that are run when a lifecycle is triggered
  44. *
  45. * @private
  46. */
  47. const hooks_ = {};
  48. /**
  49. * Get a list of hooks for a specific lifecycle
  50. *
  51. * @param {string} type
  52. * the lifecycle to get hooks from
  53. *
  54. * @param {Function|Function[]} [fn]
  55. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  56. *
  57. * @return {Array}
  58. * an array of hooks, or an empty array if there are none.
  59. */
  60. const hooks = function (type, fn) {
  61. hooks_[type] = hooks_[type] || [];
  62. if (fn) {
  63. hooks_[type] = hooks_[type].concat(fn);
  64. }
  65. return hooks_[type];
  66. };
  67. /**
  68. * Add a function hook to a specific videojs lifecycle.
  69. *
  70. * @param {string} type
  71. * the lifecycle to hook the function to.
  72. *
  73. * @param {Function|Function[]}
  74. * The function or array of functions to attach.
  75. */
  76. const hook = function (type, fn) {
  77. hooks(type, fn);
  78. };
  79. /**
  80. * Remove a hook from a specific videojs lifecycle.
  81. *
  82. * @param {string} type
  83. * the lifecycle that the function hooked to
  84. *
  85. * @param {Function} fn
  86. * The hooked function to remove
  87. *
  88. * @return {boolean}
  89. * The function that was removed or undef
  90. */
  91. const removeHook = function (type, fn) {
  92. const index = hooks(type).indexOf(fn);
  93. if (index <= -1) {
  94. return false;
  95. }
  96. hooks_[type] = hooks_[type].slice();
  97. hooks_[type].splice(index, 1);
  98. return true;
  99. };
  100. /**
  101. * Add a function hook that will only run once to a specific videojs lifecycle.
  102. *
  103. * @param {string} type
  104. * the lifecycle to hook the function to.
  105. *
  106. * @param {Function|Function[]}
  107. * The function or array of functions to attach.
  108. */
  109. const hookOnce = function (type, fn) {
  110. hooks(type, [].concat(fn).map(original => {
  111. const wrapper = (...args) => {
  112. removeHook(type, wrapper);
  113. return original(...args);
  114. };
  115. return wrapper;
  116. }));
  117. };
  118. /**
  119. * @file fullscreen-api.js
  120. * @module fullscreen-api
  121. */
  122. /**
  123. * Store the browser-specific methods for the fullscreen API.
  124. *
  125. * @type {Object}
  126. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  127. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  128. */
  129. const FullscreenApi = {
  130. prefixed: true
  131. };
  132. // browser API methods
  133. const apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'],
  134. // WebKit
  135. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'],
  136. // Mozilla
  137. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'],
  138. // Microsoft
  139. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  140. const specApi = apiMap[0];
  141. let browserApi;
  142. // determine the supported set of functions
  143. for (let i = 0; i < apiMap.length; i++) {
  144. // check for exitFullscreen function
  145. if (apiMap[i][1] in document__default["default"]) {
  146. browserApi = apiMap[i];
  147. break;
  148. }
  149. }
  150. // map the browser API names to the spec API names
  151. if (browserApi) {
  152. for (let i = 0; i < browserApi.length; i++) {
  153. FullscreenApi[specApi[i]] = browserApi[i];
  154. }
  155. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  156. }
  157. /**
  158. * @file create-logger.js
  159. * @module create-logger
  160. */
  161. // This is the private tracking variable for the logging history.
  162. let history = [];
  163. /**
  164. * Log messages to the console and history based on the type of message
  165. *
  166. * @private
  167. * @param {string} type
  168. * The name of the console method to use.
  169. *
  170. * @param {Array} args
  171. * The arguments to be passed to the matching console method.
  172. */
  173. const LogByTypeFactory = (name, log) => (type, level, args) => {
  174. const lvl = log.levels[level];
  175. const lvlRegExp = new RegExp(`^(${lvl})$`);
  176. if (type !== 'log') {
  177. // Add the type to the front of the message when it's not "log".
  178. args.unshift(type.toUpperCase() + ':');
  179. }
  180. // Add console prefix after adding to history.
  181. args.unshift(name + ':');
  182. // Add a clone of the args at this point to history.
  183. if (history) {
  184. history.push([].concat(args));
  185. // only store 1000 history entries
  186. const splice = history.length - 1000;
  187. history.splice(0, splice > 0 ? splice : 0);
  188. }
  189. // If there's no console then don't try to output messages, but they will
  190. // still be stored in history.
  191. if (!window__default["default"].console) {
  192. return;
  193. }
  194. // Was setting these once outside of this function, but containing them
  195. // in the function makes it easier to test cases where console doesn't exist
  196. // when the module is executed.
  197. let fn = window__default["default"].console[type];
  198. if (!fn && type === 'debug') {
  199. // Certain browsers don't have support for console.debug. For those, we
  200. // should default to the closest comparable log.
  201. fn = window__default["default"].console.info || window__default["default"].console.log;
  202. }
  203. // Bail out if there's no console or if this type is not allowed by the
  204. // current logging level.
  205. if (!fn || !lvl || !lvlRegExp.test(type)) {
  206. return;
  207. }
  208. fn[Array.isArray(args) ? 'apply' : 'call'](window__default["default"].console, args);
  209. };
  210. function createLogger$1(name) {
  211. // This is the private tracking variable for logging level.
  212. let level = 'info';
  213. // the curried logByType bound to the specific log and history
  214. let logByType;
  215. /**
  216. * Logs plain debug messages. Similar to `console.log`.
  217. *
  218. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  219. * of our JSDoc template, we cannot properly document this as both a function
  220. * and a namespace, so its function signature is documented here.
  221. *
  222. * #### Arguments
  223. * ##### *args
  224. * *[]
  225. *
  226. * Any combination of values that could be passed to `console.log()`.
  227. *
  228. * #### Return Value
  229. *
  230. * `undefined`
  231. *
  232. * @namespace
  233. * @param {...*} args
  234. * One or more messages or objects that should be logged.
  235. */
  236. const log = function (...args) {
  237. logByType('log', level, args);
  238. };
  239. // This is the logByType helper that the logging methods below use
  240. logByType = LogByTypeFactory(name, log);
  241. /**
  242. * Create a new sublogger which chains the old name to the new name.
  243. *
  244. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  245. * ```js
  246. * mylogger('foo');
  247. * // > VIDEOJS: player: foo
  248. * ```
  249. *
  250. * @param {string} name
  251. * The name to add call the new logger
  252. * @return {Object}
  253. */
  254. log.createLogger = subname => createLogger$1(name + ': ' + subname);
  255. /**
  256. * Enumeration of available logging levels, where the keys are the level names
  257. * and the values are `|`-separated strings containing logging methods allowed
  258. * in that logging level. These strings are used to create a regular expression
  259. * matching the function name being called.
  260. *
  261. * Levels provided by Video.js are:
  262. *
  263. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  264. * this effect. The most restrictive.
  265. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  266. * `log.warn`, and `log.error`).
  267. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  268. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  269. * - `warn`: Matches `log.warn` and `log.error` calls.
  270. * - `error`: Matches only `log.error` calls.
  271. *
  272. * @type {Object}
  273. */
  274. log.levels = {
  275. all: 'debug|log|warn|error',
  276. off: '',
  277. debug: 'debug|log|warn|error',
  278. info: 'log|warn|error',
  279. warn: 'warn|error',
  280. error: 'error',
  281. DEFAULT: level
  282. };
  283. /**
  284. * Get or set the current logging level.
  285. *
  286. * If a string matching a key from {@link module:log.levels} is provided, acts
  287. * as a setter.
  288. *
  289. * @param {string} [lvl]
  290. * Pass a valid level to set a new logging level.
  291. *
  292. * @return {string}
  293. * The current logging level.
  294. */
  295. log.level = lvl => {
  296. if (typeof lvl === 'string') {
  297. if (!log.levels.hasOwnProperty(lvl)) {
  298. throw new Error(`"${lvl}" in not a valid log level`);
  299. }
  300. level = lvl;
  301. }
  302. return level;
  303. };
  304. /**
  305. * Returns an array containing everything that has been logged to the history.
  306. *
  307. * This array is a shallow clone of the internal history record. However, its
  308. * contents are _not_ cloned; so, mutating objects inside this array will
  309. * mutate them in history.
  310. *
  311. * @return {Array}
  312. */
  313. log.history = () => history ? [].concat(history) : [];
  314. /**
  315. * Allows you to filter the history by the given logger name
  316. *
  317. * @param {string} fname
  318. * The name to filter by
  319. *
  320. * @return {Array}
  321. * The filtered list to return
  322. */
  323. log.history.filter = fname => {
  324. return (history || []).filter(historyItem => {
  325. // if the first item in each historyItem includes `fname`, then it's a match
  326. return new RegExp(`.*${fname}.*`).test(historyItem[0]);
  327. });
  328. };
  329. /**
  330. * Clears the internal history tracking, but does not prevent further history
  331. * tracking.
  332. */
  333. log.history.clear = () => {
  334. if (history) {
  335. history.length = 0;
  336. }
  337. };
  338. /**
  339. * Disable history tracking if it is currently enabled.
  340. */
  341. log.history.disable = () => {
  342. if (history !== null) {
  343. history.length = 0;
  344. history = null;
  345. }
  346. };
  347. /**
  348. * Enable history tracking if it is currently disabled.
  349. */
  350. log.history.enable = () => {
  351. if (history === null) {
  352. history = [];
  353. }
  354. };
  355. /**
  356. * Logs error messages. Similar to `console.error`.
  357. *
  358. * @param {...*} args
  359. * One or more messages or objects that should be logged as an error
  360. */
  361. log.error = (...args) => logByType('error', level, args);
  362. /**
  363. * Logs warning messages. Similar to `console.warn`.
  364. *
  365. * @param {...*} args
  366. * One or more messages or objects that should be logged as a warning.
  367. */
  368. log.warn = (...args) => logByType('warn', level, args);
  369. /**
  370. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  371. * log if `console.debug` is not available
  372. *
  373. * @param {...*} args
  374. * One or more messages or objects that should be logged as debug.
  375. */
  376. log.debug = (...args) => logByType('debug', level, args);
  377. return log;
  378. }
  379. /**
  380. * @file log.js
  381. * @module log
  382. */
  383. const log$1 = createLogger$1('VIDEOJS');
  384. const createLogger = log$1.createLogger;
  385. /**
  386. * @file obj.js
  387. * @module obj
  388. */
  389. /**
  390. * @callback obj:EachCallback
  391. *
  392. * @param {*} value
  393. * The current key for the object that is being iterated over.
  394. *
  395. * @param {string} key
  396. * The current key-value for object that is being iterated over
  397. */
  398. /**
  399. * @callback obj:ReduceCallback
  400. *
  401. * @param {*} accum
  402. * The value that is accumulating over the reduce loop.
  403. *
  404. * @param {*} value
  405. * The current key for the object that is being iterated over.
  406. *
  407. * @param {string} key
  408. * The current key-value for object that is being iterated over
  409. *
  410. * @return {*}
  411. * The new accumulated value.
  412. */
  413. const toString = Object.prototype.toString;
  414. /**
  415. * Get the keys of an Object
  416. *
  417. * @param {Object}
  418. * The Object to get the keys from
  419. *
  420. * @return {string[]}
  421. * An array of the keys from the object. Returns an empty array if the
  422. * object passed in was invalid or had no keys.
  423. *
  424. * @private
  425. */
  426. const keys = function (object) {
  427. return isObject(object) ? Object.keys(object) : [];
  428. };
  429. /**
  430. * Array-like iteration for objects.
  431. *
  432. * @param {Object} object
  433. * The object to iterate over
  434. *
  435. * @param {obj:EachCallback} fn
  436. * The callback function which is called for each key in the object.
  437. */
  438. function each(object, fn) {
  439. keys(object).forEach(key => fn(object[key], key));
  440. }
  441. /**
  442. * Array-like reduce for objects.
  443. *
  444. * @param {Object} object
  445. * The Object that you want to reduce.
  446. *
  447. * @param {Function} fn
  448. * A callback function which is called for each key in the object. It
  449. * receives the accumulated value and the per-iteration value and key
  450. * as arguments.
  451. *
  452. * @param {*} [initial = 0]
  453. * Starting value
  454. *
  455. * @return {*}
  456. * The final accumulated value.
  457. */
  458. function reduce(object, fn, initial = 0) {
  459. return keys(object).reduce((accum, key) => fn(accum, object[key], key), initial);
  460. }
  461. /**
  462. * Returns whether a value is an object of any kind - including DOM nodes,
  463. * arrays, regular expressions, etc. Not functions, though.
  464. *
  465. * This avoids the gotcha where using `typeof` on a `null` value
  466. * results in `'object'`.
  467. *
  468. * @param {Object} value
  469. * @return {boolean}
  470. */
  471. function isObject(value) {
  472. return !!value && typeof value === 'object';
  473. }
  474. /**
  475. * Returns whether an object appears to be a "plain" object - that is, a
  476. * direct instance of `Object`.
  477. *
  478. * @param {Object} value
  479. * @return {boolean}
  480. */
  481. function isPlain(value) {
  482. return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;
  483. }
  484. /**
  485. * Merge two objects recursively.
  486. *
  487. * Performs a deep merge like
  488. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  489. * plain objects (not arrays, elements, or anything else).
  490. *
  491. * Non-plain object values will be copied directly from the right-most
  492. * argument.
  493. *
  494. * @param {Object[]} sources
  495. * One or more objects to merge into a new object.
  496. *
  497. * @return {Object}
  498. * A new object that is the merged result of all sources.
  499. */
  500. function merge$1(...sources) {
  501. const result = {};
  502. sources.forEach(source => {
  503. if (!source) {
  504. return;
  505. }
  506. each(source, (value, key) => {
  507. if (!isPlain(value)) {
  508. result[key] = value;
  509. return;
  510. }
  511. if (!isPlain(result[key])) {
  512. result[key] = {};
  513. }
  514. result[key] = merge$1(result[key], value);
  515. });
  516. });
  517. return result;
  518. }
  519. /**
  520. * Object.defineProperty but "lazy", which means that the value is only set after
  521. * it is retrieved the first time, rather than being set right away.
  522. *
  523. * @param {Object} obj the object to set the property on
  524. * @param {string} key the key for the property to set
  525. * @param {Function} getValue the function used to get the value when it is needed.
  526. * @param {boolean} setter whether a setter should be allowed or not
  527. */
  528. function defineLazyProperty(obj, key, getValue, setter = true) {
  529. const set = value => Object.defineProperty(obj, key, {
  530. value,
  531. enumerable: true,
  532. writable: true
  533. });
  534. const options = {
  535. configurable: true,
  536. enumerable: true,
  537. get() {
  538. const value = getValue();
  539. set(value);
  540. return value;
  541. }
  542. };
  543. if (setter) {
  544. options.set = set;
  545. }
  546. return Object.defineProperty(obj, key, options);
  547. }
  548. var Obj = /*#__PURE__*/Object.freeze({
  549. __proto__: null,
  550. each: each,
  551. reduce: reduce,
  552. isObject: isObject,
  553. isPlain: isPlain,
  554. merge: merge$1,
  555. defineLazyProperty: defineLazyProperty
  556. });
  557. /**
  558. * @file browser.js
  559. * @module browser
  560. */
  561. /**
  562. * Whether or not this device is an iPod.
  563. *
  564. * @static
  565. * @type {Boolean}
  566. */
  567. let IS_IPOD = false;
  568. /**
  569. * The detected iOS version - or `null`.
  570. *
  571. * @static
  572. * @type {string|null}
  573. */
  574. let IOS_VERSION = null;
  575. /**
  576. * Whether or not this is an Android device.
  577. *
  578. * @static
  579. * @type {Boolean}
  580. */
  581. let IS_ANDROID = false;
  582. /**
  583. * The detected Android version - or `null` if not Android or indeterminable.
  584. *
  585. * @static
  586. * @type {number|string|null}
  587. */
  588. let ANDROID_VERSION;
  589. /**
  590. * Whether or not this is Mozilla Firefox.
  591. *
  592. * @static
  593. * @type {Boolean}
  594. */
  595. let IS_FIREFOX = false;
  596. /**
  597. * Whether or not this is Microsoft Edge.
  598. *
  599. * @static
  600. * @type {Boolean}
  601. */
  602. let IS_EDGE = false;
  603. /**
  604. * Whether or not this is any Chromium Browser
  605. *
  606. * @static
  607. * @type {Boolean}
  608. */
  609. let IS_CHROMIUM = false;
  610. /**
  611. * Whether or not this is any Chromium browser that is not Edge.
  612. *
  613. * This will also be `true` for Chrome on iOS, which will have different support
  614. * as it is actually Safari under the hood.
  615. *
  616. * Deprecated, as the behaviour to not match Edge was to prevent Legacy Edge's UA matching.
  617. * IS_CHROMIUM should be used instead.
  618. * "Chromium but not Edge" could be explicitly tested with IS_CHROMIUM && !IS_EDGE
  619. *
  620. * @static
  621. * @deprecated
  622. * @type {Boolean}
  623. */
  624. let IS_CHROME = false;
  625. /**
  626. * The detected Chromium version - or `null`.
  627. *
  628. * @static
  629. * @type {number|null}
  630. */
  631. let CHROMIUM_VERSION = null;
  632. /**
  633. * The detected Google Chrome version - or `null`.
  634. * This has always been the _Chromium_ version, i.e. would return on Chromium Edge.
  635. * Deprecated, use CHROMIUM_VERSION instead.
  636. *
  637. * @static
  638. * @deprecated
  639. * @type {number|null}
  640. */
  641. let CHROME_VERSION = null;
  642. /**
  643. * The detected Internet Explorer version - or `null`.
  644. *
  645. * @static
  646. * @deprecated
  647. * @type {number|null}
  648. */
  649. let IE_VERSION = null;
  650. /**
  651. * Whether or not this is desktop Safari.
  652. *
  653. * @static
  654. * @type {Boolean}
  655. */
  656. let IS_SAFARI = false;
  657. /**
  658. * Whether or not this is a Windows machine.
  659. *
  660. * @static
  661. * @type {Boolean}
  662. */
  663. let IS_WINDOWS = false;
  664. /**
  665. * Whether or not this device is an iPad.
  666. *
  667. * @static
  668. * @type {Boolean}
  669. */
  670. let IS_IPAD = false;
  671. /**
  672. * Whether or not this device is an iPhone.
  673. *
  674. * @static
  675. * @type {Boolean}
  676. */
  677. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  678. // to identify iPhones, we need to exclude iPads.
  679. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  680. let IS_IPHONE = false;
  681. /**
  682. * Whether or not this device is touch-enabled.
  683. *
  684. * @static
  685. * @const
  686. * @type {Boolean}
  687. */
  688. const TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window__default["default"] || window__default["default"].navigator.maxTouchPoints || window__default["default"].DocumentTouch && window__default["default"].document instanceof window__default["default"].DocumentTouch));
  689. const UAD = window__default["default"].navigator && window__default["default"].navigator.userAgentData;
  690. if (UAD) {
  691. // If userAgentData is present, use it instead of userAgent to avoid warnings
  692. // Currently only implemented on Chromium
  693. // userAgentData does not expose Android version, so ANDROID_VERSION remains `null`
  694. IS_ANDROID = UAD.platform === 'Android';
  695. IS_EDGE = Boolean(UAD.brands.find(b => b.brand === 'Microsoft Edge'));
  696. IS_CHROMIUM = Boolean(UAD.brands.find(b => b.brand === 'Chromium'));
  697. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  698. CHROMIUM_VERSION = CHROME_VERSION = (UAD.brands.find(b => b.brand === 'Chromium') || {}).version || null;
  699. IS_WINDOWS = UAD.platform === 'Windows';
  700. }
  701. // If the browser is not Chromium, either userAgentData is not present which could be an old Chromium browser,
  702. // or it's a browser that has added userAgentData since that we don't have tests for yet. In either case,
  703. // the checks need to be made agiainst the regular userAgent string.
  704. if (!IS_CHROMIUM) {
  705. const USER_AGENT = window__default["default"].navigator && window__default["default"].navigator.userAgent || '';
  706. IS_IPOD = /iPod/i.test(USER_AGENT);
  707. IOS_VERSION = function () {
  708. const match = USER_AGENT.match(/OS (\d+)_/i);
  709. if (match && match[1]) {
  710. return match[1];
  711. }
  712. return null;
  713. }();
  714. IS_ANDROID = /Android/i.test(USER_AGENT);
  715. ANDROID_VERSION = function () {
  716. // This matches Android Major.Minor.Patch versions
  717. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  718. const match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  719. if (!match) {
  720. return null;
  721. }
  722. const major = match[1] && parseFloat(match[1]);
  723. const minor = match[2] && parseFloat(match[2]);
  724. if (major && minor) {
  725. return parseFloat(match[1] + '.' + match[2]);
  726. } else if (major) {
  727. return major;
  728. }
  729. return null;
  730. }();
  731. IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  732. IS_EDGE = /Edg/i.test(USER_AGENT);
  733. IS_CHROMIUM = /Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT);
  734. IS_CHROME = !IS_EDGE && IS_CHROMIUM;
  735. CHROMIUM_VERSION = CHROME_VERSION = function () {
  736. const match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  737. if (match && match[2]) {
  738. return parseFloat(match[2]);
  739. }
  740. return null;
  741. }();
  742. IE_VERSION = function () {
  743. const result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  744. let version = result && parseFloat(result[1]);
  745. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  746. // IE 11 has a different user agent string than other IE versions
  747. version = 11.0;
  748. }
  749. return version;
  750. }();
  751. IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  752. IS_WINDOWS = /Windows/i.test(USER_AGENT);
  753. IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  754. IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  755. }
  756. /**
  757. * Whether or not this is an iOS device.
  758. *
  759. * @static
  760. * @const
  761. * @type {Boolean}
  762. */
  763. const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  764. /**
  765. * Whether or not this is any flavor of Safari - including iOS.
  766. *
  767. * @static
  768. * @const
  769. * @type {Boolean}
  770. */
  771. const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  772. var browser = /*#__PURE__*/Object.freeze({
  773. __proto__: null,
  774. get IS_IPOD () { return IS_IPOD; },
  775. get IOS_VERSION () { return IOS_VERSION; },
  776. get IS_ANDROID () { return IS_ANDROID; },
  777. get ANDROID_VERSION () { return ANDROID_VERSION; },
  778. get IS_FIREFOX () { return IS_FIREFOX; },
  779. get IS_EDGE () { return IS_EDGE; },
  780. get IS_CHROMIUM () { return IS_CHROMIUM; },
  781. get IS_CHROME () { return IS_CHROME; },
  782. get CHROMIUM_VERSION () { return CHROMIUM_VERSION; },
  783. get CHROME_VERSION () { return CHROME_VERSION; },
  784. get IE_VERSION () { return IE_VERSION; },
  785. get IS_SAFARI () { return IS_SAFARI; },
  786. get IS_WINDOWS () { return IS_WINDOWS; },
  787. get IS_IPAD () { return IS_IPAD; },
  788. get IS_IPHONE () { return IS_IPHONE; },
  789. TOUCH_ENABLED: TOUCH_ENABLED,
  790. IS_IOS: IS_IOS,
  791. IS_ANY_SAFARI: IS_ANY_SAFARI
  792. });
  793. /**
  794. * @file dom.js
  795. * @module dom
  796. */
  797. /**
  798. * Detect if a value is a string with any non-whitespace characters.
  799. *
  800. * @private
  801. * @param {string} str
  802. * The string to check
  803. *
  804. * @return {boolean}
  805. * Will be `true` if the string is non-blank, `false` otherwise.
  806. *
  807. */
  808. function isNonBlankString(str) {
  809. // we use str.trim as it will trim any whitespace characters
  810. // from the front or back of non-whitespace characters. aka
  811. // Any string that contains non-whitespace characters will
  812. // still contain them after `trim` but whitespace only strings
  813. // will have a length of 0, failing this check.
  814. return typeof str === 'string' && Boolean(str.trim());
  815. }
  816. /**
  817. * Throws an error if the passed string has whitespace. This is used by
  818. * class methods to be relatively consistent with the classList API.
  819. *
  820. * @private
  821. * @param {string} str
  822. * The string to check for whitespace.
  823. *
  824. * @throws {Error}
  825. * Throws an error if there is whitespace in the string.
  826. */
  827. function throwIfWhitespace(str) {
  828. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  829. if (str.indexOf(' ') >= 0) {
  830. throw new Error('class has illegal whitespace characters');
  831. }
  832. }
  833. /**
  834. * Whether the current DOM interface appears to be real (i.e. not simulated).
  835. *
  836. * @return {boolean}
  837. * Will be `true` if the DOM appears to be real, `false` otherwise.
  838. */
  839. function isReal() {
  840. // Both document and window will never be undefined thanks to `global`.
  841. return document__default["default"] === window__default["default"].document;
  842. }
  843. /**
  844. * Determines, via duck typing, whether or not a value is a DOM element.
  845. *
  846. * @param {*} value
  847. * The value to check.
  848. *
  849. * @return {boolean}
  850. * Will be `true` if the value is a DOM element, `false` otherwise.
  851. */
  852. function isEl(value) {
  853. return isObject(value) && value.nodeType === 1;
  854. }
  855. /**
  856. * Determines if the current DOM is embedded in an iframe.
  857. *
  858. * @return {boolean}
  859. * Will be `true` if the DOM is embedded in an iframe, `false`
  860. * otherwise.
  861. */
  862. function isInFrame() {
  863. // We need a try/catch here because Safari will throw errors when attempting
  864. // to get either `parent` or `self`
  865. try {
  866. return window__default["default"].parent !== window__default["default"].self;
  867. } catch (x) {
  868. return true;
  869. }
  870. }
  871. /**
  872. * Creates functions to query the DOM using a given method.
  873. *
  874. * @private
  875. * @param {string} method
  876. * The method to create the query with.
  877. *
  878. * @return {Function}
  879. * The query method
  880. */
  881. function createQuerier(method) {
  882. return function (selector, context) {
  883. if (!isNonBlankString(selector)) {
  884. return document__default["default"][method](null);
  885. }
  886. if (isNonBlankString(context)) {
  887. context = document__default["default"].querySelector(context);
  888. }
  889. const ctx = isEl(context) ? context : document__default["default"];
  890. return ctx[method] && ctx[method](selector);
  891. };
  892. }
  893. /**
  894. * Creates an element and applies properties, attributes, and inserts content.
  895. *
  896. * @param {string} [tagName='div']
  897. * Name of tag to be created.
  898. *
  899. * @param {Object} [properties={}]
  900. * Element properties to be applied.
  901. *
  902. * @param {Object} [attributes={}]
  903. * Element attributes to be applied.
  904. *
  905. * @param {ContentDescriptor} [content]
  906. * A content descriptor object.
  907. *
  908. * @return {Element}
  909. * The element that was created.
  910. */
  911. function createEl(tagName = 'div', properties = {}, attributes = {}, content) {
  912. const el = document__default["default"].createElement(tagName);
  913. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  914. const val = properties[propName];
  915. // Handle textContent since it's not supported everywhere and we have a
  916. // method for it.
  917. if (propName === 'textContent') {
  918. textContent(el, val);
  919. } else if (el[propName] !== val || propName === 'tabIndex') {
  920. el[propName] = val;
  921. }
  922. });
  923. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  924. el.setAttribute(attrName, attributes[attrName]);
  925. });
  926. if (content) {
  927. appendContent(el, content);
  928. }
  929. return el;
  930. }
  931. /**
  932. * Injects text into an element, replacing any existing contents entirely.
  933. *
  934. * @param {Element} el
  935. * The element to add text content into
  936. *
  937. * @param {string} text
  938. * The text content to add.
  939. *
  940. * @return {Element}
  941. * The element with added text content.
  942. */
  943. function textContent(el, text) {
  944. if (typeof el.textContent === 'undefined') {
  945. el.innerText = text;
  946. } else {
  947. el.textContent = text;
  948. }
  949. return el;
  950. }
  951. /**
  952. * Insert an element as the first child node of another
  953. *
  954. * @param {Element} child
  955. * Element to insert
  956. *
  957. * @param {Element} parent
  958. * Element to insert child into
  959. */
  960. function prependTo(child, parent) {
  961. if (parent.firstChild) {
  962. parent.insertBefore(child, parent.firstChild);
  963. } else {
  964. parent.appendChild(child);
  965. }
  966. }
  967. /**
  968. * Check if an element has a class name.
  969. *
  970. * @param {Element} element
  971. * Element to check
  972. *
  973. * @param {string} classToCheck
  974. * Class name to check for
  975. *
  976. * @return {boolean}
  977. * Will be `true` if the element has a class, `false` otherwise.
  978. *
  979. * @throws {Error}
  980. * Throws an error if `classToCheck` has white space.
  981. */
  982. function hasClass(element, classToCheck) {
  983. throwIfWhitespace(classToCheck);
  984. return element.classList.contains(classToCheck);
  985. }
  986. /**
  987. * Add a class name to an element.
  988. *
  989. * @param {Element} element
  990. * Element to add class name to.
  991. *
  992. * @param {...string} classesToAdd
  993. * One or more class name to add.
  994. *
  995. * @return {Element}
  996. * The DOM element with the added class name.
  997. */
  998. function addClass(element, ...classesToAdd) {
  999. element.classList.add(...classesToAdd.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  1000. return element;
  1001. }
  1002. /**
  1003. * Remove a class name from an element.
  1004. *
  1005. * @param {Element} element
  1006. * Element to remove a class name from.
  1007. *
  1008. * @param {...string} classesToRemove
  1009. * One or more class name to remove.
  1010. *
  1011. * @return {Element}
  1012. * The DOM element with class name removed.
  1013. */
  1014. function removeClass(element, ...classesToRemove) {
  1015. // Protect in case the player gets disposed
  1016. if (!element) {
  1017. log$1.warn("removeClass was called with an element that doesn't exist");
  1018. return null;
  1019. }
  1020. element.classList.remove(...classesToRemove.reduce((prev, current) => prev.concat(current.split(/\s+/)), []));
  1021. return element;
  1022. }
  1023. /**
  1024. * The callback definition for toggleClass.
  1025. *
  1026. * @callback module:dom~PredicateCallback
  1027. * @param {Element} element
  1028. * The DOM element of the Component.
  1029. *
  1030. * @param {string} classToToggle
  1031. * The `className` that wants to be toggled
  1032. *
  1033. * @return {boolean|undefined}
  1034. * If `true` is returned, the `classToToggle` will be added to the
  1035. * `element`. If `false`, the `classToToggle` will be removed from
  1036. * the `element`. If `undefined`, the callback will be ignored.
  1037. */
  1038. /**
  1039. * Adds or removes a class name to/from an element depending on an optional
  1040. * condition or the presence/absence of the class name.
  1041. *
  1042. * @param {Element} element
  1043. * The element to toggle a class name on.
  1044. *
  1045. * @param {string} classToToggle
  1046. * The class that should be toggled.
  1047. *
  1048. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1049. * See the return value for {@link module:dom~PredicateCallback}
  1050. *
  1051. * @return {Element}
  1052. * The element with a class that has been toggled.
  1053. */
  1054. function toggleClass(element, classToToggle, predicate) {
  1055. if (typeof predicate === 'function') {
  1056. predicate = predicate(element, classToToggle);
  1057. }
  1058. if (typeof predicate !== 'boolean') {
  1059. predicate = undefined;
  1060. }
  1061. classToToggle.split(/\s+/).forEach(className => element.classList.toggle(className, predicate));
  1062. return element;
  1063. }
  1064. /**
  1065. * Apply attributes to an HTML element.
  1066. *
  1067. * @param {Element} el
  1068. * Element to add attributes to.
  1069. *
  1070. * @param {Object} [attributes]
  1071. * Attributes to be applied.
  1072. */
  1073. function setAttributes(el, attributes) {
  1074. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1075. const attrValue = attributes[attrName];
  1076. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1077. el.removeAttribute(attrName);
  1078. } else {
  1079. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1080. }
  1081. });
  1082. }
  1083. /**
  1084. * Get an element's attribute values, as defined on the HTML tag.
  1085. *
  1086. * Attributes are not the same as properties. They're defined on the tag
  1087. * or with setAttribute.
  1088. *
  1089. * @param {Element} tag
  1090. * Element from which to get tag attributes.
  1091. *
  1092. * @return {Object}
  1093. * All attributes of the element. Boolean attributes will be `true` or
  1094. * `false`, others will be strings.
  1095. */
  1096. function getAttributes(tag) {
  1097. const obj = {};
  1098. // known boolean attributes
  1099. // we can check for matching boolean properties, but not all browsers
  1100. // and not all tags know about these attributes, so, we still want to check them manually
  1101. const knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1102. if (tag && tag.attributes && tag.attributes.length > 0) {
  1103. const attrs = tag.attributes;
  1104. for (let i = attrs.length - 1; i >= 0; i--) {
  1105. const attrName = attrs[i].name;
  1106. let attrVal = attrs[i].value;
  1107. // check for known booleans
  1108. // the matching element property will return a value for typeof
  1109. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1110. // the value of an included boolean attribute is typically an empty
  1111. // string ('') which would equal false if we just check for a false value.
  1112. // we also don't want support bad code like autoplay='false'
  1113. attrVal = attrVal !== null ? true : false;
  1114. }
  1115. obj[attrName] = attrVal;
  1116. }
  1117. }
  1118. return obj;
  1119. }
  1120. /**
  1121. * Get the value of an element's attribute.
  1122. *
  1123. * @param {Element} el
  1124. * A DOM element.
  1125. *
  1126. * @param {string} attribute
  1127. * Attribute to get the value of.
  1128. *
  1129. * @return {string}
  1130. * The value of the attribute.
  1131. */
  1132. function getAttribute(el, attribute) {
  1133. return el.getAttribute(attribute);
  1134. }
  1135. /**
  1136. * Set the value of an element's attribute.
  1137. *
  1138. * @param {Element} el
  1139. * A DOM element.
  1140. *
  1141. * @param {string} attribute
  1142. * Attribute to set.
  1143. *
  1144. * @param {string} value
  1145. * Value to set the attribute to.
  1146. */
  1147. function setAttribute(el, attribute, value) {
  1148. el.setAttribute(attribute, value);
  1149. }
  1150. /**
  1151. * Remove an element's attribute.
  1152. *
  1153. * @param {Element} el
  1154. * A DOM element.
  1155. *
  1156. * @param {string} attribute
  1157. * Attribute to remove.
  1158. */
  1159. function removeAttribute(el, attribute) {
  1160. el.removeAttribute(attribute);
  1161. }
  1162. /**
  1163. * Attempt to block the ability to select text.
  1164. */
  1165. function blockTextSelection() {
  1166. document__default["default"].body.focus();
  1167. document__default["default"].onselectstart = function () {
  1168. return false;
  1169. };
  1170. }
  1171. /**
  1172. * Turn off text selection blocking.
  1173. */
  1174. function unblockTextSelection() {
  1175. document__default["default"].onselectstart = function () {
  1176. return true;
  1177. };
  1178. }
  1179. /**
  1180. * Identical to the native `getBoundingClientRect` function, but ensures that
  1181. * the method is supported at all (it is in all browsers we claim to support)
  1182. * and that the element is in the DOM before continuing.
  1183. *
  1184. * This wrapper function also shims properties which are not provided by some
  1185. * older browsers (namely, IE8).
  1186. *
  1187. * Additionally, some browsers do not support adding properties to a
  1188. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1189. * properties (except `x` and `y` which are not widely supported). This helps
  1190. * avoid implementations where keys are non-enumerable.
  1191. *
  1192. * @param {Element} el
  1193. * Element whose `ClientRect` we want to calculate.
  1194. *
  1195. * @return {Object|undefined}
  1196. * Always returns a plain object - or `undefined` if it cannot.
  1197. */
  1198. function getBoundingClientRect(el) {
  1199. if (el && el.getBoundingClientRect && el.parentNode) {
  1200. const rect = el.getBoundingClientRect();
  1201. const result = {};
  1202. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(k => {
  1203. if (rect[k] !== undefined) {
  1204. result[k] = rect[k];
  1205. }
  1206. });
  1207. if (!result.height) {
  1208. result.height = parseFloat(computedStyle(el, 'height'));
  1209. }
  1210. if (!result.width) {
  1211. result.width = parseFloat(computedStyle(el, 'width'));
  1212. }
  1213. return result;
  1214. }
  1215. }
  1216. /**
  1217. * Represents the position of a DOM element on the page.
  1218. *
  1219. * @typedef {Object} module:dom~Position
  1220. *
  1221. * @property {number} left
  1222. * Pixels to the left.
  1223. *
  1224. * @property {number} top
  1225. * Pixels from the top.
  1226. */
  1227. /**
  1228. * Get the position of an element in the DOM.
  1229. *
  1230. * Uses `getBoundingClientRect` technique from John Resig.
  1231. *
  1232. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1233. *
  1234. * @param {Element} el
  1235. * Element from which to get offset.
  1236. *
  1237. * @return {module:dom~Position}
  1238. * The position of the element that was passed in.
  1239. */
  1240. function findPosition(el) {
  1241. if (!el || el && !el.offsetParent) {
  1242. return {
  1243. left: 0,
  1244. top: 0,
  1245. width: 0,
  1246. height: 0
  1247. };
  1248. }
  1249. const width = el.offsetWidth;
  1250. const height = el.offsetHeight;
  1251. let left = 0;
  1252. let top = 0;
  1253. while (el.offsetParent && el !== document__default["default"][FullscreenApi.fullscreenElement]) {
  1254. left += el.offsetLeft;
  1255. top += el.offsetTop;
  1256. el = el.offsetParent;
  1257. }
  1258. return {
  1259. left,
  1260. top,
  1261. width,
  1262. height
  1263. };
  1264. }
  1265. /**
  1266. * Represents x and y coordinates for a DOM element or mouse pointer.
  1267. *
  1268. * @typedef {Object} module:dom~Coordinates
  1269. *
  1270. * @property {number} x
  1271. * x coordinate in pixels
  1272. *
  1273. * @property {number} y
  1274. * y coordinate in pixels
  1275. */
  1276. /**
  1277. * Get the pointer position within an element.
  1278. *
  1279. * The base on the coordinates are the bottom left of the element.
  1280. *
  1281. * @param {Element} el
  1282. * Element on which to get the pointer position on.
  1283. *
  1284. * @param {Event} event
  1285. * Event object.
  1286. *
  1287. * @return {module:dom~Coordinates}
  1288. * A coordinates object corresponding to the mouse position.
  1289. *
  1290. */
  1291. function getPointerPosition(el, event) {
  1292. const translated = {
  1293. x: 0,
  1294. y: 0
  1295. };
  1296. if (IS_IOS) {
  1297. let item = el;
  1298. while (item && item.nodeName.toLowerCase() !== 'html') {
  1299. const transform = computedStyle(item, 'transform');
  1300. if (/^matrix/.test(transform)) {
  1301. const values = transform.slice(7, -1).split(/,\s/).map(Number);
  1302. translated.x += values[4];
  1303. translated.y += values[5];
  1304. } else if (/^matrix3d/.test(transform)) {
  1305. const values = transform.slice(9, -1).split(/,\s/).map(Number);
  1306. translated.x += values[12];
  1307. translated.y += values[13];
  1308. }
  1309. item = item.parentNode;
  1310. }
  1311. }
  1312. const position = {};
  1313. const boxTarget = findPosition(event.target);
  1314. const box = findPosition(el);
  1315. const boxW = box.width;
  1316. const boxH = box.height;
  1317. let offsetY = event.offsetY - (box.top - boxTarget.top);
  1318. let offsetX = event.offsetX - (box.left - boxTarget.left);
  1319. if (event.changedTouches) {
  1320. offsetX = event.changedTouches[0].pageX - box.left;
  1321. offsetY = event.changedTouches[0].pageY + box.top;
  1322. if (IS_IOS) {
  1323. offsetX -= translated.x;
  1324. offsetY -= translated.y;
  1325. }
  1326. }
  1327. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1328. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1329. return position;
  1330. }
  1331. /**
  1332. * Determines, via duck typing, whether or not a value is a text node.
  1333. *
  1334. * @param {*} value
  1335. * Check if this value is a text node.
  1336. *
  1337. * @return {boolean}
  1338. * Will be `true` if the value is a text node, `false` otherwise.
  1339. */
  1340. function isTextNode(value) {
  1341. return isObject(value) && value.nodeType === 3;
  1342. }
  1343. /**
  1344. * Empties the contents of an element.
  1345. *
  1346. * @param {Element} el
  1347. * The element to empty children from
  1348. *
  1349. * @return {Element}
  1350. * The element with no children
  1351. */
  1352. function emptyEl(el) {
  1353. while (el.firstChild) {
  1354. el.removeChild(el.firstChild);
  1355. }
  1356. return el;
  1357. }
  1358. /**
  1359. * This is a mixed value that describes content to be injected into the DOM
  1360. * via some method. It can be of the following types:
  1361. *
  1362. * Type | Description
  1363. * -----------|-------------
  1364. * `string` | The value will be normalized into a text node.
  1365. * `Element` | The value will be accepted as-is.
  1366. * `Text` | A TextNode. The value will be accepted as-is.
  1367. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).
  1368. * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
  1369. *
  1370. * @typedef {string|Element|Text|Array|Function} ContentDescriptor
  1371. */
  1372. /**
  1373. * Normalizes content for eventual insertion into the DOM.
  1374. *
  1375. * This allows a wide range of content definition methods, but helps protect
  1376. * from falling into the trap of simply writing to `innerHTML`, which could
  1377. * be an XSS concern.
  1378. *
  1379. * The content for an element can be passed in multiple types and
  1380. * combinations, whose behavior is as follows:
  1381. *
  1382. * @param {ContentDescriptor} content
  1383. * A content descriptor value.
  1384. *
  1385. * @return {Array}
  1386. * All of the content that was passed in, normalized to an array of
  1387. * elements or text nodes.
  1388. */
  1389. function normalizeContent(content) {
  1390. // First, invoke content if it is a function. If it produces an array,
  1391. // that needs to happen before normalization.
  1392. if (typeof content === 'function') {
  1393. content = content();
  1394. }
  1395. // Next up, normalize to an array, so one or many items can be normalized,
  1396. // filtered, and returned.
  1397. return (Array.isArray(content) ? content : [content]).map(value => {
  1398. // First, invoke value if it is a function to produce a new value,
  1399. // which will be subsequently normalized to a Node of some kind.
  1400. if (typeof value === 'function') {
  1401. value = value();
  1402. }
  1403. if (isEl(value) || isTextNode(value)) {
  1404. return value;
  1405. }
  1406. if (typeof value === 'string' && /\S/.test(value)) {
  1407. return document__default["default"].createTextNode(value);
  1408. }
  1409. }).filter(value => value);
  1410. }
  1411. /**
  1412. * Normalizes and appends content to an element.
  1413. *
  1414. * @param {Element} el
  1415. * Element to append normalized content to.
  1416. *
  1417. * @param {ContentDescriptor} content
  1418. * A content descriptor value.
  1419. *
  1420. * @return {Element}
  1421. * The element with appended normalized content.
  1422. */
  1423. function appendContent(el, content) {
  1424. normalizeContent(content).forEach(node => el.appendChild(node));
  1425. return el;
  1426. }
  1427. /**
  1428. * Normalizes and inserts content into an element; this is identical to
  1429. * `appendContent()`, except it empties the element first.
  1430. *
  1431. * @param {Element} el
  1432. * Element to insert normalized content into.
  1433. *
  1434. * @param {ContentDescriptor} content
  1435. * A content descriptor value.
  1436. *
  1437. * @return {Element}
  1438. * The element with inserted normalized content.
  1439. */
  1440. function insertContent(el, content) {
  1441. return appendContent(emptyEl(el), content);
  1442. }
  1443. /**
  1444. * Check if an event was a single left click.
  1445. *
  1446. * @param {Event} event
  1447. * Event object.
  1448. *
  1449. * @return {boolean}
  1450. * Will be `true` if a single left click, `false` otherwise.
  1451. */
  1452. function isSingleLeftClick(event) {
  1453. // Note: if you create something draggable, be sure to
  1454. // call it on both `mousedown` and `mousemove` event,
  1455. // otherwise `mousedown` should be enough for a button
  1456. if (event.button === undefined && event.buttons === undefined) {
  1457. // Why do we need `buttons` ?
  1458. // Because, middle mouse sometimes have this:
  1459. // e.button === 0 and e.buttons === 4
  1460. // Furthermore, we want to prevent combination click, something like
  1461. // HOLD middlemouse then left click, that would be
  1462. // e.button === 0, e.buttons === 5
  1463. // just `button` is not gonna work
  1464. // Alright, then what this block does ?
  1465. // this is for chrome `simulate mobile devices`
  1466. // I want to support this as well
  1467. return true;
  1468. }
  1469. if (event.button === 0 && event.buttons === undefined) {
  1470. // Touch screen, sometimes on some specific device, `buttons`
  1471. // doesn't have anything (safari on ios, blackberry...)
  1472. return true;
  1473. }
  1474. // `mouseup` event on a single left click has
  1475. // `button` and `buttons` equal to 0
  1476. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1477. return true;
  1478. }
  1479. if (event.button !== 0 || event.buttons !== 1) {
  1480. // This is the reason we have those if else block above
  1481. // if any special case we can catch and let it slide
  1482. // we do it above, when get to here, this definitely
  1483. // is-not-left-click
  1484. return false;
  1485. }
  1486. return true;
  1487. }
  1488. /**
  1489. * Finds a single DOM element matching `selector` within the optional
  1490. * `context` of another DOM element (defaulting to `document`).
  1491. *
  1492. * @param {string} selector
  1493. * A valid CSS selector, which will be passed to `querySelector`.
  1494. *
  1495. * @param {Element|String} [context=document]
  1496. * A DOM element within which to query. Can also be a selector
  1497. * string in which case the first matching element will be used
  1498. * as context. If missing (or no element matches selector), falls
  1499. * back to `document`.
  1500. *
  1501. * @return {Element|null}
  1502. * The element that was found or null.
  1503. */
  1504. const $ = createQuerier('querySelector');
  1505. /**
  1506. * Finds a all DOM elements matching `selector` within the optional
  1507. * `context` of another DOM element (defaulting to `document`).
  1508. *
  1509. * @param {string} selector
  1510. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1511. *
  1512. * @param {Element|String} [context=document]
  1513. * A DOM element within which to query. Can also be a selector
  1514. * string in which case the first matching element will be used
  1515. * as context. If missing (or no element matches selector), falls
  1516. * back to `document`.
  1517. *
  1518. * @return {NodeList}
  1519. * A element list of elements that were found. Will be empty if none
  1520. * were found.
  1521. *
  1522. */
  1523. const $$ = createQuerier('querySelectorAll');
  1524. /**
  1525. * A safe getComputedStyle.
  1526. *
  1527. * This is needed because in Firefox, if the player is loaded in an iframe with
  1528. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  1529. * null-check to make sure that the player doesn't break in these cases.
  1530. *
  1531. * @param {Element} el
  1532. * The element you want the computed style of
  1533. *
  1534. * @param {string} prop
  1535. * The property name you want
  1536. *
  1537. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  1538. */
  1539. function computedStyle(el, prop) {
  1540. if (!el || !prop) {
  1541. return '';
  1542. }
  1543. if (typeof window__default["default"].getComputedStyle === 'function') {
  1544. let computedStyleValue;
  1545. try {
  1546. computedStyleValue = window__default["default"].getComputedStyle(el);
  1547. } catch (e) {
  1548. return '';
  1549. }
  1550. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  1551. }
  1552. return '';
  1553. }
  1554. var Dom = /*#__PURE__*/Object.freeze({
  1555. __proto__: null,
  1556. isReal: isReal,
  1557. isEl: isEl,
  1558. isInFrame: isInFrame,
  1559. createEl: createEl,
  1560. textContent: textContent,
  1561. prependTo: prependTo,
  1562. hasClass: hasClass,
  1563. addClass: addClass,
  1564. removeClass: removeClass,
  1565. toggleClass: toggleClass,
  1566. setAttributes: setAttributes,
  1567. getAttributes: getAttributes,
  1568. getAttribute: getAttribute,
  1569. setAttribute: setAttribute,
  1570. removeAttribute: removeAttribute,
  1571. blockTextSelection: blockTextSelection,
  1572. unblockTextSelection: unblockTextSelection,
  1573. getBoundingClientRect: getBoundingClientRect,
  1574. findPosition: findPosition,
  1575. getPointerPosition: getPointerPosition,
  1576. isTextNode: isTextNode,
  1577. emptyEl: emptyEl,
  1578. normalizeContent: normalizeContent,
  1579. appendContent: appendContent,
  1580. insertContent: insertContent,
  1581. isSingleLeftClick: isSingleLeftClick,
  1582. $: $,
  1583. $$: $$,
  1584. computedStyle: computedStyle
  1585. });
  1586. /**
  1587. * @file setup.js - Functions for setting up a player without
  1588. * user interaction based on the data-setup `attribute` of the video tag.
  1589. *
  1590. * @module setup
  1591. */
  1592. let _windowLoaded = false;
  1593. let videojs$1;
  1594. /**
  1595. * Set up any tags that have a data-setup `attribute` when the player is started.
  1596. */
  1597. const autoSetup = function () {
  1598. if (videojs$1.options.autoSetup === false) {
  1599. return;
  1600. }
  1601. const vids = Array.prototype.slice.call(document__default["default"].getElementsByTagName('video'));
  1602. const audios = Array.prototype.slice.call(document__default["default"].getElementsByTagName('audio'));
  1603. const divs = Array.prototype.slice.call(document__default["default"].getElementsByTagName('video-js'));
  1604. const mediaEls = vids.concat(audios, divs);
  1605. // Check if any media elements exist
  1606. if (mediaEls && mediaEls.length > 0) {
  1607. for (let i = 0, e = mediaEls.length; i < e; i++) {
  1608. const mediaEl = mediaEls[i];
  1609. // Check if element exists, has getAttribute func.
  1610. if (mediaEl && mediaEl.getAttribute) {
  1611. // Make sure this player hasn't already been set up.
  1612. if (mediaEl.player === undefined) {
  1613. const options = mediaEl.getAttribute('data-setup');
  1614. // Check if data-setup attr exists.
  1615. // We only auto-setup if they've added the data-setup attr.
  1616. if (options !== null) {
  1617. // Create new video.js instance.
  1618. videojs$1(mediaEl);
  1619. }
  1620. }
  1621. // If getAttribute isn't defined, we need to wait for the DOM.
  1622. } else {
  1623. autoSetupTimeout(1);
  1624. break;
  1625. }
  1626. }
  1627. // No videos were found, so keep looping unless page is finished loading.
  1628. } else if (!_windowLoaded) {
  1629. autoSetupTimeout(1);
  1630. }
  1631. };
  1632. /**
  1633. * Wait until the page is loaded before running autoSetup. This will be called in
  1634. * autoSetup if `hasLoaded` returns false.
  1635. *
  1636. * @param {number} wait
  1637. * How long to wait in ms
  1638. *
  1639. * @param {module:videojs} [vjs]
  1640. * The videojs library function
  1641. */
  1642. function autoSetupTimeout(wait, vjs) {
  1643. // Protect against breakage in non-browser environments
  1644. if (!isReal()) {
  1645. return;
  1646. }
  1647. if (vjs) {
  1648. videojs$1 = vjs;
  1649. }
  1650. window__default["default"].setTimeout(autoSetup, wait);
  1651. }
  1652. /**
  1653. * Used to set the internal tracking of window loaded state to true.
  1654. *
  1655. * @private
  1656. */
  1657. function setWindowLoaded() {
  1658. _windowLoaded = true;
  1659. window__default["default"].removeEventListener('load', setWindowLoaded);
  1660. }
  1661. if (isReal()) {
  1662. if (document__default["default"].readyState === 'complete') {
  1663. setWindowLoaded();
  1664. } else {
  1665. /**
  1666. * Listen for the load event on window, and set _windowLoaded to true.
  1667. *
  1668. * We use a standard event listener here to avoid incrementing the GUID
  1669. * before any players are created.
  1670. *
  1671. * @listens load
  1672. */
  1673. window__default["default"].addEventListener('load', setWindowLoaded);
  1674. }
  1675. }
  1676. /**
  1677. * @file stylesheet.js
  1678. * @module stylesheet
  1679. */
  1680. /**
  1681. * Create a DOM style element given a className for it.
  1682. *
  1683. * @param {string} className
  1684. * The className to add to the created style element.
  1685. *
  1686. * @return {Element}
  1687. * The element that was created.
  1688. */
  1689. const createStyleElement = function (className) {
  1690. const style = document__default["default"].createElement('style');
  1691. style.className = className;
  1692. return style;
  1693. };
  1694. /**
  1695. * Add text to a DOM element.
  1696. *
  1697. * @param {Element} el
  1698. * The Element to add text content to.
  1699. *
  1700. * @param {string} content
  1701. * The text to add to the element.
  1702. */
  1703. const setTextContent = function (el, content) {
  1704. if (el.styleSheet) {
  1705. el.styleSheet.cssText = content;
  1706. } else {
  1707. el.textContent = content;
  1708. }
  1709. };
  1710. /**
  1711. * @file dom-data.js
  1712. * @module dom-data
  1713. */
  1714. /**
  1715. * Element Data Store.
  1716. *
  1717. * Allows for binding data to an element without putting it directly on the
  1718. * element. Ex. Event listeners are stored here.
  1719. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1720. *
  1721. * @type {Object}
  1722. * @private
  1723. */
  1724. var DomData = new WeakMap();
  1725. /**
  1726. * @file guid.js
  1727. * @module guid
  1728. */
  1729. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1730. //
  1731. // The initial GUID is 3 because some users have come to rely on the first
  1732. // default player ID ending up as `vjs_video_3`.
  1733. //
  1734. // See: https://github.com/videojs/video.js/pull/6216
  1735. const _initialGuid = 3;
  1736. /**
  1737. * Unique ID for an element or function
  1738. *
  1739. * @type {Number}
  1740. */
  1741. let _guid = _initialGuid;
  1742. /**
  1743. * Get a unique auto-incrementing ID by number that has not been returned before.
  1744. *
  1745. * @return {number}
  1746. * A new unique ID.
  1747. */
  1748. function newGUID() {
  1749. return _guid++;
  1750. }
  1751. /**
  1752. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1753. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1754. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1755. * robust as jquery's, so there's probably some differences.
  1756. *
  1757. * @file events.js
  1758. * @module events
  1759. */
  1760. /**
  1761. * Clean up the listener cache and dispatchers
  1762. *
  1763. * @param {Element|Object} elem
  1764. * Element to clean up
  1765. *
  1766. * @param {string} type
  1767. * Type of event to clean up
  1768. */
  1769. function _cleanUpEvents(elem, type) {
  1770. if (!DomData.has(elem)) {
  1771. return;
  1772. }
  1773. const data = DomData.get(elem);
  1774. // Remove the events of a particular type if there are none left
  1775. if (data.handlers[type].length === 0) {
  1776. delete data.handlers[type];
  1777. // data.handlers[type] = null;
  1778. // Setting to null was causing an error with data.handlers
  1779. // Remove the meta-handler from the element
  1780. if (elem.removeEventListener) {
  1781. elem.removeEventListener(type, data.dispatcher, false);
  1782. } else if (elem.detachEvent) {
  1783. elem.detachEvent('on' + type, data.dispatcher);
  1784. }
  1785. }
  1786. // Remove the events object if there are no types left
  1787. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1788. delete data.handlers;
  1789. delete data.dispatcher;
  1790. delete data.disabled;
  1791. }
  1792. // Finally remove the element data if there is no data left
  1793. if (Object.getOwnPropertyNames(data).length === 0) {
  1794. DomData.delete(elem);
  1795. }
  1796. }
  1797. /**
  1798. * Loops through an array of event types and calls the requested method for each type.
  1799. *
  1800. * @param {Function} fn
  1801. * The event method we want to use.
  1802. *
  1803. * @param {Element|Object} elem
  1804. * Element or object to bind listeners to
  1805. *
  1806. * @param {string} type
  1807. * Type of event to bind to.
  1808. *
  1809. * @param {Function} callback
  1810. * Event listener.
  1811. */
  1812. function _handleMultipleEvents(fn, elem, types, callback) {
  1813. types.forEach(function (type) {
  1814. // Call the event method for each one of the types
  1815. fn(elem, type, callback);
  1816. });
  1817. }
  1818. /**
  1819. * Fix a native event to have standard property values
  1820. *
  1821. * @param {Object} event
  1822. * Event object to fix.
  1823. *
  1824. * @return {Object}
  1825. * Fixed event object.
  1826. */
  1827. function fixEvent(event) {
  1828. if (event.fixed_) {
  1829. return event;
  1830. }
  1831. function returnTrue() {
  1832. return true;
  1833. }
  1834. function returnFalse() {
  1835. return false;
  1836. }
  1837. // Test if fixing up is needed
  1838. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1839. // But native events return true for stopPropagation, but don't have
  1840. // other expected methods like isPropagationStopped. Seems to be a problem
  1841. // with the Javascript Ninja code. So we're just overriding all events now.
  1842. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1843. const old = event || window__default["default"].event;
  1844. event = {};
  1845. // Clone the old object so that we can modify the values event = {};
  1846. // IE8 Doesn't like when you mess with native event properties
  1847. // Firefox returns false for event.hasOwnProperty('type') and other props
  1848. // which makes copying more difficult.
  1849. // TODO: Probably best to create a whitelist of event props
  1850. for (const key in old) {
  1851. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1852. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1853. // and webkitMovementX/Y
  1854. // Lighthouse complains if Event.path is copied
  1855. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1856. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1857. // we still want to if preventDefault isn't supported (IE8).
  1858. if (!(key === 'returnValue' && old.preventDefault)) {
  1859. event[key] = old[key];
  1860. }
  1861. }
  1862. }
  1863. // The event occurred on this element
  1864. if (!event.target) {
  1865. event.target = event.srcElement || document__default["default"];
  1866. }
  1867. // Handle which other element the event is related to
  1868. if (!event.relatedTarget) {
  1869. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1870. }
  1871. // Stop the default browser action
  1872. event.preventDefault = function () {
  1873. if (old.preventDefault) {
  1874. old.preventDefault();
  1875. }
  1876. event.returnValue = false;
  1877. old.returnValue = false;
  1878. event.defaultPrevented = true;
  1879. };
  1880. event.defaultPrevented = false;
  1881. // Stop the event from bubbling
  1882. event.stopPropagation = function () {
  1883. if (old.stopPropagation) {
  1884. old.stopPropagation();
  1885. }
  1886. event.cancelBubble = true;
  1887. old.cancelBubble = true;
  1888. event.isPropagationStopped = returnTrue;
  1889. };
  1890. event.isPropagationStopped = returnFalse;
  1891. // Stop the event from bubbling and executing other handlers
  1892. event.stopImmediatePropagation = function () {
  1893. if (old.stopImmediatePropagation) {
  1894. old.stopImmediatePropagation();
  1895. }
  1896. event.isImmediatePropagationStopped = returnTrue;
  1897. event.stopPropagation();
  1898. };
  1899. event.isImmediatePropagationStopped = returnFalse;
  1900. // Handle mouse position
  1901. if (event.clientX !== null && event.clientX !== undefined) {
  1902. const doc = document__default["default"].documentElement;
  1903. const body = document__default["default"].body;
  1904. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1905. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1906. }
  1907. // Handle key presses
  1908. event.which = event.charCode || event.keyCode;
  1909. // Fix button for mouse clicks:
  1910. // 0 == left; 1 == middle; 2 == right
  1911. if (event.button !== null && event.button !== undefined) {
  1912. // The following is disabled because it does not pass videojs-standard
  1913. // and... yikes.
  1914. /* eslint-disable */
  1915. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1916. /* eslint-enable */
  1917. }
  1918. }
  1919. event.fixed_ = true;
  1920. // Returns fixed-up instance
  1921. return event;
  1922. }
  1923. /**
  1924. * Whether passive event listeners are supported
  1925. */
  1926. let _supportsPassive;
  1927. const supportsPassive = function () {
  1928. if (typeof _supportsPassive !== 'boolean') {
  1929. _supportsPassive = false;
  1930. try {
  1931. const opts = Object.defineProperty({}, 'passive', {
  1932. get() {
  1933. _supportsPassive = true;
  1934. }
  1935. });
  1936. window__default["default"].addEventListener('test', null, opts);
  1937. window__default["default"].removeEventListener('test', null, opts);
  1938. } catch (e) {
  1939. // disregard
  1940. }
  1941. }
  1942. return _supportsPassive;
  1943. };
  1944. /**
  1945. * Touch events Chrome expects to be passive
  1946. */
  1947. const passiveEvents = ['touchstart', 'touchmove'];
  1948. /**
  1949. * Add an event listener to element
  1950. * It stores the handler function in a separate cache object
  1951. * and adds a generic handler to the element's event,
  1952. * along with a unique id (guid) to the element.
  1953. *
  1954. * @param {Element|Object} elem
  1955. * Element or object to bind listeners to
  1956. *
  1957. * @param {string|string[]} type
  1958. * Type of event to bind to.
  1959. *
  1960. * @param {Function} fn
  1961. * Event listener.
  1962. */
  1963. function on(elem, type, fn) {
  1964. if (Array.isArray(type)) {
  1965. return _handleMultipleEvents(on, elem, type, fn);
  1966. }
  1967. if (!DomData.has(elem)) {
  1968. DomData.set(elem, {});
  1969. }
  1970. const data = DomData.get(elem);
  1971. // We need a place to store all our handler data
  1972. if (!data.handlers) {
  1973. data.handlers = {};
  1974. }
  1975. if (!data.handlers[type]) {
  1976. data.handlers[type] = [];
  1977. }
  1978. if (!fn.guid) {
  1979. fn.guid = newGUID();
  1980. }
  1981. data.handlers[type].push(fn);
  1982. if (!data.dispatcher) {
  1983. data.disabled = false;
  1984. data.dispatcher = function (event, hash) {
  1985. if (data.disabled) {
  1986. return;
  1987. }
  1988. event = fixEvent(event);
  1989. const handlers = data.handlers[event.type];
  1990. if (handlers) {
  1991. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  1992. const handlersCopy = handlers.slice(0);
  1993. for (let m = 0, n = handlersCopy.length; m < n; m++) {
  1994. if (event.isImmediatePropagationStopped()) {
  1995. break;
  1996. } else {
  1997. try {
  1998. handlersCopy[m].call(elem, event, hash);
  1999. } catch (e) {
  2000. log$1.error(e);
  2001. }
  2002. }
  2003. }
  2004. }
  2005. };
  2006. }
  2007. if (data.handlers[type].length === 1) {
  2008. if (elem.addEventListener) {
  2009. let options = false;
  2010. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  2011. options = {
  2012. passive: true
  2013. };
  2014. }
  2015. elem.addEventListener(type, data.dispatcher, options);
  2016. } else if (elem.attachEvent) {
  2017. elem.attachEvent('on' + type, data.dispatcher);
  2018. }
  2019. }
  2020. }
  2021. /**
  2022. * Removes event listeners from an element
  2023. *
  2024. * @param {Element|Object} elem
  2025. * Object to remove listeners from.
  2026. *
  2027. * @param {string|string[]} [type]
  2028. * Type of listener to remove. Don't include to remove all events from element.
  2029. *
  2030. * @param {Function} [fn]
  2031. * Specific listener to remove. Don't include to remove listeners for an event
  2032. * type.
  2033. */
  2034. function off(elem, type, fn) {
  2035. // Don't want to add a cache object through getElData if not needed
  2036. if (!DomData.has(elem)) {
  2037. return;
  2038. }
  2039. const data = DomData.get(elem);
  2040. // If no events exist, nothing to unbind
  2041. if (!data.handlers) {
  2042. return;
  2043. }
  2044. if (Array.isArray(type)) {
  2045. return _handleMultipleEvents(off, elem, type, fn);
  2046. }
  2047. // Utility function
  2048. const removeType = function (el, t) {
  2049. data.handlers[t] = [];
  2050. _cleanUpEvents(el, t);
  2051. };
  2052. // Are we removing all bound events?
  2053. if (type === undefined) {
  2054. for (const t in data.handlers) {
  2055. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2056. removeType(elem, t);
  2057. }
  2058. }
  2059. return;
  2060. }
  2061. const handlers = data.handlers[type];
  2062. // If no handlers exist, nothing to unbind
  2063. if (!handlers) {
  2064. return;
  2065. }
  2066. // If no listener was provided, remove all listeners for type
  2067. if (!fn) {
  2068. removeType(elem, type);
  2069. return;
  2070. }
  2071. // We're only removing a single handler
  2072. if (fn.guid) {
  2073. for (let n = 0; n < handlers.length; n++) {
  2074. if (handlers[n].guid === fn.guid) {
  2075. handlers.splice(n--, 1);
  2076. }
  2077. }
  2078. }
  2079. _cleanUpEvents(elem, type);
  2080. }
  2081. /**
  2082. * Trigger an event for an element
  2083. *
  2084. * @param {Element|Object} elem
  2085. * Element to trigger an event on
  2086. *
  2087. * @param {EventTarget~Event|string} event
  2088. * A string (the type) or an event object with a type attribute
  2089. *
  2090. * @param {Object} [hash]
  2091. * data hash to pass along with the event
  2092. *
  2093. * @return {boolean|undefined}
  2094. * Returns the opposite of `defaultPrevented` if default was
  2095. * prevented. Otherwise, returns `undefined`
  2096. */
  2097. function trigger(elem, event, hash) {
  2098. // Fetches element data and a reference to the parent (for bubbling).
  2099. // Don't want to add a data object to cache for every parent,
  2100. // so checking hasElData first.
  2101. const elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2102. const parent = elem.parentNode || elem.ownerDocument;
  2103. // type = event.type || event,
  2104. // handler;
  2105. // If an event name was passed as a string, creates an event out of it
  2106. if (typeof event === 'string') {
  2107. event = {
  2108. type: event,
  2109. target: elem
  2110. };
  2111. } else if (!event.target) {
  2112. event.target = elem;
  2113. }
  2114. // Normalizes the event properties.
  2115. event = fixEvent(event);
  2116. // If the passed element has a dispatcher, executes the established handlers.
  2117. if (elemData.dispatcher) {
  2118. elemData.dispatcher.call(elem, event, hash);
  2119. }
  2120. // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2121. // recursively calls this function to bubble the event up the DOM.
  2122. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2123. trigger.call(null, parent, event, hash);
  2124. // If at the top of the DOM, triggers the default action unless disabled.
  2125. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2126. if (!DomData.has(event.target)) {
  2127. DomData.set(event.target, {});
  2128. }
  2129. const targetData = DomData.get(event.target);
  2130. // Checks if the target has a default action for this event.
  2131. if (event.target[event.type]) {
  2132. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2133. targetData.disabled = true;
  2134. // Executes the default action.
  2135. if (typeof event.target[event.type] === 'function') {
  2136. event.target[event.type]();
  2137. }
  2138. // Re-enables event dispatching.
  2139. targetData.disabled = false;
  2140. }
  2141. }
  2142. // Inform the triggerer if the default was prevented by returning false
  2143. return !event.defaultPrevented;
  2144. }
  2145. /**
  2146. * Trigger a listener only once for an event.
  2147. *
  2148. * @param {Element|Object} elem
  2149. * Element or object to bind to.
  2150. *
  2151. * @param {string|string[]} type
  2152. * Name/type of event
  2153. *
  2154. * @param {Event~EventListener} fn
  2155. * Event listener function
  2156. */
  2157. function one(elem, type, fn) {
  2158. if (Array.isArray(type)) {
  2159. return _handleMultipleEvents(one, elem, type, fn);
  2160. }
  2161. const func = function () {
  2162. off(elem, type, func);
  2163. fn.apply(this, arguments);
  2164. };
  2165. // copy the guid to the new function so it can removed using the original function's ID
  2166. func.guid = fn.guid = fn.guid || newGUID();
  2167. on(elem, type, func);
  2168. }
  2169. /**
  2170. * Trigger a listener only once and then turn if off for all
  2171. * configured events
  2172. *
  2173. * @param {Element|Object} elem
  2174. * Element or object to bind to.
  2175. *
  2176. * @param {string|string[]} type
  2177. * Name/type of event
  2178. *
  2179. * @param {Event~EventListener} fn
  2180. * Event listener function
  2181. */
  2182. function any(elem, type, fn) {
  2183. const func = function () {
  2184. off(elem, type, func);
  2185. fn.apply(this, arguments);
  2186. };
  2187. // copy the guid to the new function so it can removed using the original function's ID
  2188. func.guid = fn.guid = fn.guid || newGUID();
  2189. // multiple ons, but one off for everything
  2190. on(elem, type, func);
  2191. }
  2192. var Events = /*#__PURE__*/Object.freeze({
  2193. __proto__: null,
  2194. fixEvent: fixEvent,
  2195. on: on,
  2196. off: off,
  2197. trigger: trigger,
  2198. one: one,
  2199. any: any
  2200. });
  2201. /**
  2202. * @file fn.js
  2203. * @module fn
  2204. */
  2205. const UPDATE_REFRESH_INTERVAL = 30;
  2206. /**
  2207. * A private, internal-only function for changing the context of a function.
  2208. *
  2209. * It also stores a unique id on the function so it can be easily removed from
  2210. * events.
  2211. *
  2212. * @private
  2213. * @function
  2214. * @param {*} context
  2215. * The object to bind as scope.
  2216. *
  2217. * @param {Function} fn
  2218. * The function to be bound to a scope.
  2219. *
  2220. * @param {number} [uid]
  2221. * An optional unique ID for the function to be set
  2222. *
  2223. * @return {Function}
  2224. * The new function that will be bound into the context given
  2225. */
  2226. const bind_ = function (context, fn, uid) {
  2227. // Make sure the function has a unique ID
  2228. if (!fn.guid) {
  2229. fn.guid = newGUID();
  2230. }
  2231. // Create the new function that changes the context
  2232. const bound = fn.bind(context);
  2233. // Allow for the ability to individualize this function
  2234. // Needed in the case where multiple objects might share the same prototype
  2235. // IF both items add an event listener with the same function, then you try to remove just one
  2236. // it will remove both because they both have the same guid.
  2237. // when using this, you need to use the bind method when you remove the listener as well.
  2238. // currently used in text tracks
  2239. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2240. return bound;
  2241. };
  2242. /**
  2243. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2244. * at most once per every `wait` milliseconds.
  2245. *
  2246. * @function
  2247. * @param {Function} fn
  2248. * The function to be throttled.
  2249. *
  2250. * @param {number} wait
  2251. * The number of milliseconds by which to throttle.
  2252. *
  2253. * @return {Function}
  2254. */
  2255. const throttle = function (fn, wait) {
  2256. let last = window__default["default"].performance.now();
  2257. const throttled = function (...args) {
  2258. const now = window__default["default"].performance.now();
  2259. if (now - last >= wait) {
  2260. fn(...args);
  2261. last = now;
  2262. }
  2263. };
  2264. return throttled;
  2265. };
  2266. /**
  2267. * Creates a debounced function that delays invoking `func` until after `wait`
  2268. * milliseconds have elapsed since the last time the debounced function was
  2269. * invoked.
  2270. *
  2271. * Inspired by lodash and underscore implementations.
  2272. *
  2273. * @function
  2274. * @param {Function} func
  2275. * The function to wrap with debounce behavior.
  2276. *
  2277. * @param {number} wait
  2278. * The number of milliseconds to wait after the last invocation.
  2279. *
  2280. * @param {boolean} [immediate]
  2281. * Whether or not to invoke the function immediately upon creation.
  2282. *
  2283. * @param {Object} [context=window]
  2284. * The "context" in which the debounced function should debounce. For
  2285. * example, if this function should be tied to a Video.js player,
  2286. * the player can be passed here. Alternatively, defaults to the
  2287. * global `window` object.
  2288. *
  2289. * @return {Function}
  2290. * A debounced function.
  2291. */
  2292. const debounce = function (func, wait, immediate, context = window__default["default"]) {
  2293. let timeout;
  2294. const cancel = () => {
  2295. context.clearTimeout(timeout);
  2296. timeout = null;
  2297. };
  2298. /* eslint-disable consistent-this */
  2299. const debounced = function () {
  2300. const self = this;
  2301. const args = arguments;
  2302. let later = function () {
  2303. timeout = null;
  2304. later = null;
  2305. if (!immediate) {
  2306. func.apply(self, args);
  2307. }
  2308. };
  2309. if (!timeout && immediate) {
  2310. func.apply(self, args);
  2311. }
  2312. context.clearTimeout(timeout);
  2313. timeout = context.setTimeout(later, wait);
  2314. };
  2315. /* eslint-enable consistent-this */
  2316. debounced.cancel = cancel;
  2317. return debounced;
  2318. };
  2319. var Fn = /*#__PURE__*/Object.freeze({
  2320. __proto__: null,
  2321. UPDATE_REFRESH_INTERVAL: UPDATE_REFRESH_INTERVAL,
  2322. bind_: bind_,
  2323. throttle: throttle,
  2324. debounce: debounce
  2325. });
  2326. /**
  2327. * @file src/js/event-target.js
  2328. */
  2329. let EVENT_MAP;
  2330. /**
  2331. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2332. * adds shorthand functions that wrap around lengthy functions. For example:
  2333. * the `on` function is a wrapper around `addEventListener`.
  2334. *
  2335. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2336. * @class EventTarget
  2337. */
  2338. class EventTarget$2 {
  2339. /**
  2340. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2341. * function that will get called when an event with a certain name gets triggered.
  2342. *
  2343. * @param {string|string[]} type
  2344. * An event name or an array of event names.
  2345. *
  2346. * @param {Function} fn
  2347. * The function to call with `EventTarget`s
  2348. */
  2349. on(type, fn) {
  2350. // Remove the addEventListener alias before calling Events.on
  2351. // so we don't get into an infinite type loop
  2352. const ael = this.addEventListener;
  2353. this.addEventListener = () => {};
  2354. on(this, type, fn);
  2355. this.addEventListener = ael;
  2356. }
  2357. /**
  2358. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2359. * This makes it so that the `event listener` will no longer get called when the
  2360. * named event happens.
  2361. *
  2362. * @param {string|string[]} type
  2363. * An event name or an array of event names.
  2364. *
  2365. * @param {Function} fn
  2366. * The function to remove.
  2367. */
  2368. off(type, fn) {
  2369. off(this, type, fn);
  2370. }
  2371. /**
  2372. * This function will add an `event listener` that gets triggered only once. After the
  2373. * first trigger it will get removed. This is like adding an `event listener`
  2374. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2375. *
  2376. * @param {string|string[]} type
  2377. * An event name or an array of event names.
  2378. *
  2379. * @param {Function} fn
  2380. * The function to be called once for each event name.
  2381. */
  2382. one(type, fn) {
  2383. // Remove the addEventListener aliasing Events.on
  2384. // so we don't get into an infinite type loop
  2385. const ael = this.addEventListener;
  2386. this.addEventListener = () => {};
  2387. one(this, type, fn);
  2388. this.addEventListener = ael;
  2389. }
  2390. /**
  2391. * This function will add an `event listener` that gets triggered only once and is
  2392. * removed from all events. This is like adding an array of `event listener`s
  2393. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  2394. * first time it is triggered.
  2395. *
  2396. * @param {string|string[]} type
  2397. * An event name or an array of event names.
  2398. *
  2399. * @param {Function} fn
  2400. * The function to be called once for each event name.
  2401. */
  2402. any(type, fn) {
  2403. // Remove the addEventListener aliasing Events.on
  2404. // so we don't get into an infinite type loop
  2405. const ael = this.addEventListener;
  2406. this.addEventListener = () => {};
  2407. any(this, type, fn);
  2408. this.addEventListener = ael;
  2409. }
  2410. /**
  2411. * This function causes an event to happen. This will then cause any `event listeners`
  2412. * that are waiting for that event, to get called. If there are no `event listeners`
  2413. * for an event then nothing will happen.
  2414. *
  2415. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2416. * Trigger will also call the `on` + `uppercaseEventName` function.
  2417. *
  2418. * Example:
  2419. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2420. * `onClick` if it exists.
  2421. *
  2422. * @param {string|EventTarget~Event|Object} event
  2423. * The name of the event, an `Event`, or an object with a key of type set to
  2424. * an event name.
  2425. */
  2426. trigger(event) {
  2427. const type = event.type || event;
  2428. // deprecation
  2429. // In a future version we should default target to `this`
  2430. // similar to how we default the target to `elem` in
  2431. // `Events.trigger`. Right now the default `target` will be
  2432. // `document` due to the `Event.fixEvent` call.
  2433. if (typeof event === 'string') {
  2434. event = {
  2435. type
  2436. };
  2437. }
  2438. event = fixEvent(event);
  2439. if (this.allowedEvents_[type] && this['on' + type]) {
  2440. this['on' + type](event);
  2441. }
  2442. trigger(this, event);
  2443. }
  2444. queueTrigger(event) {
  2445. // only set up EVENT_MAP if it'll be used
  2446. if (!EVENT_MAP) {
  2447. EVENT_MAP = new Map();
  2448. }
  2449. const type = event.type || event;
  2450. let map = EVENT_MAP.get(this);
  2451. if (!map) {
  2452. map = new Map();
  2453. EVENT_MAP.set(this, map);
  2454. }
  2455. const oldTimeout = map.get(type);
  2456. map.delete(type);
  2457. window__default["default"].clearTimeout(oldTimeout);
  2458. const timeout = window__default["default"].setTimeout(() => {
  2459. map.delete(type);
  2460. // if we cleared out all timeouts for the current target, delete its map
  2461. if (map.size === 0) {
  2462. map = null;
  2463. EVENT_MAP.delete(this);
  2464. }
  2465. this.trigger(event);
  2466. }, 0);
  2467. map.set(type, timeout);
  2468. }
  2469. }
  2470. /**
  2471. * A Custom DOM event.
  2472. *
  2473. * @typedef {CustomEvent} Event
  2474. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2475. */
  2476. /**
  2477. * All event listeners should follow the following format.
  2478. *
  2479. * @callback EventTarget~EventListener
  2480. * @this {EventTarget}
  2481. *
  2482. * @param {Event} event
  2483. * the event that triggered this function
  2484. *
  2485. * @param {Object} [hash]
  2486. * hash of data sent during the event
  2487. */
  2488. /**
  2489. * An object containing event names as keys and booleans as values.
  2490. *
  2491. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2492. * will have extra functionality. See that function for more information.
  2493. *
  2494. * @property EventTarget.prototype.allowedEvents_
  2495. * @private
  2496. */
  2497. EventTarget$2.prototype.allowedEvents_ = {};
  2498. /**
  2499. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2500. * the standard DOM API.
  2501. *
  2502. * @function
  2503. * @see {@link EventTarget#on}
  2504. */
  2505. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2506. /**
  2507. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2508. * the standard DOM API.
  2509. *
  2510. * @function
  2511. * @see {@link EventTarget#off}
  2512. */
  2513. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2514. /**
  2515. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2516. * the standard DOM API.
  2517. *
  2518. * @function
  2519. * @see {@link EventTarget#trigger}
  2520. */
  2521. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2522. /**
  2523. * @file mixins/evented.js
  2524. * @module evented
  2525. */
  2526. const objName = obj => {
  2527. if (typeof obj.name === 'function') {
  2528. return obj.name();
  2529. }
  2530. if (typeof obj.name === 'string') {
  2531. return obj.name;
  2532. }
  2533. if (obj.name_) {
  2534. return obj.name_;
  2535. }
  2536. if (obj.constructor && obj.constructor.name) {
  2537. return obj.constructor.name;
  2538. }
  2539. return typeof obj;
  2540. };
  2541. /**
  2542. * Returns whether or not an object has had the evented mixin applied.
  2543. *
  2544. * @param {Object} object
  2545. * An object to test.
  2546. *
  2547. * @return {boolean}
  2548. * Whether or not the object appears to be evented.
  2549. */
  2550. const isEvented = object => object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(k => typeof object[k] === 'function');
  2551. /**
  2552. * Adds a callback to run after the evented mixin applied.
  2553. *
  2554. * @param {Object} object
  2555. * An object to Add
  2556. * @param {Function} callback
  2557. * The callback to run.
  2558. */
  2559. const addEventedCallback = (target, callback) => {
  2560. if (isEvented(target)) {
  2561. callback();
  2562. } else {
  2563. if (!target.eventedCallbacks) {
  2564. target.eventedCallbacks = [];
  2565. }
  2566. target.eventedCallbacks.push(callback);
  2567. }
  2568. };
  2569. /**
  2570. * Whether a value is a valid event type - non-empty string or array.
  2571. *
  2572. * @private
  2573. * @param {string|Array} type
  2574. * The type value to test.
  2575. *
  2576. * @return {boolean}
  2577. * Whether or not the type is a valid event type.
  2578. */
  2579. const isValidEventType = type =>
  2580. // The regex here verifies that the `type` contains at least one non-
  2581. // whitespace character.
  2582. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length;
  2583. /**
  2584. * Validates a value to determine if it is a valid event target. Throws if not.
  2585. *
  2586. * @private
  2587. * @throws {Error}
  2588. * If the target does not appear to be a valid event target.
  2589. *
  2590. * @param {Object} target
  2591. * The object to test.
  2592. *
  2593. * @param {Object} obj
  2594. * The evented object we are validating for
  2595. *
  2596. * @param {string} fnName
  2597. * The name of the evented mixin function that called this.
  2598. */
  2599. const validateTarget = (target, obj, fnName) => {
  2600. if (!target || !target.nodeName && !isEvented(target)) {
  2601. throw new Error(`Invalid target for ${objName(obj)}#${fnName}; must be a DOM node or evented object.`);
  2602. }
  2603. };
  2604. /**
  2605. * Validates a value to determine if it is a valid event target. Throws if not.
  2606. *
  2607. * @private
  2608. * @throws {Error}
  2609. * If the type does not appear to be a valid event type.
  2610. *
  2611. * @param {string|Array} type
  2612. * The type to test.
  2613. *
  2614. * @param {Object} obj
  2615. * The evented object we are validating for
  2616. *
  2617. * @param {string} fnName
  2618. * The name of the evented mixin function that called this.
  2619. */
  2620. const validateEventType = (type, obj, fnName) => {
  2621. if (!isValidEventType(type)) {
  2622. throw new Error(`Invalid event type for ${objName(obj)}#${fnName}; must be a non-empty string or array.`);
  2623. }
  2624. };
  2625. /**
  2626. * Validates a value to determine if it is a valid listener. Throws if not.
  2627. *
  2628. * @private
  2629. * @throws {Error}
  2630. * If the listener is not a function.
  2631. *
  2632. * @param {Function} listener
  2633. * The listener to test.
  2634. *
  2635. * @param {Object} obj
  2636. * The evented object we are validating for
  2637. *
  2638. * @param {string} fnName
  2639. * The name of the evented mixin function that called this.
  2640. */
  2641. const validateListener = (listener, obj, fnName) => {
  2642. if (typeof listener !== 'function') {
  2643. throw new Error(`Invalid listener for ${objName(obj)}#${fnName}; must be a function.`);
  2644. }
  2645. };
  2646. /**
  2647. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2648. * normalizes them into an object.
  2649. *
  2650. * @private
  2651. * @param {Object} self
  2652. * The evented object on which `on()` or `one()` was called. This
  2653. * object will be bound as the `this` value for the listener.
  2654. *
  2655. * @param {Array} args
  2656. * An array of arguments passed to `on()` or `one()`.
  2657. *
  2658. * @param {string} fnName
  2659. * The name of the evented mixin function that called this.
  2660. *
  2661. * @return {Object}
  2662. * An object containing useful values for `on()` or `one()` calls.
  2663. */
  2664. const normalizeListenArgs = (self, args, fnName) => {
  2665. // If the number of arguments is less than 3, the target is always the
  2666. // evented object itself.
  2667. const isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2668. let target;
  2669. let type;
  2670. let listener;
  2671. if (isTargetingSelf) {
  2672. target = self.eventBusEl_;
  2673. // Deal with cases where we got 3 arguments, but we are still listening to
  2674. // the evented object itself.
  2675. if (args.length >= 3) {
  2676. args.shift();
  2677. }
  2678. [type, listener] = args;
  2679. } else {
  2680. [target, type, listener] = args;
  2681. }
  2682. validateTarget(target, self, fnName);
  2683. validateEventType(type, self, fnName);
  2684. validateListener(listener, self, fnName);
  2685. listener = bind_(self, listener);
  2686. return {
  2687. isTargetingSelf,
  2688. target,
  2689. type,
  2690. listener
  2691. };
  2692. };
  2693. /**
  2694. * Adds the listener to the event type(s) on the target, normalizing for
  2695. * the type of target.
  2696. *
  2697. * @private
  2698. * @param {Element|Object} target
  2699. * A DOM node or evented object.
  2700. *
  2701. * @param {string} method
  2702. * The event binding method to use ("on" or "one").
  2703. *
  2704. * @param {string|Array} type
  2705. * One or more event type(s).
  2706. *
  2707. * @param {Function} listener
  2708. * A listener function.
  2709. */
  2710. const listen = (target, method, type, listener) => {
  2711. validateTarget(target, target, method);
  2712. if (target.nodeName) {
  2713. Events[method](target, type, listener);
  2714. } else {
  2715. target[method](type, listener);
  2716. }
  2717. };
  2718. /**
  2719. * Contains methods that provide event capabilities to an object which is passed
  2720. * to {@link module:evented|evented}.
  2721. *
  2722. * @mixin EventedMixin
  2723. */
  2724. const EventedMixin = {
  2725. /**
  2726. * Add a listener to an event (or events) on this object or another evented
  2727. * object.
  2728. *
  2729. * @param {string|Array|Element|Object} targetOrType
  2730. * If this is a string or array, it represents the event type(s)
  2731. * that will trigger the listener.
  2732. *
  2733. * Another evented object can be passed here instead, which will
  2734. * cause the listener to listen for events on _that_ object.
  2735. *
  2736. * In either case, the listener's `this` value will be bound to
  2737. * this object.
  2738. *
  2739. * @param {string|Array|Function} typeOrListener
  2740. * If the first argument was a string or array, this should be the
  2741. * listener function. Otherwise, this is a string or array of event
  2742. * type(s).
  2743. *
  2744. * @param {Function} [listener]
  2745. * If the first argument was another evented object, this will be
  2746. * the listener function.
  2747. */
  2748. on(...args) {
  2749. const {
  2750. isTargetingSelf,
  2751. target,
  2752. type,
  2753. listener
  2754. } = normalizeListenArgs(this, args, 'on');
  2755. listen(target, 'on', type, listener);
  2756. // If this object is listening to another evented object.
  2757. if (!isTargetingSelf) {
  2758. // If this object is disposed, remove the listener.
  2759. const removeListenerOnDispose = () => this.off(target, type, listener);
  2760. // Use the same function ID as the listener so we can remove it later it
  2761. // using the ID of the original listener.
  2762. removeListenerOnDispose.guid = listener.guid;
  2763. // Add a listener to the target's dispose event as well. This ensures
  2764. // that if the target is disposed BEFORE this object, we remove the
  2765. // removal listener that was just added. Otherwise, we create a memory leak.
  2766. const removeRemoverOnTargetDispose = () => this.off('dispose', removeListenerOnDispose);
  2767. // Use the same function ID as the listener so we can remove it later
  2768. // it using the ID of the original listener.
  2769. removeRemoverOnTargetDispose.guid = listener.guid;
  2770. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2771. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2772. }
  2773. },
  2774. /**
  2775. * Add a listener to an event (or events) on this object or another evented
  2776. * object. The listener will be called once per event and then removed.
  2777. *
  2778. * @param {string|Array|Element|Object} targetOrType
  2779. * If this is a string or array, it represents the event type(s)
  2780. * that will trigger the listener.
  2781. *
  2782. * Another evented object can be passed here instead, which will
  2783. * cause the listener to listen for events on _that_ object.
  2784. *
  2785. * In either case, the listener's `this` value will be bound to
  2786. * this object.
  2787. *
  2788. * @param {string|Array|Function} typeOrListener
  2789. * If the first argument was a string or array, this should be the
  2790. * listener function. Otherwise, this is a string or array of event
  2791. * type(s).
  2792. *
  2793. * @param {Function} [listener]
  2794. * If the first argument was another evented object, this will be
  2795. * the listener function.
  2796. */
  2797. one(...args) {
  2798. const {
  2799. isTargetingSelf,
  2800. target,
  2801. type,
  2802. listener
  2803. } = normalizeListenArgs(this, args, 'one');
  2804. // Targeting this evented object.
  2805. if (isTargetingSelf) {
  2806. listen(target, 'one', type, listener);
  2807. // Targeting another evented object.
  2808. } else {
  2809. // TODO: This wrapper is incorrect! It should only
  2810. // remove the wrapper for the event type that called it.
  2811. // Instead all listeners are removed on the first trigger!
  2812. // see https://github.com/videojs/video.js/issues/5962
  2813. const wrapper = (...largs) => {
  2814. this.off(target, type, wrapper);
  2815. listener.apply(null, largs);
  2816. };
  2817. // Use the same function ID as the listener so we can remove it later
  2818. // it using the ID of the original listener.
  2819. wrapper.guid = listener.guid;
  2820. listen(target, 'one', type, wrapper);
  2821. }
  2822. },
  2823. /**
  2824. * Add a listener to an event (or events) on this object or another evented
  2825. * object. The listener will only be called once for the first event that is triggered
  2826. * then removed.
  2827. *
  2828. * @param {string|Array|Element|Object} targetOrType
  2829. * If this is a string or array, it represents the event type(s)
  2830. * that will trigger the listener.
  2831. *
  2832. * Another evented object can be passed here instead, which will
  2833. * cause the listener to listen for events on _that_ object.
  2834. *
  2835. * In either case, the listener's `this` value will be bound to
  2836. * this object.
  2837. *
  2838. * @param {string|Array|Function} typeOrListener
  2839. * If the first argument was a string or array, this should be the
  2840. * listener function. Otherwise, this is a string or array of event
  2841. * type(s).
  2842. *
  2843. * @param {Function} [listener]
  2844. * If the first argument was another evented object, this will be
  2845. * the listener function.
  2846. */
  2847. any(...args) {
  2848. const {
  2849. isTargetingSelf,
  2850. target,
  2851. type,
  2852. listener
  2853. } = normalizeListenArgs(this, args, 'any');
  2854. // Targeting this evented object.
  2855. if (isTargetingSelf) {
  2856. listen(target, 'any', type, listener);
  2857. // Targeting another evented object.
  2858. } else {
  2859. const wrapper = (...largs) => {
  2860. this.off(target, type, wrapper);
  2861. listener.apply(null, largs);
  2862. };
  2863. // Use the same function ID as the listener so we can remove it later
  2864. // it using the ID of the original listener.
  2865. wrapper.guid = listener.guid;
  2866. listen(target, 'any', type, wrapper);
  2867. }
  2868. },
  2869. /**
  2870. * Removes listener(s) from event(s) on an evented object.
  2871. *
  2872. * @param {string|Array|Element|Object} [targetOrType]
  2873. * If this is a string or array, it represents the event type(s).
  2874. *
  2875. * Another evented object can be passed here instead, in which case
  2876. * ALL 3 arguments are _required_.
  2877. *
  2878. * @param {string|Array|Function} [typeOrListener]
  2879. * If the first argument was a string or array, this may be the
  2880. * listener function. Otherwise, this is a string or array of event
  2881. * type(s).
  2882. *
  2883. * @param {Function} [listener]
  2884. * If the first argument was another evented object, this will be
  2885. * the listener function; otherwise, _all_ listeners bound to the
  2886. * event type(s) will be removed.
  2887. */
  2888. off(targetOrType, typeOrListener, listener) {
  2889. // Targeting this evented object.
  2890. if (!targetOrType || isValidEventType(targetOrType)) {
  2891. off(this.eventBusEl_, targetOrType, typeOrListener);
  2892. // Targeting another evented object.
  2893. } else {
  2894. const target = targetOrType;
  2895. const type = typeOrListener;
  2896. // Fail fast and in a meaningful way!
  2897. validateTarget(target, this, 'off');
  2898. validateEventType(type, this, 'off');
  2899. validateListener(listener, this, 'off');
  2900. // Ensure there's at least a guid, even if the function hasn't been used
  2901. listener = bind_(this, listener);
  2902. // Remove the dispose listener on this evented object, which was given
  2903. // the same guid as the event listener in on().
  2904. this.off('dispose', listener);
  2905. if (target.nodeName) {
  2906. off(target, type, listener);
  2907. off(target, 'dispose', listener);
  2908. } else if (isEvented(target)) {
  2909. target.off(type, listener);
  2910. target.off('dispose', listener);
  2911. }
  2912. }
  2913. },
  2914. /**
  2915. * Fire an event on this evented object, causing its listeners to be called.
  2916. *
  2917. * @param {string|Object} event
  2918. * An event type or an object with a type property.
  2919. *
  2920. * @param {Object} [hash]
  2921. * An additional object to pass along to listeners.
  2922. *
  2923. * @return {boolean}
  2924. * Whether or not the default behavior was prevented.
  2925. */
  2926. trigger(event, hash) {
  2927. validateTarget(this.eventBusEl_, this, 'trigger');
  2928. const type = event && typeof event !== 'string' ? event.type : event;
  2929. if (!isValidEventType(type)) {
  2930. throw new Error(`Invalid event type for ${objName(this)}#trigger; ` + 'must be a non-empty string or object with a type key that has a non-empty value.');
  2931. }
  2932. return trigger(this.eventBusEl_, event, hash);
  2933. }
  2934. };
  2935. /**
  2936. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2937. *
  2938. * @param {Object} target
  2939. * The object to which to add event methods.
  2940. *
  2941. * @param {Object} [options={}]
  2942. * Options for customizing the mixin behavior.
  2943. *
  2944. * @param {string} [options.eventBusKey]
  2945. * By default, adds a `eventBusEl_` DOM element to the target object,
  2946. * which is used as an event bus. If the target object already has a
  2947. * DOM element that should be used, pass its key here.
  2948. *
  2949. * @return {Object}
  2950. * The target object.
  2951. */
  2952. function evented(target, options = {}) {
  2953. const {
  2954. eventBusKey
  2955. } = options;
  2956. // Set or create the eventBusEl_.
  2957. if (eventBusKey) {
  2958. if (!target[eventBusKey].nodeName) {
  2959. throw new Error(`The eventBusKey "${eventBusKey}" does not refer to an element.`);
  2960. }
  2961. target.eventBusEl_ = target[eventBusKey];
  2962. } else {
  2963. target.eventBusEl_ = createEl('span', {
  2964. className: 'vjs-event-bus'
  2965. });
  2966. }
  2967. Object.assign(target, EventedMixin);
  2968. if (target.eventedCallbacks) {
  2969. target.eventedCallbacks.forEach(callback => {
  2970. callback();
  2971. });
  2972. }
  2973. // When any evented object is disposed, it removes all its listeners.
  2974. target.on('dispose', () => {
  2975. target.off();
  2976. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2977. if (val && DomData.has(val)) {
  2978. DomData.delete(val);
  2979. }
  2980. });
  2981. window__default["default"].setTimeout(() => {
  2982. target.eventBusEl_ = null;
  2983. }, 0);
  2984. });
  2985. return target;
  2986. }
  2987. /**
  2988. * @file mixins/stateful.js
  2989. * @module stateful
  2990. */
  2991. /**
  2992. * Contains methods that provide statefulness to an object which is passed
  2993. * to {@link module:stateful}.
  2994. *
  2995. * @mixin StatefulMixin
  2996. */
  2997. const StatefulMixin = {
  2998. /**
  2999. * A hash containing arbitrary keys and values representing the state of
  3000. * the object.
  3001. *
  3002. * @type {Object}
  3003. */
  3004. state: {},
  3005. /**
  3006. * Set the state of an object by mutating its
  3007. * {@link module:stateful~StatefulMixin.state|state} object in place.
  3008. *
  3009. * @fires module:stateful~StatefulMixin#statechanged
  3010. * @param {Object|Function} stateUpdates
  3011. * A new set of properties to shallow-merge into the plugin state.
  3012. * Can be a plain object or a function returning a plain object.
  3013. *
  3014. * @return {Object|undefined}
  3015. * An object containing changes that occurred. If no changes
  3016. * occurred, returns `undefined`.
  3017. */
  3018. setState(stateUpdates) {
  3019. // Support providing the `stateUpdates` state as a function.
  3020. if (typeof stateUpdates === 'function') {
  3021. stateUpdates = stateUpdates();
  3022. }
  3023. let changes;
  3024. each(stateUpdates, (value, key) => {
  3025. // Record the change if the value is different from what's in the
  3026. // current state.
  3027. if (this.state[key] !== value) {
  3028. changes = changes || {};
  3029. changes[key] = {
  3030. from: this.state[key],
  3031. to: value
  3032. };
  3033. }
  3034. this.state[key] = value;
  3035. });
  3036. // Only trigger "statechange" if there were changes AND we have a trigger
  3037. // function. This allows us to not require that the target object be an
  3038. // evented object.
  3039. if (changes && isEvented(this)) {
  3040. /**
  3041. * An event triggered on an object that is both
  3042. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3043. * indicating that its state has changed.
  3044. *
  3045. * @event module:stateful~StatefulMixin#statechanged
  3046. * @type {Object}
  3047. * @property {Object} changes
  3048. * A hash containing the properties that were changed and
  3049. * the values they were changed `from` and `to`.
  3050. */
  3051. this.trigger({
  3052. changes,
  3053. type: 'statechanged'
  3054. });
  3055. }
  3056. return changes;
  3057. }
  3058. };
  3059. /**
  3060. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3061. * object.
  3062. *
  3063. * If the target object is {@link module:evented|evented} and has a
  3064. * `handleStateChanged` method, that method will be automatically bound to the
  3065. * `statechanged` event on itself.
  3066. *
  3067. * @param {Object} target
  3068. * The object to be made stateful.
  3069. *
  3070. * @param {Object} [defaultState]
  3071. * A default set of properties to populate the newly-stateful object's
  3072. * `state` property.
  3073. *
  3074. * @return {Object}
  3075. * Returns the `target`.
  3076. */
  3077. function stateful(target, defaultState) {
  3078. Object.assign(target, StatefulMixin);
  3079. // This happens after the mixing-in because we need to replace the `state`
  3080. // added in that step.
  3081. target.state = Object.assign({}, target.state, defaultState);
  3082. // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3083. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3084. target.on('statechanged', target.handleStateChanged);
  3085. }
  3086. return target;
  3087. }
  3088. /**
  3089. * @file str.js
  3090. * @module to-lower-case
  3091. */
  3092. /**
  3093. * Lowercase the first letter of a string.
  3094. *
  3095. * @param {string} string
  3096. * String to be lowercased
  3097. *
  3098. * @return {string}
  3099. * The string with a lowercased first letter
  3100. */
  3101. const toLowerCase = function (string) {
  3102. if (typeof string !== 'string') {
  3103. return string;
  3104. }
  3105. return string.replace(/./, w => w.toLowerCase());
  3106. };
  3107. /**
  3108. * Uppercase the first letter of a string.
  3109. *
  3110. * @param {string} string
  3111. * String to be uppercased
  3112. *
  3113. * @return {string}
  3114. * The string with an uppercased first letter
  3115. */
  3116. const toTitleCase$1 = function (string) {
  3117. if (typeof string !== 'string') {
  3118. return string;
  3119. }
  3120. return string.replace(/./, w => w.toUpperCase());
  3121. };
  3122. /**
  3123. * Compares the TitleCase versions of the two strings for equality.
  3124. *
  3125. * @param {string} str1
  3126. * The first string to compare
  3127. *
  3128. * @param {string} str2
  3129. * The second string to compare
  3130. *
  3131. * @return {boolean}
  3132. * Whether the TitleCase versions of the strings are equal
  3133. */
  3134. const titleCaseEquals = function (str1, str2) {
  3135. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3136. };
  3137. var Str = /*#__PURE__*/Object.freeze({
  3138. __proto__: null,
  3139. toLowerCase: toLowerCase,
  3140. toTitleCase: toTitleCase$1,
  3141. titleCaseEquals: titleCaseEquals
  3142. });
  3143. /**
  3144. * Player Component - Base class for all UI objects
  3145. *
  3146. * @file component.js
  3147. */
  3148. /**
  3149. * Base class for all UI Components.
  3150. * Components are UI objects which represent both a javascript object and an element
  3151. * in the DOM. They can be children of other components, and can have
  3152. * children themselves.
  3153. *
  3154. * Components can also use methods from {@link EventTarget}
  3155. */
  3156. class Component$1 {
  3157. /**
  3158. * A callback that is called when a component is ready. Does not have any
  3159. * parameters and any callback value will be ignored.
  3160. *
  3161. * @callback ReadyCallback
  3162. * @this Component
  3163. */
  3164. /**
  3165. * Creates an instance of this class.
  3166. *
  3167. * @param { import('./player').default } player
  3168. * The `Player` that this class should be attached to.
  3169. *
  3170. * @param {Object} [options]
  3171. * The key/value store of component options.
  3172. *
  3173. * @param {Object[]} [options.children]
  3174. * An array of children objects to initialize this component with. Children objects have
  3175. * a name property that will be used if more than one component of the same type needs to be
  3176. * added.
  3177. *
  3178. * @param {string} [options.className]
  3179. * A class or space separated list of classes to add the component
  3180. *
  3181. * @param {ReadyCallback} [ready]
  3182. * Function that gets called when the `Component` is ready.
  3183. */
  3184. constructor(player, options, ready) {
  3185. // The component might be the player itself and we can't pass `this` to super
  3186. if (!player && this.play) {
  3187. this.player_ = player = this; // eslint-disable-line
  3188. } else {
  3189. this.player_ = player;
  3190. }
  3191. this.isDisposed_ = false;
  3192. // Hold the reference to the parent component via `addChild` method
  3193. this.parentComponent_ = null;
  3194. // Make a copy of prototype.options_ to protect against overriding defaults
  3195. this.options_ = merge$1({}, this.options_);
  3196. // Updated options with supplied options
  3197. options = this.options_ = merge$1(this.options_, options);
  3198. // Get ID from options or options element if one is supplied
  3199. this.id_ = options.id || options.el && options.el.id;
  3200. // If there was no ID from the options, generate one
  3201. if (!this.id_) {
  3202. // Don't require the player ID function in the case of mock players
  3203. const id = player && player.id && player.id() || 'no_player';
  3204. this.id_ = `${id}_component_${newGUID()}`;
  3205. }
  3206. this.name_ = options.name || null;
  3207. // Create element if one wasn't provided in options
  3208. if (options.el) {
  3209. this.el_ = options.el;
  3210. } else if (options.createEl !== false) {
  3211. this.el_ = this.createEl();
  3212. }
  3213. if (options.className && this.el_) {
  3214. options.className.split(' ').forEach(c => this.addClass(c));
  3215. }
  3216. // Remove the placeholder event methods. If the component is evented, the
  3217. // real methods are added next
  3218. ['on', 'off', 'one', 'any', 'trigger'].forEach(fn => {
  3219. this[fn] = undefined;
  3220. });
  3221. // if evented is anything except false, we want to mixin in evented
  3222. if (options.evented !== false) {
  3223. // Make this an evented object and use `el_`, if available, as its event bus
  3224. evented(this, {
  3225. eventBusKey: this.el_ ? 'el_' : null
  3226. });
  3227. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3228. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3229. }
  3230. stateful(this, this.constructor.defaultState);
  3231. this.children_ = [];
  3232. this.childIndex_ = {};
  3233. this.childNameIndex_ = {};
  3234. this.setTimeoutIds_ = new Set();
  3235. this.setIntervalIds_ = new Set();
  3236. this.rafIds_ = new Set();
  3237. this.namedRafs_ = new Map();
  3238. this.clearingTimersOnDispose_ = false;
  3239. // Add any child components in options
  3240. if (options.initChildren !== false) {
  3241. this.initChildren();
  3242. }
  3243. // Don't want to trigger ready here or it will go before init is actually
  3244. // finished for all children that run this constructor
  3245. this.ready(ready);
  3246. if (options.reportTouchActivity !== false) {
  3247. this.enableTouchActivity();
  3248. }
  3249. }
  3250. // `on`, `off`, `one`, `any` and `trigger` are here so tsc includes them in definitions.
  3251. // They are replaced or removed in the constructor
  3252. /**
  3253. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  3254. * function that will get called when an event with a certain name gets triggered.
  3255. *
  3256. * @param {string|string[]} type
  3257. * An event name or an array of event names.
  3258. *
  3259. * @param {Function} fn
  3260. * The function to call with `EventTarget`s
  3261. */
  3262. on(type, fn) {}
  3263. /**
  3264. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  3265. * This makes it so that the `event listener` will no longer get called when the
  3266. * named event happens.
  3267. *
  3268. * @param {string|string[]} type
  3269. * An event name or an array of event names.
  3270. *
  3271. * @param {Function} fn
  3272. * The function to remove.
  3273. */
  3274. off(type, fn) {}
  3275. /**
  3276. * This function will add an `event listener` that gets triggered only once. After the
  3277. * first trigger it will get removed. This is like adding an `event listener`
  3278. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  3279. *
  3280. * @param {string|string[]} type
  3281. * An event name or an array of event names.
  3282. *
  3283. * @param {Function} fn
  3284. * The function to be called once for each event name.
  3285. */
  3286. one(type, fn) {}
  3287. /**
  3288. * This function will add an `event listener` that gets triggered only once and is
  3289. * removed from all events. This is like adding an array of `event listener`s
  3290. * with {@link EventTarget#on} that calls {@link EventTarget#off} on all events the
  3291. * first time it is triggered.
  3292. *
  3293. * @param {string|string[]} type
  3294. * An event name or an array of event names.
  3295. *
  3296. * @param {Function} fn
  3297. * The function to be called once for each event name.
  3298. */
  3299. any(type, fn) {}
  3300. /**
  3301. * This function causes an event to happen. This will then cause any `event listeners`
  3302. * that are waiting for that event, to get called. If there are no `event listeners`
  3303. * for an event then nothing will happen.
  3304. *
  3305. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  3306. * Trigger will also call the `on` + `uppercaseEventName` function.
  3307. *
  3308. * Example:
  3309. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  3310. * `onClick` if it exists.
  3311. *
  3312. * @param {string|Event|Object} event
  3313. * The name of the event, an `Event`, or an object with a key of type set to
  3314. * an event name.
  3315. */
  3316. trigger(event) {}
  3317. /**
  3318. * Dispose of the `Component` and all child components.
  3319. *
  3320. * @fires Component#dispose
  3321. *
  3322. * @param {Object} options
  3323. * @param {Element} options.originalEl element with which to replace player element
  3324. */
  3325. dispose(options = {}) {
  3326. // Bail out if the component has already been disposed.
  3327. if (this.isDisposed_) {
  3328. return;
  3329. }
  3330. if (this.readyQueue_) {
  3331. this.readyQueue_.length = 0;
  3332. }
  3333. /**
  3334. * Triggered when a `Component` is disposed.
  3335. *
  3336. * @event Component#dispose
  3337. * @type {Event}
  3338. *
  3339. * @property {boolean} [bubbles=false]
  3340. * set to false so that the dispose event does not
  3341. * bubble up
  3342. */
  3343. this.trigger({
  3344. type: 'dispose',
  3345. bubbles: false
  3346. });
  3347. this.isDisposed_ = true;
  3348. // Dispose all children.
  3349. if (this.children_) {
  3350. for (let i = this.children_.length - 1; i >= 0; i--) {
  3351. if (this.children_[i].dispose) {
  3352. this.children_[i].dispose();
  3353. }
  3354. }
  3355. }
  3356. // Delete child references
  3357. this.children_ = null;
  3358. this.childIndex_ = null;
  3359. this.childNameIndex_ = null;
  3360. this.parentComponent_ = null;
  3361. if (this.el_) {
  3362. // Remove element from DOM
  3363. if (this.el_.parentNode) {
  3364. if (options.restoreEl) {
  3365. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3366. } else {
  3367. this.el_.parentNode.removeChild(this.el_);
  3368. }
  3369. }
  3370. this.el_ = null;
  3371. }
  3372. // remove reference to the player after disposing of the element
  3373. this.player_ = null;
  3374. }
  3375. /**
  3376. * Determine whether or not this component has been disposed.
  3377. *
  3378. * @return {boolean}
  3379. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3380. */
  3381. isDisposed() {
  3382. return Boolean(this.isDisposed_);
  3383. }
  3384. /**
  3385. * Return the {@link Player} that the `Component` has attached to.
  3386. *
  3387. * @return { import('./player').default }
  3388. * The player that this `Component` has attached to.
  3389. */
  3390. player() {
  3391. return this.player_;
  3392. }
  3393. /**
  3394. * Deep merge of options objects with new options.
  3395. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3396. * The two properties get merged using {@link module:obj.merge}
  3397. *
  3398. * @param {Object} obj
  3399. * The object that contains new options.
  3400. *
  3401. * @return {Object}
  3402. * A new object of `this.options_` and `obj` merged together.
  3403. */
  3404. options(obj) {
  3405. if (!obj) {
  3406. return this.options_;
  3407. }
  3408. this.options_ = merge$1(this.options_, obj);
  3409. return this.options_;
  3410. }
  3411. /**
  3412. * Get the `Component`s DOM element
  3413. *
  3414. * @return {Element}
  3415. * The DOM element for this `Component`.
  3416. */
  3417. el() {
  3418. return this.el_;
  3419. }
  3420. /**
  3421. * Create the `Component`s DOM element.
  3422. *
  3423. * @param {string} [tagName]
  3424. * Element's DOM node type. e.g. 'div'
  3425. *
  3426. * @param {Object} [properties]
  3427. * An object of properties that should be set.
  3428. *
  3429. * @param {Object} [attributes]
  3430. * An object of attributes that should be set.
  3431. *
  3432. * @return {Element}
  3433. * The element that gets created.
  3434. */
  3435. createEl(tagName, properties, attributes) {
  3436. return createEl(tagName, properties, attributes);
  3437. }
  3438. /**
  3439. * Localize a string given the string in english.
  3440. *
  3441. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3442. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3443. *
  3444. * If a `defaultValue` is provided, it'll use that over `string`,
  3445. * if a value isn't found in provided language files.
  3446. * This is useful if you want to have a descriptive key for token replacement
  3447. * but have a succinct localized string and not require `en.json` to be included.
  3448. *
  3449. * Currently, it is used for the progress bar timing.
  3450. * ```js
  3451. * {
  3452. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3453. * }
  3454. * ```
  3455. * It is then used like so:
  3456. * ```js
  3457. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3458. * [this.player_.currentTime(), this.player_.duration()],
  3459. * '{1} of {2}');
  3460. * ```
  3461. *
  3462. * Which outputs something like: `01:23 of 24:56`.
  3463. *
  3464. *
  3465. * @param {string} string
  3466. * The string to localize and the key to lookup in the language files.
  3467. * @param {string[]} [tokens]
  3468. * If the current item has token replacements, provide the tokens here.
  3469. * @param {string} [defaultValue]
  3470. * Defaults to `string`. Can be a default value to use for token replacement
  3471. * if the lookup key is needed to be separate.
  3472. *
  3473. * @return {string}
  3474. * The localized string or if no localization exists the english string.
  3475. */
  3476. localize(string, tokens, defaultValue = string) {
  3477. const code = this.player_.language && this.player_.language();
  3478. const languages = this.player_.languages && this.player_.languages();
  3479. const language = languages && languages[code];
  3480. const primaryCode = code && code.split('-')[0];
  3481. const primaryLang = languages && languages[primaryCode];
  3482. let localizedString = defaultValue;
  3483. if (language && language[string]) {
  3484. localizedString = language[string];
  3485. } else if (primaryLang && primaryLang[string]) {
  3486. localizedString = primaryLang[string];
  3487. }
  3488. if (tokens) {
  3489. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3490. const value = tokens[index - 1];
  3491. let ret = value;
  3492. if (typeof value === 'undefined') {
  3493. ret = match;
  3494. }
  3495. return ret;
  3496. });
  3497. }
  3498. return localizedString;
  3499. }
  3500. /**
  3501. * Handles language change for the player in components. Should be overridden by sub-components.
  3502. *
  3503. * @abstract
  3504. */
  3505. handleLanguagechange() {}
  3506. /**
  3507. * Return the `Component`s DOM element. This is where children get inserted.
  3508. * This will usually be the the same as the element returned in {@link Component#el}.
  3509. *
  3510. * @return {Element}
  3511. * The content element for this `Component`.
  3512. */
  3513. contentEl() {
  3514. return this.contentEl_ || this.el_;
  3515. }
  3516. /**
  3517. * Get this `Component`s ID
  3518. *
  3519. * @return {string}
  3520. * The id of this `Component`
  3521. */
  3522. id() {
  3523. return this.id_;
  3524. }
  3525. /**
  3526. * Get the `Component`s name. The name gets used to reference the `Component`
  3527. * and is set during registration.
  3528. *
  3529. * @return {string}
  3530. * The name of this `Component`.
  3531. */
  3532. name() {
  3533. return this.name_;
  3534. }
  3535. /**
  3536. * Get an array of all child components
  3537. *
  3538. * @return {Array}
  3539. * The children
  3540. */
  3541. children() {
  3542. return this.children_;
  3543. }
  3544. /**
  3545. * Returns the child `Component` with the given `id`.
  3546. *
  3547. * @param {string} id
  3548. * The id of the child `Component` to get.
  3549. *
  3550. * @return {Component|undefined}
  3551. * The child `Component` with the given `id` or undefined.
  3552. */
  3553. getChildById(id) {
  3554. return this.childIndex_[id];
  3555. }
  3556. /**
  3557. * Returns the child `Component` with the given `name`.
  3558. *
  3559. * @param {string} name
  3560. * The name of the child `Component` to get.
  3561. *
  3562. * @return {Component|undefined}
  3563. * The child `Component` with the given `name` or undefined.
  3564. */
  3565. getChild(name) {
  3566. if (!name) {
  3567. return;
  3568. }
  3569. return this.childNameIndex_[name];
  3570. }
  3571. /**
  3572. * Returns the descendant `Component` following the givent
  3573. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3574. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3575. * component and 'baz' on the 'bar' component and return undefined
  3576. * if any of those don't exist.
  3577. *
  3578. * @param {...string[]|...string} names
  3579. * The name of the child `Component` to get.
  3580. *
  3581. * @return {Component|undefined}
  3582. * The descendant `Component` following the given descendant
  3583. * `names` or undefined.
  3584. */
  3585. getDescendant(...names) {
  3586. // flatten array argument into the main array
  3587. names = names.reduce((acc, n) => acc.concat(n), []);
  3588. let currentChild = this;
  3589. for (let i = 0; i < names.length; i++) {
  3590. currentChild = currentChild.getChild(names[i]);
  3591. if (!currentChild || !currentChild.getChild) {
  3592. return;
  3593. }
  3594. }
  3595. return currentChild;
  3596. }
  3597. /**
  3598. * Add a child `Component` inside the current `Component`.
  3599. *
  3600. *
  3601. * @param {string|Component} child
  3602. * The name or instance of a child to add.
  3603. *
  3604. * @param {Object} [options={}]
  3605. * The key/value store of options that will get passed to children of
  3606. * the child.
  3607. *
  3608. * @param {number} [index=this.children_.length]
  3609. * The index to attempt to add a child into.
  3610. *
  3611. * @return {Component}
  3612. * The `Component` that gets added as a child. When using a string the
  3613. * `Component` will get created by this process.
  3614. */
  3615. addChild(child, options = {}, index = this.children_.length) {
  3616. let component;
  3617. let componentName;
  3618. // If child is a string, create component with options
  3619. if (typeof child === 'string') {
  3620. componentName = toTitleCase$1(child);
  3621. const componentClassName = options.componentClass || componentName;
  3622. // Set name through options
  3623. options.name = componentName;
  3624. // Create a new object & element for this controls set
  3625. // If there's no .player_, this is a player
  3626. const ComponentClass = Component$1.getComponent(componentClassName);
  3627. if (!ComponentClass) {
  3628. throw new Error(`Component ${componentClassName} does not exist`);
  3629. }
  3630. // data stored directly on the videojs object may be
  3631. // misidentified as a component to retain
  3632. // backwards-compatibility with 4.x. check to make sure the
  3633. // component class can be instantiated.
  3634. if (typeof ComponentClass !== 'function') {
  3635. return null;
  3636. }
  3637. component = new ComponentClass(this.player_ || this, options);
  3638. // child is a component instance
  3639. } else {
  3640. component = child;
  3641. }
  3642. if (component.parentComponent_) {
  3643. component.parentComponent_.removeChild(component);
  3644. }
  3645. this.children_.splice(index, 0, component);
  3646. component.parentComponent_ = this;
  3647. if (typeof component.id === 'function') {
  3648. this.childIndex_[component.id()] = component;
  3649. }
  3650. // If a name wasn't used to create the component, check if we can use the
  3651. // name function of the component
  3652. componentName = componentName || component.name && toTitleCase$1(component.name());
  3653. if (componentName) {
  3654. this.childNameIndex_[componentName] = component;
  3655. this.childNameIndex_[toLowerCase(componentName)] = component;
  3656. }
  3657. // Add the UI object's element to the container div (box)
  3658. // Having an element is not required
  3659. if (typeof component.el === 'function' && component.el()) {
  3660. // If inserting before a component, insert before that component's element
  3661. let refNode = null;
  3662. if (this.children_[index + 1]) {
  3663. // Most children are components, but the video tech is an HTML element
  3664. if (this.children_[index + 1].el_) {
  3665. refNode = this.children_[index + 1].el_;
  3666. } else if (isEl(this.children_[index + 1])) {
  3667. refNode = this.children_[index + 1];
  3668. }
  3669. }
  3670. this.contentEl().insertBefore(component.el(), refNode);
  3671. }
  3672. // Return so it can stored on parent object if desired.
  3673. return component;
  3674. }
  3675. /**
  3676. * Remove a child `Component` from this `Component`s list of children. Also removes
  3677. * the child `Component`s element from this `Component`s element.
  3678. *
  3679. * @param {Component} component
  3680. * The child `Component` to remove.
  3681. */
  3682. removeChild(component) {
  3683. if (typeof component === 'string') {
  3684. component = this.getChild(component);
  3685. }
  3686. if (!component || !this.children_) {
  3687. return;
  3688. }
  3689. let childFound = false;
  3690. for (let i = this.children_.length - 1; i >= 0; i--) {
  3691. if (this.children_[i] === component) {
  3692. childFound = true;
  3693. this.children_.splice(i, 1);
  3694. break;
  3695. }
  3696. }
  3697. if (!childFound) {
  3698. return;
  3699. }
  3700. component.parentComponent_ = null;
  3701. this.childIndex_[component.id()] = null;
  3702. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3703. this.childNameIndex_[toLowerCase(component.name())] = null;
  3704. const compEl = component.el();
  3705. if (compEl && compEl.parentNode === this.contentEl()) {
  3706. this.contentEl().removeChild(component.el());
  3707. }
  3708. }
  3709. /**
  3710. * Add and initialize default child `Component`s based upon options.
  3711. */
  3712. initChildren() {
  3713. const children = this.options_.children;
  3714. if (children) {
  3715. // `this` is `parent`
  3716. const parentOptions = this.options_;
  3717. const handleAdd = child => {
  3718. const name = child.name;
  3719. let opts = child.opts;
  3720. // Allow options for children to be set at the parent options
  3721. // e.g. videojs(id, { controlBar: false });
  3722. // instead of videojs(id, { children: { controlBar: false });
  3723. if (parentOptions[name] !== undefined) {
  3724. opts = parentOptions[name];
  3725. }
  3726. // Allow for disabling default components
  3727. // e.g. options['children']['posterImage'] = false
  3728. if (opts === false) {
  3729. return;
  3730. }
  3731. // Allow options to be passed as a simple boolean if no configuration
  3732. // is necessary.
  3733. if (opts === true) {
  3734. opts = {};
  3735. }
  3736. // We also want to pass the original player options
  3737. // to each component as well so they don't need to
  3738. // reach back into the player for options later.
  3739. opts.playerOptions = this.options_.playerOptions;
  3740. // Create and add the child component.
  3741. // Add a direct reference to the child by name on the parent instance.
  3742. // If two of the same component are used, different names should be supplied
  3743. // for each
  3744. const newChild = this.addChild(name, opts);
  3745. if (newChild) {
  3746. this[name] = newChild;
  3747. }
  3748. };
  3749. // Allow for an array of children details to passed in the options
  3750. let workingChildren;
  3751. const Tech = Component$1.getComponent('Tech');
  3752. if (Array.isArray(children)) {
  3753. workingChildren = children;
  3754. } else {
  3755. workingChildren = Object.keys(children);
  3756. }
  3757. workingChildren
  3758. // children that are in this.options_ but also in workingChildren would
  3759. // give us extra children we do not want. So, we want to filter them out.
  3760. .concat(Object.keys(this.options_).filter(function (child) {
  3761. return !workingChildren.some(function (wchild) {
  3762. if (typeof wchild === 'string') {
  3763. return child === wchild;
  3764. }
  3765. return child === wchild.name;
  3766. });
  3767. })).map(child => {
  3768. let name;
  3769. let opts;
  3770. if (typeof child === 'string') {
  3771. name = child;
  3772. opts = children[name] || this.options_[name] || {};
  3773. } else {
  3774. name = child.name;
  3775. opts = child;
  3776. }
  3777. return {
  3778. name,
  3779. opts
  3780. };
  3781. }).filter(child => {
  3782. // we have to make sure that child.name isn't in the techOrder since
  3783. // techs are registered as Components but can't aren't compatible
  3784. // See https://github.com/videojs/video.js/issues/2772
  3785. const c = Component$1.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3786. return c && !Tech.isTech(c);
  3787. }).forEach(handleAdd);
  3788. }
  3789. }
  3790. /**
  3791. * Builds the default DOM class name. Should be overridden by sub-components.
  3792. *
  3793. * @return {string}
  3794. * The DOM class name for this object.
  3795. *
  3796. * @abstract
  3797. */
  3798. buildCSSClass() {
  3799. // Child classes can include a function that does:
  3800. // return 'CLASS NAME' + this._super();
  3801. return '';
  3802. }
  3803. /**
  3804. * Bind a listener to the component's ready state.
  3805. * Different from event listeners in that if the ready event has already happened
  3806. * it will trigger the function immediately.
  3807. *
  3808. * @param {ReadyCallback} fn
  3809. * Function that gets called when the `Component` is ready.
  3810. *
  3811. * @return {Component}
  3812. * Returns itself; method can be chained.
  3813. */
  3814. ready(fn, sync = false) {
  3815. if (!fn) {
  3816. return;
  3817. }
  3818. if (!this.isReady_) {
  3819. this.readyQueue_ = this.readyQueue_ || [];
  3820. this.readyQueue_.push(fn);
  3821. return;
  3822. }
  3823. if (sync) {
  3824. fn.call(this);
  3825. } else {
  3826. // Call the function asynchronously by default for consistency
  3827. this.setTimeout(fn, 1);
  3828. }
  3829. }
  3830. /**
  3831. * Trigger all the ready listeners for this `Component`.
  3832. *
  3833. * @fires Component#ready
  3834. */
  3835. triggerReady() {
  3836. this.isReady_ = true;
  3837. // Ensure ready is triggered asynchronously
  3838. this.setTimeout(function () {
  3839. const readyQueue = this.readyQueue_;
  3840. // Reset Ready Queue
  3841. this.readyQueue_ = [];
  3842. if (readyQueue && readyQueue.length > 0) {
  3843. readyQueue.forEach(function (fn) {
  3844. fn.call(this);
  3845. }, this);
  3846. }
  3847. // Allow for using event listeners also
  3848. /**
  3849. * Triggered when a `Component` is ready.
  3850. *
  3851. * @event Component#ready
  3852. * @type {Event}
  3853. */
  3854. this.trigger('ready');
  3855. }, 1);
  3856. }
  3857. /**
  3858. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  3859. * `contentEl()` or another custom context.
  3860. *
  3861. * @param {string} selector
  3862. * A valid CSS selector, which will be passed to `querySelector`.
  3863. *
  3864. * @param {Element|string} [context=this.contentEl()]
  3865. * A DOM element within which to query. Can also be a selector string in
  3866. * which case the first matching element will get used as context. If
  3867. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3868. * nothing it falls back to `document`.
  3869. *
  3870. * @return {Element|null}
  3871. * the dom element that was found, or null
  3872. *
  3873. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3874. */
  3875. $(selector, context) {
  3876. return $(selector, context || this.contentEl());
  3877. }
  3878. /**
  3879. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  3880. * `contentEl()` or another custom context.
  3881. *
  3882. * @param {string} selector
  3883. * A valid CSS selector, which will be passed to `querySelectorAll`.
  3884. *
  3885. * @param {Element|string} [context=this.contentEl()]
  3886. * A DOM element within which to query. Can also be a selector string in
  3887. * which case the first matching element will get used as context. If
  3888. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3889. * nothing it falls back to `document`.
  3890. *
  3891. * @return {NodeList}
  3892. * a list of dom elements that were found
  3893. *
  3894. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3895. */
  3896. $$(selector, context) {
  3897. return $$(selector, context || this.contentEl());
  3898. }
  3899. /**
  3900. * Check if a component's element has a CSS class name.
  3901. *
  3902. * @param {string} classToCheck
  3903. * CSS class name to check.
  3904. *
  3905. * @return {boolean}
  3906. * - True if the `Component` has the class.
  3907. * - False if the `Component` does not have the class`
  3908. */
  3909. hasClass(classToCheck) {
  3910. return hasClass(this.el_, classToCheck);
  3911. }
  3912. /**
  3913. * Add a CSS class name to the `Component`s element.
  3914. *
  3915. * @param {...string} classesToAdd
  3916. * One or more CSS class name to add.
  3917. */
  3918. addClass(...classesToAdd) {
  3919. addClass(this.el_, ...classesToAdd);
  3920. }
  3921. /**
  3922. * Remove a CSS class name from the `Component`s element.
  3923. *
  3924. * @param {...string} classesToRemove
  3925. * One or more CSS class name to remove.
  3926. */
  3927. removeClass(...classesToRemove) {
  3928. removeClass(this.el_, ...classesToRemove);
  3929. }
  3930. /**
  3931. * Add or remove a CSS class name from the component's element.
  3932. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  3933. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  3934. *
  3935. * @param {string} classToToggle
  3936. * The class to add or remove based on (@link Component#hasClass}
  3937. *
  3938. * @param {boolean|Dom~predicate} [predicate]
  3939. * An {@link Dom~predicate} function or a boolean
  3940. */
  3941. toggleClass(classToToggle, predicate) {
  3942. toggleClass(this.el_, classToToggle, predicate);
  3943. }
  3944. /**
  3945. * Show the `Component`s element if it is hidden by removing the
  3946. * 'vjs-hidden' class name from it.
  3947. */
  3948. show() {
  3949. this.removeClass('vjs-hidden');
  3950. }
  3951. /**
  3952. * Hide the `Component`s element if it is currently showing by adding the
  3953. * 'vjs-hidden` class name to it.
  3954. */
  3955. hide() {
  3956. this.addClass('vjs-hidden');
  3957. }
  3958. /**
  3959. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  3960. * class name to it. Used during fadeIn/fadeOut.
  3961. *
  3962. * @private
  3963. */
  3964. lockShowing() {
  3965. this.addClass('vjs-lock-showing');
  3966. }
  3967. /**
  3968. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  3969. * class name from it. Used during fadeIn/fadeOut.
  3970. *
  3971. * @private
  3972. */
  3973. unlockShowing() {
  3974. this.removeClass('vjs-lock-showing');
  3975. }
  3976. /**
  3977. * Get the value of an attribute on the `Component`s element.
  3978. *
  3979. * @param {string} attribute
  3980. * Name of the attribute to get the value from.
  3981. *
  3982. * @return {string|null}
  3983. * - The value of the attribute that was asked for.
  3984. * - Can be an empty string on some browsers if the attribute does not exist
  3985. * or has no value
  3986. * - Most browsers will return null if the attribute does not exist or has
  3987. * no value.
  3988. *
  3989. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  3990. */
  3991. getAttribute(attribute) {
  3992. return getAttribute(this.el_, attribute);
  3993. }
  3994. /**
  3995. * Set the value of an attribute on the `Component`'s element
  3996. *
  3997. * @param {string} attribute
  3998. * Name of the attribute to set.
  3999. *
  4000. * @param {string} value
  4001. * Value to set the attribute to.
  4002. *
  4003. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4004. */
  4005. setAttribute(attribute, value) {
  4006. setAttribute(this.el_, attribute, value);
  4007. }
  4008. /**
  4009. * Remove an attribute from the `Component`s element.
  4010. *
  4011. * @param {string} attribute
  4012. * Name of the attribute to remove.
  4013. *
  4014. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4015. */
  4016. removeAttribute(attribute) {
  4017. removeAttribute(this.el_, attribute);
  4018. }
  4019. /**
  4020. * Get or set the width of the component based upon the CSS styles.
  4021. * See {@link Component#dimension} for more detailed information.
  4022. *
  4023. * @param {number|string} [num]
  4024. * The width that you want to set postfixed with '%', 'px' or nothing.
  4025. *
  4026. * @param {boolean} [skipListeners]
  4027. * Skip the componentresize event trigger
  4028. *
  4029. * @return {number|string}
  4030. * The width when getting, zero if there is no width. Can be a string
  4031. * postpixed with '%' or 'px'.
  4032. */
  4033. width(num, skipListeners) {
  4034. return this.dimension('width', num, skipListeners);
  4035. }
  4036. /**
  4037. * Get or set the height of the component based upon the CSS styles.
  4038. * See {@link Component#dimension} for more detailed information.
  4039. *
  4040. * @param {number|string} [num]
  4041. * The height that you want to set postfixed with '%', 'px' or nothing.
  4042. *
  4043. * @param {boolean} [skipListeners]
  4044. * Skip the componentresize event trigger
  4045. *
  4046. * @return {number|string}
  4047. * The width when getting, zero if there is no width. Can be a string
  4048. * postpixed with '%' or 'px'.
  4049. */
  4050. height(num, skipListeners) {
  4051. return this.dimension('height', num, skipListeners);
  4052. }
  4053. /**
  4054. * Set both the width and height of the `Component` element at the same time.
  4055. *
  4056. * @param {number|string} width
  4057. * Width to set the `Component`s element to.
  4058. *
  4059. * @param {number|string} height
  4060. * Height to set the `Component`s element to.
  4061. */
  4062. dimensions(width, height) {
  4063. // Skip componentresize listeners on width for optimization
  4064. this.width(width, true);
  4065. this.height(height);
  4066. }
  4067. /**
  4068. * Get or set width or height of the `Component` element. This is the shared code
  4069. * for the {@link Component#width} and {@link Component#height}.
  4070. *
  4071. * Things to know:
  4072. * - If the width or height in an number this will return the number postfixed with 'px'.
  4073. * - If the width/height is a percent this will return the percent postfixed with '%'
  4074. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4075. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4076. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4077. * for more information
  4078. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4079. * and {@link {Component#currentHeight}
  4080. *
  4081. * @fires Component#componentresize
  4082. *
  4083. * @param {string} widthOrHeight
  4084. 8 'width' or 'height'
  4085. *
  4086. * @param {number|string} [num]
  4087. 8 New dimension
  4088. *
  4089. * @param {boolean} [skipListeners]
  4090. * Skip componentresize event trigger
  4091. *
  4092. * @return {number}
  4093. * The dimension when getting or 0 if unset
  4094. */
  4095. dimension(widthOrHeight, num, skipListeners) {
  4096. if (num !== undefined) {
  4097. // Set to zero if null or literally NaN (NaN !== NaN)
  4098. if (num === null || num !== num) {
  4099. num = 0;
  4100. }
  4101. // Check if using css width/height (% or px) and adjust
  4102. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4103. this.el_.style[widthOrHeight] = num;
  4104. } else if (num === 'auto') {
  4105. this.el_.style[widthOrHeight] = '';
  4106. } else {
  4107. this.el_.style[widthOrHeight] = num + 'px';
  4108. }
  4109. // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4110. if (!skipListeners) {
  4111. /**
  4112. * Triggered when a component is resized.
  4113. *
  4114. * @event Component#componentresize
  4115. * @type {Event}
  4116. */
  4117. this.trigger('componentresize');
  4118. }
  4119. return;
  4120. }
  4121. // Not setting a value, so getting it
  4122. // Make sure element exists
  4123. if (!this.el_) {
  4124. return 0;
  4125. }
  4126. // Get dimension value from style
  4127. const val = this.el_.style[widthOrHeight];
  4128. const pxIndex = val.indexOf('px');
  4129. if (pxIndex !== -1) {
  4130. // Return the pixel value with no 'px'
  4131. return parseInt(val.slice(0, pxIndex), 10);
  4132. }
  4133. // No px so using % or no style was set, so falling back to offsetWidth/height
  4134. // If component has display:none, offset will return 0
  4135. // TODO: handle display:none and no dimension style using px
  4136. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4137. }
  4138. /**
  4139. * Get the computed width or the height of the component's element.
  4140. *
  4141. * Uses `window.getComputedStyle`.
  4142. *
  4143. * @param {string} widthOrHeight
  4144. * A string containing 'width' or 'height'. Whichever one you want to get.
  4145. *
  4146. * @return {number}
  4147. * The dimension that gets asked for or 0 if nothing was set
  4148. * for that dimension.
  4149. */
  4150. currentDimension(widthOrHeight) {
  4151. let computedWidthOrHeight = 0;
  4152. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4153. throw new Error('currentDimension only accepts width or height value');
  4154. }
  4155. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight);
  4156. // remove 'px' from variable and parse as integer
  4157. computedWidthOrHeight = parseFloat(computedWidthOrHeight);
  4158. // if the computed value is still 0, it's possible that the browser is lying
  4159. // and we want to check the offset values.
  4160. // This code also runs wherever getComputedStyle doesn't exist.
  4161. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4162. const rule = `offset${toTitleCase$1(widthOrHeight)}`;
  4163. computedWidthOrHeight = this.el_[rule];
  4164. }
  4165. return computedWidthOrHeight;
  4166. }
  4167. /**
  4168. * An object that contains width and height values of the `Component`s
  4169. * computed style. Uses `window.getComputedStyle`.
  4170. *
  4171. * @typedef {Object} Component~DimensionObject
  4172. *
  4173. * @property {number} width
  4174. * The width of the `Component`s computed style.
  4175. *
  4176. * @property {number} height
  4177. * The height of the `Component`s computed style.
  4178. */
  4179. /**
  4180. * Get an object that contains computed width and height values of the
  4181. * component's element.
  4182. *
  4183. * Uses `window.getComputedStyle`.
  4184. *
  4185. * @return {Component~DimensionObject}
  4186. * The computed dimensions of the component's element.
  4187. */
  4188. currentDimensions() {
  4189. return {
  4190. width: this.currentDimension('width'),
  4191. height: this.currentDimension('height')
  4192. };
  4193. }
  4194. /**
  4195. * Get the computed width of the component's element.
  4196. *
  4197. * Uses `window.getComputedStyle`.
  4198. *
  4199. * @return {number}
  4200. * The computed width of the component's element.
  4201. */
  4202. currentWidth() {
  4203. return this.currentDimension('width');
  4204. }
  4205. /**
  4206. * Get the computed height of the component's element.
  4207. *
  4208. * Uses `window.getComputedStyle`.
  4209. *
  4210. * @return {number}
  4211. * The computed height of the component's element.
  4212. */
  4213. currentHeight() {
  4214. return this.currentDimension('height');
  4215. }
  4216. /**
  4217. * Set the focus to this component
  4218. */
  4219. focus() {
  4220. this.el_.focus();
  4221. }
  4222. /**
  4223. * Remove the focus from this component
  4224. */
  4225. blur() {
  4226. this.el_.blur();
  4227. }
  4228. /**
  4229. * When this Component receives a `keydown` event which it does not process,
  4230. * it passes the event to the Player for handling.
  4231. *
  4232. * @param {KeyboardEvent} event
  4233. * The `keydown` event that caused this function to be called.
  4234. */
  4235. handleKeyDown(event) {
  4236. if (this.player_) {
  4237. // We only stop propagation here because we want unhandled events to fall
  4238. // back to the browser. Exclude Tab for focus trapping.
  4239. if (!keycode__default["default"].isEventKey(event, 'Tab')) {
  4240. event.stopPropagation();
  4241. }
  4242. this.player_.handleKeyDown(event);
  4243. }
  4244. }
  4245. /**
  4246. * Many components used to have a `handleKeyPress` method, which was poorly
  4247. * named because it listened to a `keydown` event. This method name now
  4248. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4249. * will not see their method calls stop working.
  4250. *
  4251. * @param {Event} event
  4252. * The event that caused this function to be called.
  4253. */
  4254. handleKeyPress(event) {
  4255. this.handleKeyDown(event);
  4256. }
  4257. /**
  4258. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4259. * support toggling the controls through a tap on the video. They get enabled
  4260. * because every sub-component would have extra overhead otherwise.
  4261. *
  4262. * @private
  4263. * @fires Component#tap
  4264. * @listens Component#touchstart
  4265. * @listens Component#touchmove
  4266. * @listens Component#touchleave
  4267. * @listens Component#touchcancel
  4268. * @listens Component#touchend
  4269. */
  4270. emitTapEvents() {
  4271. // Track the start time so we can determine how long the touch lasted
  4272. let touchStart = 0;
  4273. let firstTouch = null;
  4274. // Maximum movement allowed during a touch event to still be considered a tap
  4275. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4276. // so 10 seems like a nice, round number.
  4277. const tapMovementThreshold = 10;
  4278. // The maximum length a touch can be while still being considered a tap
  4279. const touchTimeThreshold = 200;
  4280. let couldBeTap;
  4281. this.on('touchstart', function (event) {
  4282. // If more than one finger, don't consider treating this as a click
  4283. if (event.touches.length === 1) {
  4284. // Copy pageX/pageY from the object
  4285. firstTouch = {
  4286. pageX: event.touches[0].pageX,
  4287. pageY: event.touches[0].pageY
  4288. };
  4289. // Record start time so we can detect a tap vs. "touch and hold"
  4290. touchStart = window__default["default"].performance.now();
  4291. // Reset couldBeTap tracking
  4292. couldBeTap = true;
  4293. }
  4294. });
  4295. this.on('touchmove', function (event) {
  4296. // If more than one finger, don't consider treating this as a click
  4297. if (event.touches.length > 1) {
  4298. couldBeTap = false;
  4299. } else if (firstTouch) {
  4300. // Some devices will throw touchmoves for all but the slightest of taps.
  4301. // So, if we moved only a small distance, this could still be a tap
  4302. const xdiff = event.touches[0].pageX - firstTouch.pageX;
  4303. const ydiff = event.touches[0].pageY - firstTouch.pageY;
  4304. const touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4305. if (touchDistance > tapMovementThreshold) {
  4306. couldBeTap = false;
  4307. }
  4308. }
  4309. });
  4310. const noTap = function () {
  4311. couldBeTap = false;
  4312. };
  4313. // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4314. this.on('touchleave', noTap);
  4315. this.on('touchcancel', noTap);
  4316. // When the touch ends, measure how long it took and trigger the appropriate
  4317. // event
  4318. this.on('touchend', function (event) {
  4319. firstTouch = null;
  4320. // Proceed only if the touchmove/leave/cancel event didn't happen
  4321. if (couldBeTap === true) {
  4322. // Measure how long the touch lasted
  4323. const touchTime = window__default["default"].performance.now() - touchStart;
  4324. // Make sure the touch was less than the threshold to be considered a tap
  4325. if (touchTime < touchTimeThreshold) {
  4326. // Don't let browser turn this into a click
  4327. event.preventDefault();
  4328. /**
  4329. * Triggered when a `Component` is tapped.
  4330. *
  4331. * @event Component#tap
  4332. * @type {MouseEvent}
  4333. */
  4334. this.trigger('tap');
  4335. // It may be good to copy the touchend event object and change the
  4336. // type to tap, if the other event properties aren't exact after
  4337. // Events.fixEvent runs (e.g. event.target)
  4338. }
  4339. }
  4340. });
  4341. }
  4342. /**
  4343. * This function reports user activity whenever touch events happen. This can get
  4344. * turned off by any sub-components that wants touch events to act another way.
  4345. *
  4346. * Report user touch activity when touch events occur. User activity gets used to
  4347. * determine when controls should show/hide. It is simple when it comes to mouse
  4348. * events, because any mouse event should show the controls. So we capture mouse
  4349. * events that bubble up to the player and report activity when that happens.
  4350. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4351. * controls. So touch events can't help us at the player level either.
  4352. *
  4353. * User activity gets checked asynchronously. So what could happen is a tap event
  4354. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4355. * the player. Which, if it reported user activity, would turn the controls right
  4356. * back on. We also don't want to completely block touch events from bubbling up.
  4357. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4358. * controls back on.
  4359. *
  4360. * @listens Component#touchstart
  4361. * @listens Component#touchmove
  4362. * @listens Component#touchend
  4363. * @listens Component#touchcancel
  4364. */
  4365. enableTouchActivity() {
  4366. // Don't continue if the root player doesn't support reporting user activity
  4367. if (!this.player() || !this.player().reportUserActivity) {
  4368. return;
  4369. }
  4370. // listener for reporting that the user is active
  4371. const report = bind_(this.player(), this.player().reportUserActivity);
  4372. let touchHolding;
  4373. this.on('touchstart', function () {
  4374. report();
  4375. // For as long as the they are touching the device or have their mouse down,
  4376. // we consider them active even if they're not moving their finger or mouse.
  4377. // So we want to continue to update that they are active
  4378. this.clearInterval(touchHolding);
  4379. // report at the same interval as activityCheck
  4380. touchHolding = this.setInterval(report, 250);
  4381. });
  4382. const touchEnd = function (event) {
  4383. report();
  4384. // stop the interval that maintains activity if the touch is holding
  4385. this.clearInterval(touchHolding);
  4386. };
  4387. this.on('touchmove', report);
  4388. this.on('touchend', touchEnd);
  4389. this.on('touchcancel', touchEnd);
  4390. }
  4391. /**
  4392. * A callback that has no parameters and is bound into `Component`s context.
  4393. *
  4394. * @callback Component~GenericCallback
  4395. * @this Component
  4396. */
  4397. /**
  4398. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4399. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4400. * instead though:
  4401. * 1. It gets cleared via {@link Component#clearTimeout} when
  4402. * {@link Component#dispose} gets called.
  4403. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4404. *
  4405. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4406. * will cause its dispose listener not to get cleaned up! Please use
  4407. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4408. *
  4409. * @param {Component~GenericCallback} fn
  4410. * The function that will be run after `timeout`.
  4411. *
  4412. * @param {number} timeout
  4413. * Timeout in milliseconds to delay before executing the specified function.
  4414. *
  4415. * @return {number}
  4416. * Returns a timeout ID that gets used to identify the timeout. It can also
  4417. * get used in {@link Component#clearTimeout} to clear the timeout that
  4418. * was set.
  4419. *
  4420. * @listens Component#dispose
  4421. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4422. */
  4423. setTimeout(fn, timeout) {
  4424. // declare as variables so they are properly available in timeout function
  4425. // eslint-disable-next-line
  4426. var timeoutId;
  4427. fn = bind_(this, fn);
  4428. this.clearTimersOnDispose_();
  4429. timeoutId = window__default["default"].setTimeout(() => {
  4430. if (this.setTimeoutIds_.has(timeoutId)) {
  4431. this.setTimeoutIds_.delete(timeoutId);
  4432. }
  4433. fn();
  4434. }, timeout);
  4435. this.setTimeoutIds_.add(timeoutId);
  4436. return timeoutId;
  4437. }
  4438. /**
  4439. * Clears a timeout that gets created via `window.setTimeout` or
  4440. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4441. * use this function instead of `window.clearTimout`. If you don't your dispose
  4442. * listener will not get cleaned up until {@link Component#dispose}!
  4443. *
  4444. * @param {number} timeoutId
  4445. * The id of the timeout to clear. The return value of
  4446. * {@link Component#setTimeout} or `window.setTimeout`.
  4447. *
  4448. * @return {number}
  4449. * Returns the timeout id that was cleared.
  4450. *
  4451. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4452. */
  4453. clearTimeout(timeoutId) {
  4454. if (this.setTimeoutIds_.has(timeoutId)) {
  4455. this.setTimeoutIds_.delete(timeoutId);
  4456. window__default["default"].clearTimeout(timeoutId);
  4457. }
  4458. return timeoutId;
  4459. }
  4460. /**
  4461. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4462. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4463. * 1. It gets cleared via {@link Component#clearInterval} when
  4464. * {@link Component#dispose} gets called.
  4465. * 2. The function callback will be a {@link Component~GenericCallback}
  4466. *
  4467. * @param {Component~GenericCallback} fn
  4468. * The function to run every `x` seconds.
  4469. *
  4470. * @param {number} interval
  4471. * Execute the specified function every `x` milliseconds.
  4472. *
  4473. * @return {number}
  4474. * Returns an id that can be used to identify the interval. It can also be be used in
  4475. * {@link Component#clearInterval} to clear the interval.
  4476. *
  4477. * @listens Component#dispose
  4478. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4479. */
  4480. setInterval(fn, interval) {
  4481. fn = bind_(this, fn);
  4482. this.clearTimersOnDispose_();
  4483. const intervalId = window__default["default"].setInterval(fn, interval);
  4484. this.setIntervalIds_.add(intervalId);
  4485. return intervalId;
  4486. }
  4487. /**
  4488. * Clears an interval that gets created via `window.setInterval` or
  4489. * {@link Component#setInterval}. If you set an interval via {@link Component#setInterval}
  4490. * use this function instead of `window.clearInterval`. If you don't your dispose
  4491. * listener will not get cleaned up until {@link Component#dispose}!
  4492. *
  4493. * @param {number} intervalId
  4494. * The id of the interval to clear. The return value of
  4495. * {@link Component#setInterval} or `window.setInterval`.
  4496. *
  4497. * @return {number}
  4498. * Returns the interval id that was cleared.
  4499. *
  4500. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4501. */
  4502. clearInterval(intervalId) {
  4503. if (this.setIntervalIds_.has(intervalId)) {
  4504. this.setIntervalIds_.delete(intervalId);
  4505. window__default["default"].clearInterval(intervalId);
  4506. }
  4507. return intervalId;
  4508. }
  4509. /**
  4510. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4511. * with a few extra bonuses:
  4512. *
  4513. * - Supports browsers that do not support rAF by falling back to
  4514. * {@link Component#setTimeout}.
  4515. *
  4516. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4517. * bound to the component).
  4518. *
  4519. * - Automatic cancellation of the rAF callback is handled if the component
  4520. * is disposed before it is called.
  4521. *
  4522. * @param {Component~GenericCallback} fn
  4523. * A function that will be bound to this component and executed just
  4524. * before the browser's next repaint.
  4525. *
  4526. * @return {number}
  4527. * Returns an rAF ID that gets used to identify the timeout. It can
  4528. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4529. * the animation frame callback.
  4530. *
  4531. * @listens Component#dispose
  4532. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4533. */
  4534. requestAnimationFrame(fn) {
  4535. this.clearTimersOnDispose_();
  4536. // declare as variables so they are properly available in rAF function
  4537. // eslint-disable-next-line
  4538. var id;
  4539. fn = bind_(this, fn);
  4540. id = window__default["default"].requestAnimationFrame(() => {
  4541. if (this.rafIds_.has(id)) {
  4542. this.rafIds_.delete(id);
  4543. }
  4544. fn();
  4545. });
  4546. this.rafIds_.add(id);
  4547. return id;
  4548. }
  4549. /**
  4550. * Request an animation frame, but only one named animation
  4551. * frame will be queued. Another will never be added until
  4552. * the previous one finishes.
  4553. *
  4554. * @param {string} name
  4555. * The name to give this requestAnimationFrame
  4556. *
  4557. * @param {Component~GenericCallback} fn
  4558. * A function that will be bound to this component and executed just
  4559. * before the browser's next repaint.
  4560. */
  4561. requestNamedAnimationFrame(name, fn) {
  4562. if (this.namedRafs_.has(name)) {
  4563. return;
  4564. }
  4565. this.clearTimersOnDispose_();
  4566. fn = bind_(this, fn);
  4567. const id = this.requestAnimationFrame(() => {
  4568. fn();
  4569. if (this.namedRafs_.has(name)) {
  4570. this.namedRafs_.delete(name);
  4571. }
  4572. });
  4573. this.namedRafs_.set(name, id);
  4574. return name;
  4575. }
  4576. /**
  4577. * Cancels a current named animation frame if it exists.
  4578. *
  4579. * @param {string} name
  4580. * The name of the requestAnimationFrame to cancel.
  4581. */
  4582. cancelNamedAnimationFrame(name) {
  4583. if (!this.namedRafs_.has(name)) {
  4584. return;
  4585. }
  4586. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4587. this.namedRafs_.delete(name);
  4588. }
  4589. /**
  4590. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4591. * (rAF).
  4592. *
  4593. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4594. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4595. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4596. *
  4597. * @param {number} id
  4598. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4599. *
  4600. * @return {number}
  4601. * Returns the rAF ID that was cleared.
  4602. *
  4603. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4604. */
  4605. cancelAnimationFrame(id) {
  4606. if (this.rafIds_.has(id)) {
  4607. this.rafIds_.delete(id);
  4608. window__default["default"].cancelAnimationFrame(id);
  4609. }
  4610. return id;
  4611. }
  4612. /**
  4613. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4614. * and `setInterval`, clearing on dispose.
  4615. *
  4616. * > Previously each timer added and removed dispose listeners on it's own.
  4617. * For better performance it was decided to batch them all, and use `Set`s
  4618. * to track outstanding timer ids.
  4619. *
  4620. * @private
  4621. */
  4622. clearTimersOnDispose_() {
  4623. if (this.clearingTimersOnDispose_) {
  4624. return;
  4625. }
  4626. this.clearingTimersOnDispose_ = true;
  4627. this.one('dispose', () => {
  4628. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(([idName, cancelName]) => {
  4629. // for a `Set` key will actually be the value again
  4630. // so forEach((val, val) =>` but for maps we want to use
  4631. // the key.
  4632. this[idName].forEach((val, key) => this[cancelName](key));
  4633. });
  4634. this.clearingTimersOnDispose_ = false;
  4635. });
  4636. }
  4637. /**
  4638. * Register a `Component` with `videojs` given the name and the component.
  4639. *
  4640. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4641. * should be registered using {@link Tech.registerTech} or
  4642. * {@link videojs:videojs.registerTech}.
  4643. *
  4644. * > NOTE: This function can also be seen on videojs as
  4645. * {@link videojs:videojs.registerComponent}.
  4646. *
  4647. * @param {string} name
  4648. * The name of the `Component` to register.
  4649. *
  4650. * @param {Component} ComponentToRegister
  4651. * The `Component` class to register.
  4652. *
  4653. * @return {Component}
  4654. * The `Component` that was registered.
  4655. */
  4656. static registerComponent(name, ComponentToRegister) {
  4657. if (typeof name !== 'string' || !name) {
  4658. throw new Error(`Illegal component name, "${name}"; must be a non-empty string.`);
  4659. }
  4660. const Tech = Component$1.getComponent('Tech');
  4661. // We need to make sure this check is only done if Tech has been registered.
  4662. const isTech = Tech && Tech.isTech(ComponentToRegister);
  4663. const isComp = Component$1 === ComponentToRegister || Component$1.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4664. if (isTech || !isComp) {
  4665. let reason;
  4666. if (isTech) {
  4667. reason = 'techs must be registered using Tech.registerTech()';
  4668. } else {
  4669. reason = 'must be a Component subclass';
  4670. }
  4671. throw new Error(`Illegal component, "${name}"; ${reason}.`);
  4672. }
  4673. name = toTitleCase$1(name);
  4674. if (!Component$1.components_) {
  4675. Component$1.components_ = {};
  4676. }
  4677. const Player = Component$1.getComponent('Player');
  4678. if (name === 'Player' && Player && Player.players) {
  4679. const players = Player.players;
  4680. const playerNames = Object.keys(players);
  4681. // If we have players that were disposed, then their name will still be
  4682. // in Players.players. So, we must loop through and verify that the value
  4683. // for each item is not null. This allows registration of the Player component
  4684. // after all players have been disposed or before any were created.
  4685. if (players && playerNames.length > 0 && playerNames.map(pname => players[pname]).every(Boolean)) {
  4686. throw new Error('Can not register Player component after player has been created.');
  4687. }
  4688. }
  4689. Component$1.components_[name] = ComponentToRegister;
  4690. Component$1.components_[toLowerCase(name)] = ComponentToRegister;
  4691. return ComponentToRegister;
  4692. }
  4693. /**
  4694. * Get a `Component` based on the name it was registered with.
  4695. *
  4696. * @param {string} name
  4697. * The Name of the component to get.
  4698. *
  4699. * @return {Component}
  4700. * The `Component` that got registered under the given name.
  4701. */
  4702. static getComponent(name) {
  4703. if (!name || !Component$1.components_) {
  4704. return;
  4705. }
  4706. return Component$1.components_[name];
  4707. }
  4708. }
  4709. Component$1.registerComponent('Component', Component$1);
  4710. /**
  4711. * @file time.js
  4712. * @module time
  4713. */
  4714. /**
  4715. * Returns the time for the specified index at the start or end
  4716. * of a TimeRange object.
  4717. *
  4718. * @typedef {Function} TimeRangeIndex
  4719. *
  4720. * @param {number} [index=0]
  4721. * The range number to return the time for.
  4722. *
  4723. * @return {number}
  4724. * The time offset at the specified index.
  4725. *
  4726. * @deprecated The index argument must be provided.
  4727. * In the future, leaving it out will throw an error.
  4728. */
  4729. /**
  4730. * An object that contains ranges of time, which mimics {@link TimeRanges}.
  4731. *
  4732. * @typedef {Object} TimeRange
  4733. *
  4734. * @property {number} length
  4735. * The number of time ranges represented by this object.
  4736. *
  4737. * @property {module:time~TimeRangeIndex} start
  4738. * Returns the time offset at which a specified time range begins.
  4739. *
  4740. * @property {module:time~TimeRangeIndex} end
  4741. * Returns the time offset at which a specified time range ends.
  4742. *
  4743. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4744. */
  4745. /**
  4746. * Check if any of the time ranges are over the maximum index.
  4747. *
  4748. * @private
  4749. * @param {string} fnName
  4750. * The function name to use for logging
  4751. *
  4752. * @param {number} index
  4753. * The index to check
  4754. *
  4755. * @param {number} maxIndex
  4756. * The maximum possible index
  4757. *
  4758. * @throws {Error} if the timeRanges provided are over the maxIndex
  4759. */
  4760. function rangeCheck(fnName, index, maxIndex) {
  4761. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4762. throw new Error(`Failed to execute '${fnName}' on 'TimeRanges': The index provided (${index}) is non-numeric or out of bounds (0-${maxIndex}).`);
  4763. }
  4764. }
  4765. /**
  4766. * Get the time for the specified index at the start or end
  4767. * of a TimeRange object.
  4768. *
  4769. * @private
  4770. * @param {string} fnName
  4771. * The function name to use for logging
  4772. *
  4773. * @param {string} valueIndex
  4774. * The property that should be used to get the time. should be
  4775. * 'start' or 'end'
  4776. *
  4777. * @param {Array} ranges
  4778. * An array of time ranges
  4779. *
  4780. * @param {Array} [rangeIndex=0]
  4781. * The index to start the search at
  4782. *
  4783. * @return {number}
  4784. * The time that offset at the specified index.
  4785. *
  4786. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4787. * @throws {Error} if rangeIndex is more than the length of ranges
  4788. */
  4789. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4790. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4791. return ranges[rangeIndex][valueIndex];
  4792. }
  4793. /**
  4794. * Create a time range object given ranges of time.
  4795. *
  4796. * @private
  4797. * @param {Array} [ranges]
  4798. * An array of time ranges.
  4799. *
  4800. * @return {TimeRange}
  4801. */
  4802. function createTimeRangesObj(ranges) {
  4803. let timeRangesObj;
  4804. if (ranges === undefined || ranges.length === 0) {
  4805. timeRangesObj = {
  4806. length: 0,
  4807. start() {
  4808. throw new Error('This TimeRanges object is empty');
  4809. },
  4810. end() {
  4811. throw new Error('This TimeRanges object is empty');
  4812. }
  4813. };
  4814. } else {
  4815. timeRangesObj = {
  4816. length: ranges.length,
  4817. start: getRange.bind(null, 'start', 0, ranges),
  4818. end: getRange.bind(null, 'end', 1, ranges)
  4819. };
  4820. }
  4821. if (window__default["default"].Symbol && window__default["default"].Symbol.iterator) {
  4822. timeRangesObj[window__default["default"].Symbol.iterator] = () => (ranges || []).values();
  4823. }
  4824. return timeRangesObj;
  4825. }
  4826. /**
  4827. * Create a `TimeRange` object which mimics an
  4828. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4829. *
  4830. * @param {number|Array[]} start
  4831. * The start of a single range (a number) or an array of ranges (an
  4832. * array of arrays of two numbers each).
  4833. *
  4834. * @param {number} end
  4835. * The end of a single range. Cannot be used with the array form of
  4836. * the `start` argument.
  4837. *
  4838. * @return {TimeRange}
  4839. */
  4840. function createTimeRanges$1(start, end) {
  4841. if (Array.isArray(start)) {
  4842. return createTimeRangesObj(start);
  4843. } else if (start === undefined || end === undefined) {
  4844. return createTimeRangesObj();
  4845. }
  4846. return createTimeRangesObj([[start, end]]);
  4847. }
  4848. /**
  4849. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  4850. * seconds) will force a number of leading zeros to cover the length of the
  4851. * guide.
  4852. *
  4853. * @private
  4854. * @param {number} seconds
  4855. * Number of seconds to be turned into a string
  4856. *
  4857. * @param {number} guide
  4858. * Number (in seconds) to model the string after
  4859. *
  4860. * @return {string}
  4861. * Time formatted as H:MM:SS or M:SS
  4862. */
  4863. const defaultImplementation = function (seconds, guide) {
  4864. seconds = seconds < 0 ? 0 : seconds;
  4865. let s = Math.floor(seconds % 60);
  4866. let m = Math.floor(seconds / 60 % 60);
  4867. let h = Math.floor(seconds / 3600);
  4868. const gm = Math.floor(guide / 60 % 60);
  4869. const gh = Math.floor(guide / 3600);
  4870. // handle invalid times
  4871. if (isNaN(seconds) || seconds === Infinity) {
  4872. // '-' is false for all relational operators (e.g. <, >=) so this setting
  4873. // will add the minimum number of fields specified by the guide
  4874. h = m = s = '-';
  4875. }
  4876. // Check if we need to show hours
  4877. h = h > 0 || gh > 0 ? h + ':' : '';
  4878. // If hours are showing, we may need to add a leading zero.
  4879. // Always show at least one digit of minutes.
  4880. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':';
  4881. // Check if leading zero is need for seconds
  4882. s = s < 10 ? '0' + s : s;
  4883. return h + m + s;
  4884. };
  4885. // Internal pointer to the current implementation.
  4886. let implementation = defaultImplementation;
  4887. /**
  4888. * Replaces the default formatTime implementation with a custom implementation.
  4889. *
  4890. * @param {Function} customImplementation
  4891. * A function which will be used in place of the default formatTime
  4892. * implementation. Will receive the current time in seconds and the
  4893. * guide (in seconds) as arguments.
  4894. */
  4895. function setFormatTime(customImplementation) {
  4896. implementation = customImplementation;
  4897. }
  4898. /**
  4899. * Resets formatTime to the default implementation.
  4900. */
  4901. function resetFormatTime() {
  4902. implementation = defaultImplementation;
  4903. }
  4904. /**
  4905. * Delegates to either the default time formatting function or a custom
  4906. * function supplied via `setFormatTime`.
  4907. *
  4908. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  4909. * guide (in seconds) will force a number of leading zeros to cover the
  4910. * length of the guide.
  4911. *
  4912. * @example formatTime(125, 600) === "02:05"
  4913. * @param {number} seconds
  4914. * Number of seconds to be turned into a string
  4915. *
  4916. * @param {number} guide
  4917. * Number (in seconds) to model the string after
  4918. *
  4919. * @return {string}
  4920. * Time formatted as H:MM:SS or M:SS
  4921. */
  4922. function formatTime(seconds, guide = seconds) {
  4923. return implementation(seconds, guide);
  4924. }
  4925. var Time = /*#__PURE__*/Object.freeze({
  4926. __proto__: null,
  4927. createTimeRanges: createTimeRanges$1,
  4928. createTimeRange: createTimeRanges$1,
  4929. setFormatTime: setFormatTime,
  4930. resetFormatTime: resetFormatTime,
  4931. formatTime: formatTime
  4932. });
  4933. /**
  4934. * @file buffer.js
  4935. * @module buffer
  4936. */
  4937. /**
  4938. * Compute the percentage of the media that has been buffered.
  4939. *
  4940. * @param { import('./time').TimeRange } buffered
  4941. * The current `TimeRanges` object representing buffered time ranges
  4942. *
  4943. * @param {number} duration
  4944. * Total duration of the media
  4945. *
  4946. * @return {number}
  4947. * Percent buffered of the total duration in decimal form.
  4948. */
  4949. function bufferedPercent(buffered, duration) {
  4950. let bufferedDuration = 0;
  4951. let start;
  4952. let end;
  4953. if (!duration) {
  4954. return 0;
  4955. }
  4956. if (!buffered || !buffered.length) {
  4957. buffered = createTimeRanges$1(0, 0);
  4958. }
  4959. for (let i = 0; i < buffered.length; i++) {
  4960. start = buffered.start(i);
  4961. end = buffered.end(i);
  4962. // buffered end can be bigger than duration by a very small fraction
  4963. if (end > duration) {
  4964. end = duration;
  4965. }
  4966. bufferedDuration += end - start;
  4967. }
  4968. return bufferedDuration / duration;
  4969. }
  4970. /**
  4971. * @file media-error.js
  4972. */
  4973. /**
  4974. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  4975. *
  4976. * @param {number|string|Object|MediaError} value
  4977. * This can be of multiple types:
  4978. * - number: should be a standard error code
  4979. * - string: an error message (the code will be 0)
  4980. * - Object: arbitrary properties
  4981. * - `MediaError` (native): used to populate a video.js `MediaError` object
  4982. * - `MediaError` (video.js): will return itself if it's already a
  4983. * video.js `MediaError` object.
  4984. *
  4985. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  4986. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  4987. *
  4988. * @class MediaError
  4989. */
  4990. function MediaError(value) {
  4991. // Allow redundant calls to this constructor to avoid having `instanceof`
  4992. // checks peppered around the code.
  4993. if (value instanceof MediaError) {
  4994. return value;
  4995. }
  4996. if (typeof value === 'number') {
  4997. this.code = value;
  4998. } else if (typeof value === 'string') {
  4999. // default code is zero, so this is a custom error
  5000. this.message = value;
  5001. } else if (isObject(value)) {
  5002. // We assign the `code` property manually because native `MediaError` objects
  5003. // do not expose it as an own/enumerable property of the object.
  5004. if (typeof value.code === 'number') {
  5005. this.code = value.code;
  5006. }
  5007. Object.assign(this, value);
  5008. }
  5009. if (!this.message) {
  5010. this.message = MediaError.defaultMessages[this.code] || '';
  5011. }
  5012. }
  5013. /**
  5014. * The error code that refers two one of the defined `MediaError` types
  5015. *
  5016. * @type {Number}
  5017. */
  5018. MediaError.prototype.code = 0;
  5019. /**
  5020. * An optional message that to show with the error. Message is not part of the HTML5
  5021. * video spec but allows for more informative custom errors.
  5022. *
  5023. * @type {String}
  5024. */
  5025. MediaError.prototype.message = '';
  5026. /**
  5027. * An optional status code that can be set by plugins to allow even more detail about
  5028. * the error. For example a plugin might provide a specific HTTP status code and an
  5029. * error message for that code. Then when the plugin gets that error this class will
  5030. * know how to display an error message for it. This allows a custom message to show
  5031. * up on the `Player` error overlay.
  5032. *
  5033. * @type {Array}
  5034. */
  5035. MediaError.prototype.status = null;
  5036. /**
  5037. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5038. * specification listed under {@link MediaError} for more information.
  5039. *
  5040. * @enum {array}
  5041. * @readonly
  5042. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5043. * @property {string} 1 - MEDIA_ERR_ABORTED
  5044. * @property {string} 2 - MEDIA_ERR_NETWORK
  5045. * @property {string} 3 - MEDIA_ERR_DECODE
  5046. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5047. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5048. */
  5049. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5050. /**
  5051. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5052. *
  5053. * @type {Array}
  5054. * @constant
  5055. */
  5056. MediaError.defaultMessages = {
  5057. 1: 'You aborted the media playback',
  5058. 2: 'A network error caused the media download to fail part-way.',
  5059. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5060. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5061. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5062. };
  5063. // Add types as properties on MediaError
  5064. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5065. for (let errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5066. MediaError[MediaError.errorTypes[errNum]] = errNum;
  5067. // values should be accessible on both the class and instance
  5068. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5069. }
  5070. /**
  5071. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5072. *
  5073. * @param {Object} value
  5074. * An object that may or may not be `Promise`-like.
  5075. *
  5076. * @return {boolean}
  5077. * Whether or not the object is `Promise`-like.
  5078. */
  5079. function isPromise(value) {
  5080. return value !== undefined && value !== null && typeof value.then === 'function';
  5081. }
  5082. /**
  5083. * Silence a Promise-like object.
  5084. *
  5085. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5086. * play promise" rejection error messages.
  5087. *
  5088. * @param {Object} value
  5089. * An object that may or may not be `Promise`-like.
  5090. */
  5091. function silencePromise(value) {
  5092. if (isPromise(value)) {
  5093. value.then(null, e => {});
  5094. }
  5095. }
  5096. /**
  5097. * @file text-track-list-converter.js Utilities for capturing text track state and
  5098. * re-creating tracks based on a capture.
  5099. *
  5100. * @module text-track-list-converter
  5101. */
  5102. /**
  5103. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5104. * represents the {@link TextTrack}'s state.
  5105. *
  5106. * @param {TextTrack} track
  5107. * The text track to query.
  5108. *
  5109. * @return {Object}
  5110. * A serializable javascript representation of the TextTrack.
  5111. * @private
  5112. */
  5113. const trackToJson_ = function (track) {
  5114. const ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce((acc, prop, i) => {
  5115. if (track[prop]) {
  5116. acc[prop] = track[prop];
  5117. }
  5118. return acc;
  5119. }, {
  5120. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5121. return {
  5122. startTime: cue.startTime,
  5123. endTime: cue.endTime,
  5124. text: cue.text,
  5125. id: cue.id
  5126. };
  5127. })
  5128. });
  5129. return ret;
  5130. };
  5131. /**
  5132. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5133. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5134. * {@link text-track-list-converter:jsonToTextTracks}.
  5135. *
  5136. * @param { import('../tech/tech').default } tech
  5137. * The tech object to query
  5138. *
  5139. * @return {Array}
  5140. * A serializable javascript representation of the {@link Tech}s
  5141. * {@link TextTrackList}.
  5142. */
  5143. const textTracksToJson = function (tech) {
  5144. const trackEls = tech.$$('track');
  5145. const trackObjs = Array.prototype.map.call(trackEls, t => t.track);
  5146. const tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5147. const json = trackToJson_(trackEl.track);
  5148. if (trackEl.src) {
  5149. json.src = trackEl.src;
  5150. }
  5151. return json;
  5152. });
  5153. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5154. return trackObjs.indexOf(track) === -1;
  5155. }).map(trackToJson_));
  5156. };
  5157. /**
  5158. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5159. * object {@link TextTrack} representations.
  5160. *
  5161. * @param {Array} json
  5162. * An array of `TextTrack` representation objects, like those that would be
  5163. * produced by `textTracksToJson`.
  5164. *
  5165. * @param {Tech} tech
  5166. * The `Tech` to create the `TextTrack`s on.
  5167. */
  5168. const jsonToTextTracks = function (json, tech) {
  5169. json.forEach(function (track) {
  5170. const addedTrack = tech.addRemoteTextTrack(track).track;
  5171. if (!track.src && track.cues) {
  5172. track.cues.forEach(cue => addedTrack.addCue(cue));
  5173. }
  5174. });
  5175. return tech.textTracks();
  5176. };
  5177. var textTrackConverter = {
  5178. textTracksToJson,
  5179. jsonToTextTracks,
  5180. trackToJson_
  5181. };
  5182. /**
  5183. * @file modal-dialog.js
  5184. */
  5185. const MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5186. /**
  5187. * The `ModalDialog` displays over the video and its controls, which blocks
  5188. * interaction with the player until it is closed.
  5189. *
  5190. * Modal dialogs include a "Close" button and will close when that button
  5191. * is activated - or when ESC is pressed anywhere.
  5192. *
  5193. * @extends Component
  5194. */
  5195. class ModalDialog extends Component$1 {
  5196. /**
  5197. * Create an instance of this class.
  5198. *
  5199. * @param { import('./player').default } player
  5200. * The `Player` that this class should be attached to.
  5201. *
  5202. * @param {Object} [options]
  5203. * The key/value store of player options.
  5204. *
  5205. * @param { import('./utils/dom').ContentDescriptor} [options.content=undefined]
  5206. * Provide customized content for this modal.
  5207. *
  5208. * @param {string} [options.description]
  5209. * A text description for the modal, primarily for accessibility.
  5210. *
  5211. * @param {boolean} [options.fillAlways=false]
  5212. * Normally, modals are automatically filled only the first time
  5213. * they open. This tells the modal to refresh its content
  5214. * every time it opens.
  5215. *
  5216. * @param {string} [options.label]
  5217. * A text label for the modal, primarily for accessibility.
  5218. *
  5219. * @param {boolean} [options.pauseOnOpen=true]
  5220. * If `true`, playback will will be paused if playing when
  5221. * the modal opens, and resumed when it closes.
  5222. *
  5223. * @param {boolean} [options.temporary=true]
  5224. * If `true`, the modal can only be opened once; it will be
  5225. * disposed as soon as it's closed.
  5226. *
  5227. * @param {boolean} [options.uncloseable=false]
  5228. * If `true`, the user will not be able to close the modal
  5229. * through the UI in the normal ways. Programmatic closing is
  5230. * still possible.
  5231. */
  5232. constructor(player, options) {
  5233. super(player, options);
  5234. this.handleKeyDown_ = e => this.handleKeyDown(e);
  5235. this.close_ = e => this.close(e);
  5236. this.opened_ = this.hasBeenOpened_ = this.hasBeenFilled_ = false;
  5237. this.closeable(!this.options_.uncloseable);
  5238. this.content(this.options_.content);
  5239. // Make sure the contentEl is defined AFTER any children are initialized
  5240. // because we only want the contents of the modal in the contentEl
  5241. // (not the UI elements like the close button).
  5242. this.contentEl_ = createEl('div', {
  5243. className: `${MODAL_CLASS_NAME}-content`
  5244. }, {
  5245. role: 'document'
  5246. });
  5247. this.descEl_ = createEl('p', {
  5248. className: `${MODAL_CLASS_NAME}-description vjs-control-text`,
  5249. id: this.el().getAttribute('aria-describedby')
  5250. });
  5251. textContent(this.descEl_, this.description());
  5252. this.el_.appendChild(this.descEl_);
  5253. this.el_.appendChild(this.contentEl_);
  5254. }
  5255. /**
  5256. * Create the `ModalDialog`'s DOM element
  5257. *
  5258. * @return {Element}
  5259. * The DOM element that gets created.
  5260. */
  5261. createEl() {
  5262. return super.createEl('div', {
  5263. className: this.buildCSSClass(),
  5264. tabIndex: -1
  5265. }, {
  5266. 'aria-describedby': `${this.id()}_description`,
  5267. 'aria-hidden': 'true',
  5268. 'aria-label': this.label(),
  5269. 'role': 'dialog'
  5270. });
  5271. }
  5272. dispose() {
  5273. this.contentEl_ = null;
  5274. this.descEl_ = null;
  5275. this.previouslyActiveEl_ = null;
  5276. super.dispose();
  5277. }
  5278. /**
  5279. * Builds the default DOM `className`.
  5280. *
  5281. * @return {string}
  5282. * The DOM `className` for this object.
  5283. */
  5284. buildCSSClass() {
  5285. return `${MODAL_CLASS_NAME} vjs-hidden ${super.buildCSSClass()}`;
  5286. }
  5287. /**
  5288. * Returns the label string for this modal. Primarily used for accessibility.
  5289. *
  5290. * @return {string}
  5291. * the localized or raw label of this modal.
  5292. */
  5293. label() {
  5294. return this.localize(this.options_.label || 'Modal Window');
  5295. }
  5296. /**
  5297. * Returns the description string for this modal. Primarily used for
  5298. * accessibility.
  5299. *
  5300. * @return {string}
  5301. * The localized or raw description of this modal.
  5302. */
  5303. description() {
  5304. let desc = this.options_.description || this.localize('This is a modal window.');
  5305. // Append a universal closeability message if the modal is closeable.
  5306. if (this.closeable()) {
  5307. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5308. }
  5309. return desc;
  5310. }
  5311. /**
  5312. * Opens the modal.
  5313. *
  5314. * @fires ModalDialog#beforemodalopen
  5315. * @fires ModalDialog#modalopen
  5316. */
  5317. open() {
  5318. if (!this.opened_) {
  5319. const player = this.player();
  5320. /**
  5321. * Fired just before a `ModalDialog` is opened.
  5322. *
  5323. * @event ModalDialog#beforemodalopen
  5324. * @type {Event}
  5325. */
  5326. this.trigger('beforemodalopen');
  5327. this.opened_ = true;
  5328. // Fill content if the modal has never opened before and
  5329. // never been filled.
  5330. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5331. this.fill();
  5332. }
  5333. // If the player was playing, pause it and take note of its previously
  5334. // playing state.
  5335. this.wasPlaying_ = !player.paused();
  5336. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5337. player.pause();
  5338. }
  5339. this.on('keydown', this.handleKeyDown_);
  5340. // Hide controls and note if they were enabled.
  5341. this.hadControls_ = player.controls();
  5342. player.controls(false);
  5343. this.show();
  5344. this.conditionalFocus_();
  5345. this.el().setAttribute('aria-hidden', 'false');
  5346. /**
  5347. * Fired just after a `ModalDialog` is opened.
  5348. *
  5349. * @event ModalDialog#modalopen
  5350. * @type {Event}
  5351. */
  5352. this.trigger('modalopen');
  5353. this.hasBeenOpened_ = true;
  5354. }
  5355. }
  5356. /**
  5357. * If the `ModalDialog` is currently open or closed.
  5358. *
  5359. * @param {boolean} [value]
  5360. * If given, it will open (`true`) or close (`false`) the modal.
  5361. *
  5362. * @return {boolean}
  5363. * the current open state of the modaldialog
  5364. */
  5365. opened(value) {
  5366. if (typeof value === 'boolean') {
  5367. this[value ? 'open' : 'close']();
  5368. }
  5369. return this.opened_;
  5370. }
  5371. /**
  5372. * Closes the modal, does nothing if the `ModalDialog` is
  5373. * not open.
  5374. *
  5375. * @fires ModalDialog#beforemodalclose
  5376. * @fires ModalDialog#modalclose
  5377. */
  5378. close() {
  5379. if (!this.opened_) {
  5380. return;
  5381. }
  5382. const player = this.player();
  5383. /**
  5384. * Fired just before a `ModalDialog` is closed.
  5385. *
  5386. * @event ModalDialog#beforemodalclose
  5387. * @type {Event}
  5388. */
  5389. this.trigger('beforemodalclose');
  5390. this.opened_ = false;
  5391. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5392. player.play();
  5393. }
  5394. this.off('keydown', this.handleKeyDown_);
  5395. if (this.hadControls_) {
  5396. player.controls(true);
  5397. }
  5398. this.hide();
  5399. this.el().setAttribute('aria-hidden', 'true');
  5400. /**
  5401. * Fired just after a `ModalDialog` is closed.
  5402. *
  5403. * @event ModalDialog#modalclose
  5404. * @type {Event}
  5405. */
  5406. this.trigger('modalclose');
  5407. this.conditionalBlur_();
  5408. if (this.options_.temporary) {
  5409. this.dispose();
  5410. }
  5411. }
  5412. /**
  5413. * Check to see if the `ModalDialog` is closeable via the UI.
  5414. *
  5415. * @param {boolean} [value]
  5416. * If given as a boolean, it will set the `closeable` option.
  5417. *
  5418. * @return {boolean}
  5419. * Returns the final value of the closable option.
  5420. */
  5421. closeable(value) {
  5422. if (typeof value === 'boolean') {
  5423. const closeable = this.closeable_ = !!value;
  5424. let close = this.getChild('closeButton');
  5425. // If this is being made closeable and has no close button, add one.
  5426. if (closeable && !close) {
  5427. // The close button should be a child of the modal - not its
  5428. // content element, so temporarily change the content element.
  5429. const temp = this.contentEl_;
  5430. this.contentEl_ = this.el_;
  5431. close = this.addChild('closeButton', {
  5432. controlText: 'Close Modal Dialog'
  5433. });
  5434. this.contentEl_ = temp;
  5435. this.on(close, 'close', this.close_);
  5436. }
  5437. // If this is being made uncloseable and has a close button, remove it.
  5438. if (!closeable && close) {
  5439. this.off(close, 'close', this.close_);
  5440. this.removeChild(close);
  5441. close.dispose();
  5442. }
  5443. }
  5444. return this.closeable_;
  5445. }
  5446. /**
  5447. * Fill the modal's content element with the modal's "content" option.
  5448. * The content element will be emptied before this change takes place.
  5449. */
  5450. fill() {
  5451. this.fillWith(this.content());
  5452. }
  5453. /**
  5454. * Fill the modal's content element with arbitrary content.
  5455. * The content element will be emptied before this change takes place.
  5456. *
  5457. * @fires ModalDialog#beforemodalfill
  5458. * @fires ModalDialog#modalfill
  5459. *
  5460. * @param { import('./utils/dom').ContentDescriptor} [content]
  5461. * The same rules apply to this as apply to the `content` option.
  5462. */
  5463. fillWith(content) {
  5464. const contentEl = this.contentEl();
  5465. const parentEl = contentEl.parentNode;
  5466. const nextSiblingEl = contentEl.nextSibling;
  5467. /**
  5468. * Fired just before a `ModalDialog` is filled with content.
  5469. *
  5470. * @event ModalDialog#beforemodalfill
  5471. * @type {Event}
  5472. */
  5473. this.trigger('beforemodalfill');
  5474. this.hasBeenFilled_ = true;
  5475. // Detach the content element from the DOM before performing
  5476. // manipulation to avoid modifying the live DOM multiple times.
  5477. parentEl.removeChild(contentEl);
  5478. this.empty();
  5479. insertContent(contentEl, content);
  5480. /**
  5481. * Fired just after a `ModalDialog` is filled with content.
  5482. *
  5483. * @event ModalDialog#modalfill
  5484. * @type {Event}
  5485. */
  5486. this.trigger('modalfill');
  5487. // Re-inject the re-filled content element.
  5488. if (nextSiblingEl) {
  5489. parentEl.insertBefore(contentEl, nextSiblingEl);
  5490. } else {
  5491. parentEl.appendChild(contentEl);
  5492. }
  5493. // make sure that the close button is last in the dialog DOM
  5494. const closeButton = this.getChild('closeButton');
  5495. if (closeButton) {
  5496. parentEl.appendChild(closeButton.el_);
  5497. }
  5498. }
  5499. /**
  5500. * Empties the content element. This happens anytime the modal is filled.
  5501. *
  5502. * @fires ModalDialog#beforemodalempty
  5503. * @fires ModalDialog#modalempty
  5504. */
  5505. empty() {
  5506. /**
  5507. * Fired just before a `ModalDialog` is emptied.
  5508. *
  5509. * @event ModalDialog#beforemodalempty
  5510. * @type {Event}
  5511. */
  5512. this.trigger('beforemodalempty');
  5513. emptyEl(this.contentEl());
  5514. /**
  5515. * Fired just after a `ModalDialog` is emptied.
  5516. *
  5517. * @event ModalDialog#modalempty
  5518. * @type {Event}
  5519. */
  5520. this.trigger('modalempty');
  5521. }
  5522. /**
  5523. * Gets or sets the modal content, which gets normalized before being
  5524. * rendered into the DOM.
  5525. *
  5526. * This does not update the DOM or fill the modal, but it is called during
  5527. * that process.
  5528. *
  5529. * @param { import('./utils/dom').ContentDescriptor} [value]
  5530. * If defined, sets the internal content value to be used on the
  5531. * next call(s) to `fill`. This value is normalized before being
  5532. * inserted. To "clear" the internal content value, pass `null`.
  5533. *
  5534. * @return { import('./utils/dom').ContentDescriptor}
  5535. * The current content of the modal dialog
  5536. */
  5537. content(value) {
  5538. if (typeof value !== 'undefined') {
  5539. this.content_ = value;
  5540. }
  5541. return this.content_;
  5542. }
  5543. /**
  5544. * conditionally focus the modal dialog if focus was previously on the player.
  5545. *
  5546. * @private
  5547. */
  5548. conditionalFocus_() {
  5549. const activeEl = document__default["default"].activeElement;
  5550. const playerEl = this.player_.el_;
  5551. this.previouslyActiveEl_ = null;
  5552. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5553. this.previouslyActiveEl_ = activeEl;
  5554. this.focus();
  5555. }
  5556. }
  5557. /**
  5558. * conditionally blur the element and refocus the last focused element
  5559. *
  5560. * @private
  5561. */
  5562. conditionalBlur_() {
  5563. if (this.previouslyActiveEl_) {
  5564. this.previouslyActiveEl_.focus();
  5565. this.previouslyActiveEl_ = null;
  5566. }
  5567. }
  5568. /**
  5569. * Keydown handler. Attached when modal is focused.
  5570. *
  5571. * @listens keydown
  5572. */
  5573. handleKeyDown(event) {
  5574. // Do not allow keydowns to reach out of the modal dialog.
  5575. event.stopPropagation();
  5576. if (keycode__default["default"].isEventKey(event, 'Escape') && this.closeable()) {
  5577. event.preventDefault();
  5578. this.close();
  5579. return;
  5580. }
  5581. // exit early if it isn't a tab key
  5582. if (!keycode__default["default"].isEventKey(event, 'Tab')) {
  5583. return;
  5584. }
  5585. const focusableEls = this.focusableEls_();
  5586. const activeEl = this.el_.querySelector(':focus');
  5587. let focusIndex;
  5588. for (let i = 0; i < focusableEls.length; i++) {
  5589. if (activeEl === focusableEls[i]) {
  5590. focusIndex = i;
  5591. break;
  5592. }
  5593. }
  5594. if (document__default["default"].activeElement === this.el_) {
  5595. focusIndex = 0;
  5596. }
  5597. if (event.shiftKey && focusIndex === 0) {
  5598. focusableEls[focusableEls.length - 1].focus();
  5599. event.preventDefault();
  5600. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5601. focusableEls[0].focus();
  5602. event.preventDefault();
  5603. }
  5604. }
  5605. /**
  5606. * get all focusable elements
  5607. *
  5608. * @private
  5609. */
  5610. focusableEls_() {
  5611. const allChildren = this.el_.querySelectorAll('*');
  5612. return Array.prototype.filter.call(allChildren, child => {
  5613. return (child instanceof window__default["default"].HTMLAnchorElement || child instanceof window__default["default"].HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window__default["default"].HTMLInputElement || child instanceof window__default["default"].HTMLSelectElement || child instanceof window__default["default"].HTMLTextAreaElement || child instanceof window__default["default"].HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window__default["default"].HTMLIFrameElement || child instanceof window__default["default"].HTMLObjectElement || child instanceof window__default["default"].HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  5614. });
  5615. }
  5616. }
  5617. /**
  5618. * Default options for `ModalDialog` default options.
  5619. *
  5620. * @type {Object}
  5621. * @private
  5622. */
  5623. ModalDialog.prototype.options_ = {
  5624. pauseOnOpen: true,
  5625. temporary: true
  5626. };
  5627. Component$1.registerComponent('ModalDialog', ModalDialog);
  5628. /**
  5629. * @file track-list.js
  5630. */
  5631. /**
  5632. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5633. * {@link VideoTrackList}
  5634. *
  5635. * @extends EventTarget
  5636. */
  5637. class TrackList extends EventTarget$2 {
  5638. /**
  5639. * Create an instance of this class
  5640. *
  5641. * @param { import('./track').default[] } tracks
  5642. * A list of tracks to initialize the list with.
  5643. *
  5644. * @abstract
  5645. */
  5646. constructor(tracks = []) {
  5647. super();
  5648. this.tracks_ = [];
  5649. /**
  5650. * @memberof TrackList
  5651. * @member {number} length
  5652. * The current number of `Track`s in the this Trackist.
  5653. * @instance
  5654. */
  5655. Object.defineProperty(this, 'length', {
  5656. get() {
  5657. return this.tracks_.length;
  5658. }
  5659. });
  5660. for (let i = 0; i < tracks.length; i++) {
  5661. this.addTrack(tracks[i]);
  5662. }
  5663. }
  5664. /**
  5665. * Add a {@link Track} to the `TrackList`
  5666. *
  5667. * @param { import('./track').default } track
  5668. * The audio, video, or text track to add to the list.
  5669. *
  5670. * @fires TrackList#addtrack
  5671. */
  5672. addTrack(track) {
  5673. const index = this.tracks_.length;
  5674. if (!('' + index in this)) {
  5675. Object.defineProperty(this, index, {
  5676. get() {
  5677. return this.tracks_[index];
  5678. }
  5679. });
  5680. }
  5681. // Do not add duplicate tracks
  5682. if (this.tracks_.indexOf(track) === -1) {
  5683. this.tracks_.push(track);
  5684. /**
  5685. * Triggered when a track is added to a track list.
  5686. *
  5687. * @event TrackList#addtrack
  5688. * @type {Event}
  5689. * @property {Track} track
  5690. * A reference to track that was added.
  5691. */
  5692. this.trigger({
  5693. track,
  5694. type: 'addtrack',
  5695. target: this
  5696. });
  5697. }
  5698. /**
  5699. * Triggered when a track label is changed.
  5700. *
  5701. * @event TrackList#addtrack
  5702. * @type {Event}
  5703. * @property {Track} track
  5704. * A reference to track that was added.
  5705. */
  5706. track.labelchange_ = () => {
  5707. this.trigger({
  5708. track,
  5709. type: 'labelchange',
  5710. target: this
  5711. });
  5712. };
  5713. if (isEvented(track)) {
  5714. track.addEventListener('labelchange', track.labelchange_);
  5715. }
  5716. }
  5717. /**
  5718. * Remove a {@link Track} from the `TrackList`
  5719. *
  5720. * @param { import('./track').default } rtrack
  5721. * The audio, video, or text track to remove from the list.
  5722. *
  5723. * @fires TrackList#removetrack
  5724. */
  5725. removeTrack(rtrack) {
  5726. let track;
  5727. for (let i = 0, l = this.length; i < l; i++) {
  5728. if (this[i] === rtrack) {
  5729. track = this[i];
  5730. if (track.off) {
  5731. track.off();
  5732. }
  5733. this.tracks_.splice(i, 1);
  5734. break;
  5735. }
  5736. }
  5737. if (!track) {
  5738. return;
  5739. }
  5740. /**
  5741. * Triggered when a track is removed from track list.
  5742. *
  5743. * @event TrackList#removetrack
  5744. * @type {Event}
  5745. * @property {Track} track
  5746. * A reference to track that was removed.
  5747. */
  5748. this.trigger({
  5749. track,
  5750. type: 'removetrack',
  5751. target: this
  5752. });
  5753. }
  5754. /**
  5755. * Get a Track from the TrackList by a tracks id
  5756. *
  5757. * @param {string} id - the id of the track to get
  5758. * @method getTrackById
  5759. * @return { import('./track').default }
  5760. * @private
  5761. */
  5762. getTrackById(id) {
  5763. let result = null;
  5764. for (let i = 0, l = this.length; i < l; i++) {
  5765. const track = this[i];
  5766. if (track.id === id) {
  5767. result = track;
  5768. break;
  5769. }
  5770. }
  5771. return result;
  5772. }
  5773. }
  5774. /**
  5775. * Triggered when a different track is selected/enabled.
  5776. *
  5777. * @event TrackList#change
  5778. * @type {Event}
  5779. */
  5780. /**
  5781. * Events that can be called with on + eventName. See {@link EventHandler}.
  5782. *
  5783. * @property {Object} TrackList#allowedEvents_
  5784. * @private
  5785. */
  5786. TrackList.prototype.allowedEvents_ = {
  5787. change: 'change',
  5788. addtrack: 'addtrack',
  5789. removetrack: 'removetrack',
  5790. labelchange: 'labelchange'
  5791. };
  5792. // emulate attribute EventHandler support to allow for feature detection
  5793. for (const event in TrackList.prototype.allowedEvents_) {
  5794. TrackList.prototype['on' + event] = null;
  5795. }
  5796. /**
  5797. * @file audio-track-list.js
  5798. */
  5799. /**
  5800. * Anywhere we call this function we diverge from the spec
  5801. * as we only support one enabled audiotrack at a time
  5802. *
  5803. * @param {AudioTrackList} list
  5804. * list to work on
  5805. *
  5806. * @param { import('./audio-track').default } track
  5807. * The track to skip
  5808. *
  5809. * @private
  5810. */
  5811. const disableOthers$1 = function (list, track) {
  5812. for (let i = 0; i < list.length; i++) {
  5813. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5814. continue;
  5815. }
  5816. // another audio track is enabled, disable it
  5817. list[i].enabled = false;
  5818. }
  5819. };
  5820. /**
  5821. * The current list of {@link AudioTrack} for a media file.
  5822. *
  5823. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5824. * @extends TrackList
  5825. */
  5826. class AudioTrackList extends TrackList {
  5827. /**
  5828. * Create an instance of this class.
  5829. *
  5830. * @param {AudioTrack[]} [tracks=[]]
  5831. * A list of `AudioTrack` to instantiate the list with.
  5832. */
  5833. constructor(tracks = []) {
  5834. // make sure only 1 track is enabled
  5835. // sorted from last index to first index
  5836. for (let i = tracks.length - 1; i >= 0; i--) {
  5837. if (tracks[i].enabled) {
  5838. disableOthers$1(tracks, tracks[i]);
  5839. break;
  5840. }
  5841. }
  5842. super(tracks);
  5843. this.changing_ = false;
  5844. }
  5845. /**
  5846. * Add an {@link AudioTrack} to the `AudioTrackList`.
  5847. *
  5848. * @param { import('./audio-track').default } track
  5849. * The AudioTrack to add to the list
  5850. *
  5851. * @fires TrackList#addtrack
  5852. */
  5853. addTrack(track) {
  5854. if (track.enabled) {
  5855. disableOthers$1(this, track);
  5856. }
  5857. super.addTrack(track);
  5858. // native tracks don't have this
  5859. if (!track.addEventListener) {
  5860. return;
  5861. }
  5862. track.enabledChange_ = () => {
  5863. // when we are disabling other tracks (since we don't support
  5864. // more than one track at a time) we will set changing_
  5865. // to true so that we don't trigger additional change events
  5866. if (this.changing_) {
  5867. return;
  5868. }
  5869. this.changing_ = true;
  5870. disableOthers$1(this, track);
  5871. this.changing_ = false;
  5872. this.trigger('change');
  5873. };
  5874. /**
  5875. * @listens AudioTrack#enabledchange
  5876. * @fires TrackList#change
  5877. */
  5878. track.addEventListener('enabledchange', track.enabledChange_);
  5879. }
  5880. removeTrack(rtrack) {
  5881. super.removeTrack(rtrack);
  5882. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  5883. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  5884. rtrack.enabledChange_ = null;
  5885. }
  5886. }
  5887. }
  5888. /**
  5889. * @file video-track-list.js
  5890. */
  5891. /**
  5892. * Un-select all other {@link VideoTrack}s that are selected.
  5893. *
  5894. * @param {VideoTrackList} list
  5895. * list to work on
  5896. *
  5897. * @param { import('./video-track').default } track
  5898. * The track to skip
  5899. *
  5900. * @private
  5901. */
  5902. const disableOthers = function (list, track) {
  5903. for (let i = 0; i < list.length; i++) {
  5904. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5905. continue;
  5906. }
  5907. // another video track is enabled, disable it
  5908. list[i].selected = false;
  5909. }
  5910. };
  5911. /**
  5912. * The current list of {@link VideoTrack} for a video.
  5913. *
  5914. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  5915. * @extends TrackList
  5916. */
  5917. class VideoTrackList extends TrackList {
  5918. /**
  5919. * Create an instance of this class.
  5920. *
  5921. * @param {VideoTrack[]} [tracks=[]]
  5922. * A list of `VideoTrack` to instantiate the list with.
  5923. */
  5924. constructor(tracks = []) {
  5925. // make sure only 1 track is enabled
  5926. // sorted from last index to first index
  5927. for (let i = tracks.length - 1; i >= 0; i--) {
  5928. if (tracks[i].selected) {
  5929. disableOthers(tracks, tracks[i]);
  5930. break;
  5931. }
  5932. }
  5933. super(tracks);
  5934. this.changing_ = false;
  5935. /**
  5936. * @member {number} VideoTrackList#selectedIndex
  5937. * The current index of the selected {@link VideoTrack`}.
  5938. */
  5939. Object.defineProperty(this, 'selectedIndex', {
  5940. get() {
  5941. for (let i = 0; i < this.length; i++) {
  5942. if (this[i].selected) {
  5943. return i;
  5944. }
  5945. }
  5946. return -1;
  5947. },
  5948. set() {}
  5949. });
  5950. }
  5951. /**
  5952. * Add a {@link VideoTrack} to the `VideoTrackList`.
  5953. *
  5954. * @param { import('./video-track').default } track
  5955. * The VideoTrack to add to the list
  5956. *
  5957. * @fires TrackList#addtrack
  5958. */
  5959. addTrack(track) {
  5960. if (track.selected) {
  5961. disableOthers(this, track);
  5962. }
  5963. super.addTrack(track);
  5964. // native tracks don't have this
  5965. if (!track.addEventListener) {
  5966. return;
  5967. }
  5968. track.selectedChange_ = () => {
  5969. if (this.changing_) {
  5970. return;
  5971. }
  5972. this.changing_ = true;
  5973. disableOthers(this, track);
  5974. this.changing_ = false;
  5975. this.trigger('change');
  5976. };
  5977. /**
  5978. * @listens VideoTrack#selectedchange
  5979. * @fires TrackList#change
  5980. */
  5981. track.addEventListener('selectedchange', track.selectedChange_);
  5982. }
  5983. removeTrack(rtrack) {
  5984. super.removeTrack(rtrack);
  5985. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  5986. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  5987. rtrack.selectedChange_ = null;
  5988. }
  5989. }
  5990. }
  5991. /**
  5992. * @file text-track-list.js
  5993. */
  5994. /**
  5995. * The current list of {@link TextTrack} for a media file.
  5996. *
  5997. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  5998. * @extends TrackList
  5999. */
  6000. class TextTrackList extends TrackList {
  6001. /**
  6002. * Add a {@link TextTrack} to the `TextTrackList`
  6003. *
  6004. * @param { import('./text-track').default } track
  6005. * The text track to add to the list.
  6006. *
  6007. * @fires TrackList#addtrack
  6008. */
  6009. addTrack(track) {
  6010. super.addTrack(track);
  6011. if (!this.queueChange_) {
  6012. this.queueChange_ = () => this.queueTrigger('change');
  6013. }
  6014. if (!this.triggerSelectedlanguagechange) {
  6015. this.triggerSelectedlanguagechange_ = () => this.trigger('selectedlanguagechange');
  6016. }
  6017. /**
  6018. * @listens TextTrack#modechange
  6019. * @fires TrackList#change
  6020. */
  6021. track.addEventListener('modechange', this.queueChange_);
  6022. const nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6023. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6024. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6025. }
  6026. }
  6027. removeTrack(rtrack) {
  6028. super.removeTrack(rtrack);
  6029. // manually remove the event handlers we added
  6030. if (rtrack.removeEventListener) {
  6031. if (this.queueChange_) {
  6032. rtrack.removeEventListener('modechange', this.queueChange_);
  6033. }
  6034. if (this.selectedlanguagechange_) {
  6035. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6036. }
  6037. }
  6038. }
  6039. }
  6040. /**
  6041. * @file html-track-element-list.js
  6042. */
  6043. /**
  6044. * The current list of {@link HtmlTrackElement}s.
  6045. */
  6046. class HtmlTrackElementList {
  6047. /**
  6048. * Create an instance of this class.
  6049. *
  6050. * @param {HtmlTrackElement[]} [tracks=[]]
  6051. * A list of `HtmlTrackElement` to instantiate the list with.
  6052. */
  6053. constructor(trackElements = []) {
  6054. this.trackElements_ = [];
  6055. /**
  6056. * @memberof HtmlTrackElementList
  6057. * @member {number} length
  6058. * The current number of `Track`s in the this Trackist.
  6059. * @instance
  6060. */
  6061. Object.defineProperty(this, 'length', {
  6062. get() {
  6063. return this.trackElements_.length;
  6064. }
  6065. });
  6066. for (let i = 0, length = trackElements.length; i < length; i++) {
  6067. this.addTrackElement_(trackElements[i]);
  6068. }
  6069. }
  6070. /**
  6071. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6072. *
  6073. * @param {HtmlTrackElement} trackElement
  6074. * The track element to add to the list.
  6075. *
  6076. * @private
  6077. */
  6078. addTrackElement_(trackElement) {
  6079. const index = this.trackElements_.length;
  6080. if (!('' + index in this)) {
  6081. Object.defineProperty(this, index, {
  6082. get() {
  6083. return this.trackElements_[index];
  6084. }
  6085. });
  6086. }
  6087. // Do not add duplicate elements
  6088. if (this.trackElements_.indexOf(trackElement) === -1) {
  6089. this.trackElements_.push(trackElement);
  6090. }
  6091. }
  6092. /**
  6093. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6094. * {@link TextTrack}.
  6095. *
  6096. * @param {TextTrack} track
  6097. * The track associated with a track element.
  6098. *
  6099. * @return {HtmlTrackElement|undefined}
  6100. * The track element that was found or undefined.
  6101. *
  6102. * @private
  6103. */
  6104. getTrackElementByTrack_(track) {
  6105. let trackElement_;
  6106. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6107. if (track === this.trackElements_[i].track) {
  6108. trackElement_ = this.trackElements_[i];
  6109. break;
  6110. }
  6111. }
  6112. return trackElement_;
  6113. }
  6114. /**
  6115. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6116. *
  6117. * @param {HtmlTrackElement} trackElement
  6118. * The track element to remove from the list.
  6119. *
  6120. * @private
  6121. */
  6122. removeTrackElement_(trackElement) {
  6123. for (let i = 0, length = this.trackElements_.length; i < length; i++) {
  6124. if (trackElement === this.trackElements_[i]) {
  6125. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6126. this.trackElements_[i].track.off();
  6127. }
  6128. if (typeof this.trackElements_[i].off === 'function') {
  6129. this.trackElements_[i].off();
  6130. }
  6131. this.trackElements_.splice(i, 1);
  6132. break;
  6133. }
  6134. }
  6135. }
  6136. }
  6137. /**
  6138. * @file text-track-cue-list.js
  6139. */
  6140. /**
  6141. * @typedef {Object} TextTrackCueList~TextTrackCue
  6142. *
  6143. * @property {string} id
  6144. * The unique id for this text track cue
  6145. *
  6146. * @property {number} startTime
  6147. * The start time for this text track cue
  6148. *
  6149. * @property {number} endTime
  6150. * The end time for this text track cue
  6151. *
  6152. * @property {boolean} pauseOnExit
  6153. * Pause when the end time is reached if true.
  6154. *
  6155. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6156. */
  6157. /**
  6158. * A List of TextTrackCues.
  6159. *
  6160. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6161. */
  6162. class TextTrackCueList {
  6163. /**
  6164. * Create an instance of this class..
  6165. *
  6166. * @param {Array} cues
  6167. * A list of cues to be initialized with
  6168. */
  6169. constructor(cues) {
  6170. TextTrackCueList.prototype.setCues_.call(this, cues);
  6171. /**
  6172. * @memberof TextTrackCueList
  6173. * @member {number} length
  6174. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6175. * @instance
  6176. */
  6177. Object.defineProperty(this, 'length', {
  6178. get() {
  6179. return this.length_;
  6180. }
  6181. });
  6182. }
  6183. /**
  6184. * A setter for cues in this list. Creates getters
  6185. * an an index for the cues.
  6186. *
  6187. * @param {Array} cues
  6188. * An array of cues to set
  6189. *
  6190. * @private
  6191. */
  6192. setCues_(cues) {
  6193. const oldLength = this.length || 0;
  6194. let i = 0;
  6195. const l = cues.length;
  6196. this.cues_ = cues;
  6197. this.length_ = cues.length;
  6198. const defineProp = function (index) {
  6199. if (!('' + index in this)) {
  6200. Object.defineProperty(this, '' + index, {
  6201. get() {
  6202. return this.cues_[index];
  6203. }
  6204. });
  6205. }
  6206. };
  6207. if (oldLength < l) {
  6208. i = oldLength;
  6209. for (; i < l; i++) {
  6210. defineProp.call(this, i);
  6211. }
  6212. }
  6213. }
  6214. /**
  6215. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6216. *
  6217. * @param {string} id
  6218. * The id of the cue that should be searched for.
  6219. *
  6220. * @return {TextTrackCueList~TextTrackCue|null}
  6221. * A single cue or null if none was found.
  6222. */
  6223. getCueById(id) {
  6224. let result = null;
  6225. for (let i = 0, l = this.length; i < l; i++) {
  6226. const cue = this[i];
  6227. if (cue.id === id) {
  6228. result = cue;
  6229. break;
  6230. }
  6231. }
  6232. return result;
  6233. }
  6234. }
  6235. /**
  6236. * @file track-kinds.js
  6237. */
  6238. /**
  6239. * All possible `VideoTrackKind`s
  6240. *
  6241. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6242. * @typedef VideoTrack~Kind
  6243. * @enum
  6244. */
  6245. const VideoTrackKind = {
  6246. alternative: 'alternative',
  6247. captions: 'captions',
  6248. main: 'main',
  6249. sign: 'sign',
  6250. subtitles: 'subtitles',
  6251. commentary: 'commentary'
  6252. };
  6253. /**
  6254. * All possible `AudioTrackKind`s
  6255. *
  6256. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6257. * @typedef AudioTrack~Kind
  6258. * @enum
  6259. */
  6260. const AudioTrackKind = {
  6261. 'alternative': 'alternative',
  6262. 'descriptions': 'descriptions',
  6263. 'main': 'main',
  6264. 'main-desc': 'main-desc',
  6265. 'translation': 'translation',
  6266. 'commentary': 'commentary'
  6267. };
  6268. /**
  6269. * All possible `TextTrackKind`s
  6270. *
  6271. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6272. * @typedef TextTrack~Kind
  6273. * @enum
  6274. */
  6275. const TextTrackKind = {
  6276. subtitles: 'subtitles',
  6277. captions: 'captions',
  6278. descriptions: 'descriptions',
  6279. chapters: 'chapters',
  6280. metadata: 'metadata'
  6281. };
  6282. /**
  6283. * All possible `TextTrackMode`s
  6284. *
  6285. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6286. * @typedef TextTrack~Mode
  6287. * @enum
  6288. */
  6289. const TextTrackMode = {
  6290. disabled: 'disabled',
  6291. hidden: 'hidden',
  6292. showing: 'showing'
  6293. };
  6294. /**
  6295. * @file track.js
  6296. */
  6297. /**
  6298. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6299. * {@link VideoTrack}, and {@link TextTrack}.
  6300. *
  6301. * > Note: This class should not be used directly
  6302. *
  6303. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6304. * @extends EventTarget
  6305. * @abstract
  6306. */
  6307. class Track extends EventTarget$2 {
  6308. /**
  6309. * Create an instance of this class.
  6310. *
  6311. * @param {Object} [options={}]
  6312. * Object of option names and values
  6313. *
  6314. * @param {string} [options.kind='']
  6315. * A valid kind for the track type you are creating.
  6316. *
  6317. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6318. * A unique id for this AudioTrack.
  6319. *
  6320. * @param {string} [options.label='']
  6321. * The menu label for this track.
  6322. *
  6323. * @param {string} [options.language='']
  6324. * A valid two character language code.
  6325. *
  6326. * @abstract
  6327. */
  6328. constructor(options = {}) {
  6329. super();
  6330. const trackProps = {
  6331. id: options.id || 'vjs_track_' + newGUID(),
  6332. kind: options.kind || '',
  6333. language: options.language || ''
  6334. };
  6335. let label = options.label || '';
  6336. /**
  6337. * @memberof Track
  6338. * @member {string} id
  6339. * The id of this track. Cannot be changed after creation.
  6340. * @instance
  6341. *
  6342. * @readonly
  6343. */
  6344. /**
  6345. * @memberof Track
  6346. * @member {string} kind
  6347. * The kind of track that this is. Cannot be changed after creation.
  6348. * @instance
  6349. *
  6350. * @readonly
  6351. */
  6352. /**
  6353. * @memberof Track
  6354. * @member {string} language
  6355. * The two letter language code for this track. Cannot be changed after
  6356. * creation.
  6357. * @instance
  6358. *
  6359. * @readonly
  6360. */
  6361. for (const key in trackProps) {
  6362. Object.defineProperty(this, key, {
  6363. get() {
  6364. return trackProps[key];
  6365. },
  6366. set() {}
  6367. });
  6368. }
  6369. /**
  6370. * @memberof Track
  6371. * @member {string} label
  6372. * The label of this track. Cannot be changed after creation.
  6373. * @instance
  6374. *
  6375. * @fires Track#labelchange
  6376. */
  6377. Object.defineProperty(this, 'label', {
  6378. get() {
  6379. return label;
  6380. },
  6381. set(newLabel) {
  6382. if (newLabel !== label) {
  6383. label = newLabel;
  6384. /**
  6385. * An event that fires when label changes on this track.
  6386. *
  6387. * > Note: This is not part of the spec!
  6388. *
  6389. * @event Track#labelchange
  6390. * @type {Event}
  6391. */
  6392. this.trigger('labelchange');
  6393. }
  6394. }
  6395. });
  6396. }
  6397. }
  6398. /**
  6399. * @file url.js
  6400. * @module url
  6401. */
  6402. /**
  6403. * @typedef {Object} url:URLObject
  6404. *
  6405. * @property {string} protocol
  6406. * The protocol of the url that was parsed.
  6407. *
  6408. * @property {string} hostname
  6409. * The hostname of the url that was parsed.
  6410. *
  6411. * @property {string} port
  6412. * The port of the url that was parsed.
  6413. *
  6414. * @property {string} pathname
  6415. * The pathname of the url that was parsed.
  6416. *
  6417. * @property {string} search
  6418. * The search query of the url that was parsed.
  6419. *
  6420. * @property {string} hash
  6421. * The hash of the url that was parsed.
  6422. *
  6423. * @property {string} host
  6424. * The host of the url that was parsed.
  6425. */
  6426. /**
  6427. * Resolve and parse the elements of a URL.
  6428. *
  6429. * @function
  6430. * @param {String} url
  6431. * The url to parse
  6432. *
  6433. * @return {url:URLObject}
  6434. * An object of url details
  6435. */
  6436. const parseUrl = function (url) {
  6437. // This entire method can be replace with URL once we are able to drop IE11
  6438. const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
  6439. // add the url to an anchor and let the browser parse the URL
  6440. const a = document__default["default"].createElement('a');
  6441. a.href = url;
  6442. // Copy the specific URL properties to a new object
  6443. // This is also needed for IE because the anchor loses its
  6444. // properties when it's removed from the dom
  6445. const details = {};
  6446. for (let i = 0; i < props.length; i++) {
  6447. details[props[i]] = a[props[i]];
  6448. }
  6449. // IE adds the port to the host property unlike everyone else. If
  6450. // a port identifier is added for standard ports, strip it.
  6451. if (details.protocol === 'http:') {
  6452. details.host = details.host.replace(/:80$/, '');
  6453. }
  6454. if (details.protocol === 'https:') {
  6455. details.host = details.host.replace(/:443$/, '');
  6456. }
  6457. if (!details.protocol) {
  6458. details.protocol = window__default["default"].location.protocol;
  6459. }
  6460. /* istanbul ignore if */
  6461. if (!details.host) {
  6462. details.host = window__default["default"].location.host;
  6463. }
  6464. return details;
  6465. };
  6466. /**
  6467. * Get absolute version of relative URL.
  6468. *
  6469. * @function
  6470. * @param {string} url
  6471. * URL to make absolute
  6472. *
  6473. * @return {string}
  6474. * Absolute URL
  6475. *
  6476. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6477. */
  6478. const getAbsoluteURL = function (url) {
  6479. // Check if absolute URL
  6480. if (!url.match(/^https?:\/\//)) {
  6481. // Add the url to an anchor and let the browser parse it to convert to an absolute url
  6482. const a = document__default["default"].createElement('a');
  6483. a.href = url;
  6484. url = a.href;
  6485. }
  6486. return url;
  6487. };
  6488. /**
  6489. * Returns the extension of the passed file name. It will return an empty string
  6490. * if passed an invalid path.
  6491. *
  6492. * @function
  6493. * @param {string} path
  6494. * The fileName path like '/path/to/file.mp4'
  6495. *
  6496. * @return {string}
  6497. * The extension in lower case or an empty string if no
  6498. * extension could be found.
  6499. */
  6500. const getFileExtension = function (path) {
  6501. if (typeof path === 'string') {
  6502. const splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6503. const pathParts = splitPathRe.exec(path);
  6504. if (pathParts) {
  6505. return pathParts.pop().toLowerCase();
  6506. }
  6507. }
  6508. return '';
  6509. };
  6510. /**
  6511. * Returns whether the url passed is a cross domain request or not.
  6512. *
  6513. * @function
  6514. * @param {string} url
  6515. * The url to check.
  6516. *
  6517. * @param {Object} [winLoc]
  6518. * the domain to check the url against, defaults to window.location
  6519. *
  6520. * @param {string} [winLoc.protocol]
  6521. * The window location protocol defaults to window.location.protocol
  6522. *
  6523. * @param {string} [winLoc.host]
  6524. * The window location host defaults to window.location.host
  6525. *
  6526. * @return {boolean}
  6527. * Whether it is a cross domain request or not.
  6528. */
  6529. const isCrossOrigin = function (url, winLoc = window__default["default"].location) {
  6530. const urlInfo = parseUrl(url);
  6531. // IE8 protocol relative urls will return ':' for protocol
  6532. const srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol;
  6533. // Check if url is for another domain/origin
  6534. // IE8 doesn't know location.origin, so we won't rely on it here
  6535. const crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6536. return crossOrigin;
  6537. };
  6538. var Url = /*#__PURE__*/Object.freeze({
  6539. __proto__: null,
  6540. parseUrl: parseUrl,
  6541. getAbsoluteURL: getAbsoluteURL,
  6542. getFileExtension: getFileExtension,
  6543. isCrossOrigin: isCrossOrigin
  6544. });
  6545. /**
  6546. * @file text-track.js
  6547. */
  6548. /**
  6549. * Takes a webvtt file contents and parses it into cues
  6550. *
  6551. * @param {string} srcContent
  6552. * webVTT file contents
  6553. *
  6554. * @param {TextTrack} track
  6555. * TextTrack to add cues to. Cues come from the srcContent.
  6556. *
  6557. * @private
  6558. */
  6559. const parseCues = function (srcContent, track) {
  6560. const parser = new window__default["default"].WebVTT.Parser(window__default["default"], window__default["default"].vttjs, window__default["default"].WebVTT.StringDecoder());
  6561. const errors = [];
  6562. parser.oncue = function (cue) {
  6563. track.addCue(cue);
  6564. };
  6565. parser.onparsingerror = function (error) {
  6566. errors.push(error);
  6567. };
  6568. parser.onflush = function () {
  6569. track.trigger({
  6570. type: 'loadeddata',
  6571. target: track
  6572. });
  6573. };
  6574. parser.parse(srcContent);
  6575. if (errors.length > 0) {
  6576. if (window__default["default"].console && window__default["default"].console.groupCollapsed) {
  6577. window__default["default"].console.groupCollapsed(`Text Track parsing errors for ${track.src}`);
  6578. }
  6579. errors.forEach(error => log$1.error(error));
  6580. if (window__default["default"].console && window__default["default"].console.groupEnd) {
  6581. window__default["default"].console.groupEnd();
  6582. }
  6583. }
  6584. parser.flush();
  6585. };
  6586. /**
  6587. * Load a `TextTrack` from a specified url.
  6588. *
  6589. * @param {string} src
  6590. * Url to load track from.
  6591. *
  6592. * @param {TextTrack} track
  6593. * Track to add cues to. Comes from the content at the end of `url`.
  6594. *
  6595. * @private
  6596. */
  6597. const loadTrack = function (src, track) {
  6598. const opts = {
  6599. uri: src
  6600. };
  6601. const crossOrigin = isCrossOrigin(src);
  6602. if (crossOrigin) {
  6603. opts.cors = crossOrigin;
  6604. }
  6605. const withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  6606. if (withCredentials) {
  6607. opts.withCredentials = withCredentials;
  6608. }
  6609. XHR__default["default"](opts, bind_(this, function (err, response, responseBody) {
  6610. if (err) {
  6611. return log$1.error(err, response);
  6612. }
  6613. track.loaded_ = true;
  6614. // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  6615. // NOTE: this is only used for the alt/video.novtt.js build
  6616. if (typeof window__default["default"].WebVTT !== 'function') {
  6617. if (track.tech_) {
  6618. // to prevent use before define eslint error, we define loadHandler
  6619. // as a let here
  6620. track.tech_.any(['vttjsloaded', 'vttjserror'], event => {
  6621. if (event.type === 'vttjserror') {
  6622. log$1.error(`vttjs failed to load, stopping trying to process ${track.src}`);
  6623. return;
  6624. }
  6625. return parseCues(responseBody, track);
  6626. });
  6627. }
  6628. } else {
  6629. parseCues(responseBody, track);
  6630. }
  6631. }));
  6632. };
  6633. /**
  6634. * A representation of a single `TextTrack`.
  6635. *
  6636. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  6637. * @extends Track
  6638. */
  6639. class TextTrack extends Track {
  6640. /**
  6641. * Create an instance of this class.
  6642. *
  6643. * @param {Object} options={}
  6644. * Object of option names and values
  6645. *
  6646. * @param { import('../tech/tech').default } options.tech
  6647. * A reference to the tech that owns this TextTrack.
  6648. *
  6649. * @param {TextTrack~Kind} [options.kind='subtitles']
  6650. * A valid text track kind.
  6651. *
  6652. * @param {TextTrack~Mode} [options.mode='disabled']
  6653. * A valid text track mode.
  6654. *
  6655. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6656. * A unique id for this TextTrack.
  6657. *
  6658. * @param {string} [options.label='']
  6659. * The menu label for this track.
  6660. *
  6661. * @param {string} [options.language='']
  6662. * A valid two character language code.
  6663. *
  6664. * @param {string} [options.srclang='']
  6665. * A valid two character language code. An alternative, but deprioritized
  6666. * version of `options.language`
  6667. *
  6668. * @param {string} [options.src]
  6669. * A url to TextTrack cues.
  6670. *
  6671. * @param {boolean} [options.default]
  6672. * If this track should default to on or off.
  6673. */
  6674. constructor(options = {}) {
  6675. if (!options.tech) {
  6676. throw new Error('A tech was not provided.');
  6677. }
  6678. const settings = merge$1(options, {
  6679. kind: TextTrackKind[options.kind] || 'subtitles',
  6680. language: options.language || options.srclang || ''
  6681. });
  6682. let mode = TextTrackMode[settings.mode] || 'disabled';
  6683. const default_ = settings.default;
  6684. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  6685. mode = 'hidden';
  6686. }
  6687. super(settings);
  6688. this.tech_ = settings.tech;
  6689. this.cues_ = [];
  6690. this.activeCues_ = [];
  6691. this.preload_ = this.tech_.preloadTextTracks !== false;
  6692. const cues = new TextTrackCueList(this.cues_);
  6693. const activeCues = new TextTrackCueList(this.activeCues_);
  6694. let changed = false;
  6695. this.timeupdateHandler = bind_(this, function (event = {}) {
  6696. if (this.tech_.isDisposed()) {
  6697. return;
  6698. }
  6699. if (!this.tech_.isReady_) {
  6700. if (event.type !== 'timeupdate') {
  6701. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6702. }
  6703. return;
  6704. }
  6705. // Accessing this.activeCues for the side-effects of updating itself
  6706. // due to its nature as a getter function. Do not remove or cues will
  6707. // stop updating!
  6708. // Use the setter to prevent deletion from uglify (pure_getters rule)
  6709. this.activeCues = this.activeCues;
  6710. if (changed) {
  6711. this.trigger('cuechange');
  6712. changed = false;
  6713. }
  6714. if (event.type !== 'timeupdate') {
  6715. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6716. }
  6717. });
  6718. const disposeHandler = () => {
  6719. this.stopTracking();
  6720. };
  6721. this.tech_.one('dispose', disposeHandler);
  6722. if (mode !== 'disabled') {
  6723. this.startTracking();
  6724. }
  6725. Object.defineProperties(this, {
  6726. /**
  6727. * @memberof TextTrack
  6728. * @member {boolean} default
  6729. * If this track was set to be on or off by default. Cannot be changed after
  6730. * creation.
  6731. * @instance
  6732. *
  6733. * @readonly
  6734. */
  6735. default: {
  6736. get() {
  6737. return default_;
  6738. },
  6739. set() {}
  6740. },
  6741. /**
  6742. * @memberof TextTrack
  6743. * @member {string} mode
  6744. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  6745. * not be set if setting to an invalid mode.
  6746. * @instance
  6747. *
  6748. * @fires TextTrack#modechange
  6749. */
  6750. mode: {
  6751. get() {
  6752. return mode;
  6753. },
  6754. set(newMode) {
  6755. if (!TextTrackMode[newMode]) {
  6756. return;
  6757. }
  6758. if (mode === newMode) {
  6759. return;
  6760. }
  6761. mode = newMode;
  6762. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  6763. // On-demand load.
  6764. loadTrack(this.src, this);
  6765. }
  6766. this.stopTracking();
  6767. if (mode !== 'disabled') {
  6768. this.startTracking();
  6769. }
  6770. /**
  6771. * An event that fires when mode changes on this track. This allows
  6772. * the TextTrackList that holds this track to act accordingly.
  6773. *
  6774. * > Note: This is not part of the spec!
  6775. *
  6776. * @event TextTrack#modechange
  6777. * @type {Event}
  6778. */
  6779. this.trigger('modechange');
  6780. }
  6781. },
  6782. /**
  6783. * @memberof TextTrack
  6784. * @member {TextTrackCueList} cues
  6785. * The text track cue list for this TextTrack.
  6786. * @instance
  6787. */
  6788. cues: {
  6789. get() {
  6790. if (!this.loaded_) {
  6791. return null;
  6792. }
  6793. return cues;
  6794. },
  6795. set() {}
  6796. },
  6797. /**
  6798. * @memberof TextTrack
  6799. * @member {TextTrackCueList} activeCues
  6800. * The list text track cues that are currently active for this TextTrack.
  6801. * @instance
  6802. */
  6803. activeCues: {
  6804. get() {
  6805. if (!this.loaded_) {
  6806. return null;
  6807. }
  6808. // nothing to do
  6809. if (this.cues.length === 0) {
  6810. return activeCues;
  6811. }
  6812. const ct = this.tech_.currentTime();
  6813. const active = [];
  6814. for (let i = 0, l = this.cues.length; i < l; i++) {
  6815. const cue = this.cues[i];
  6816. if (cue.startTime <= ct && cue.endTime >= ct) {
  6817. active.push(cue);
  6818. }
  6819. }
  6820. changed = false;
  6821. if (active.length !== this.activeCues_.length) {
  6822. changed = true;
  6823. } else {
  6824. for (let i = 0; i < active.length; i++) {
  6825. if (this.activeCues_.indexOf(active[i]) === -1) {
  6826. changed = true;
  6827. }
  6828. }
  6829. }
  6830. this.activeCues_ = active;
  6831. activeCues.setCues_(this.activeCues_);
  6832. return activeCues;
  6833. },
  6834. // /!\ Keep this setter empty (see the timeupdate handler above)
  6835. set() {}
  6836. }
  6837. });
  6838. if (settings.src) {
  6839. this.src = settings.src;
  6840. if (!this.preload_) {
  6841. // Tracks will load on-demand.
  6842. // Act like we're loaded for other purposes.
  6843. this.loaded_ = true;
  6844. }
  6845. if (this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  6846. loadTrack(this.src, this);
  6847. }
  6848. } else {
  6849. this.loaded_ = true;
  6850. }
  6851. }
  6852. startTracking() {
  6853. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  6854. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6855. // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  6856. this.tech_.on('timeupdate', this.timeupdateHandler);
  6857. }
  6858. stopTracking() {
  6859. if (this.rvf_) {
  6860. this.tech_.cancelVideoFrameCallback(this.rvf_);
  6861. this.rvf_ = undefined;
  6862. }
  6863. this.tech_.off('timeupdate', this.timeupdateHandler);
  6864. }
  6865. /**
  6866. * Add a cue to the internal list of cues.
  6867. *
  6868. * @param {TextTrack~Cue} cue
  6869. * The cue to add to our internal list
  6870. */
  6871. addCue(originalCue) {
  6872. let cue = originalCue;
  6873. if (window__default["default"].vttjs && !(originalCue instanceof window__default["default"].vttjs.VTTCue)) {
  6874. cue = new window__default["default"].vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  6875. for (const prop in originalCue) {
  6876. if (!(prop in cue)) {
  6877. cue[prop] = originalCue[prop];
  6878. }
  6879. }
  6880. // make sure that `id` is copied over
  6881. cue.id = originalCue.id;
  6882. cue.originalCue_ = originalCue;
  6883. }
  6884. const tracks = this.tech_.textTracks();
  6885. for (let i = 0; i < tracks.length; i++) {
  6886. if (tracks[i] !== this) {
  6887. tracks[i].removeCue(cue);
  6888. }
  6889. }
  6890. this.cues_.push(cue);
  6891. this.cues.setCues_(this.cues_);
  6892. }
  6893. /**
  6894. * Remove a cue from our internal list
  6895. *
  6896. * @param {TextTrack~Cue} removeCue
  6897. * The cue to remove from our internal list
  6898. */
  6899. removeCue(removeCue) {
  6900. let i = this.cues_.length;
  6901. while (i--) {
  6902. const cue = this.cues_[i];
  6903. if (cue === removeCue || cue.originalCue_ && cue.originalCue_ === removeCue) {
  6904. this.cues_.splice(i, 1);
  6905. this.cues.setCues_(this.cues_);
  6906. break;
  6907. }
  6908. }
  6909. }
  6910. }
  6911. /**
  6912. * cuechange - One or more cues in the track have become active or stopped being active.
  6913. */
  6914. TextTrack.prototype.allowedEvents_ = {
  6915. cuechange: 'cuechange'
  6916. };
  6917. /**
  6918. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  6919. * only one `AudioTrack` in the list will be enabled at a time.
  6920. *
  6921. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  6922. * @extends Track
  6923. */
  6924. class AudioTrack extends Track {
  6925. /**
  6926. * Create an instance of this class.
  6927. *
  6928. * @param {Object} [options={}]
  6929. * Object of option names and values
  6930. *
  6931. * @param {AudioTrack~Kind} [options.kind='']
  6932. * A valid audio track kind
  6933. *
  6934. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6935. * A unique id for this AudioTrack.
  6936. *
  6937. * @param {string} [options.label='']
  6938. * The menu label for this track.
  6939. *
  6940. * @param {string} [options.language='']
  6941. * A valid two character language code.
  6942. *
  6943. * @param {boolean} [options.enabled]
  6944. * If this track is the one that is currently playing. If this track is part of
  6945. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  6946. */
  6947. constructor(options = {}) {
  6948. const settings = merge$1(options, {
  6949. kind: AudioTrackKind[options.kind] || ''
  6950. });
  6951. super(settings);
  6952. let enabled = false;
  6953. /**
  6954. * @memberof AudioTrack
  6955. * @member {boolean} enabled
  6956. * If this `AudioTrack` is enabled or not. When setting this will
  6957. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  6958. * @instance
  6959. *
  6960. * @fires VideoTrack#selectedchange
  6961. */
  6962. Object.defineProperty(this, 'enabled', {
  6963. get() {
  6964. return enabled;
  6965. },
  6966. set(newEnabled) {
  6967. // an invalid or unchanged value
  6968. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  6969. return;
  6970. }
  6971. enabled = newEnabled;
  6972. /**
  6973. * An event that fires when enabled changes on this track. This allows
  6974. * the AudioTrackList that holds this track to act accordingly.
  6975. *
  6976. * > Note: This is not part of the spec! Native tracks will do
  6977. * this internally without an event.
  6978. *
  6979. * @event AudioTrack#enabledchange
  6980. * @type {Event}
  6981. */
  6982. this.trigger('enabledchange');
  6983. }
  6984. });
  6985. // if the user sets this track to selected then
  6986. // set selected to that true value otherwise
  6987. // we keep it false
  6988. if (settings.enabled) {
  6989. this.enabled = settings.enabled;
  6990. }
  6991. this.loaded_ = true;
  6992. }
  6993. }
  6994. /**
  6995. * A representation of a single `VideoTrack`.
  6996. *
  6997. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  6998. * @extends Track
  6999. */
  7000. class VideoTrack extends Track {
  7001. /**
  7002. * Create an instance of this class.
  7003. *
  7004. * @param {Object} [options={}]
  7005. * Object of option names and values
  7006. *
  7007. * @param {string} [options.kind='']
  7008. * A valid {@link VideoTrack~Kind}
  7009. *
  7010. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7011. * A unique id for this AudioTrack.
  7012. *
  7013. * @param {string} [options.label='']
  7014. * The menu label for this track.
  7015. *
  7016. * @param {string} [options.language='']
  7017. * A valid two character language code.
  7018. *
  7019. * @param {boolean} [options.selected]
  7020. * If this track is the one that is currently playing.
  7021. */
  7022. constructor(options = {}) {
  7023. const settings = merge$1(options, {
  7024. kind: VideoTrackKind[options.kind] || ''
  7025. });
  7026. super(settings);
  7027. let selected = false;
  7028. /**
  7029. * @memberof VideoTrack
  7030. * @member {boolean} selected
  7031. * If this `VideoTrack` is selected or not. When setting this will
  7032. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7033. * @instance
  7034. *
  7035. * @fires VideoTrack#selectedchange
  7036. */
  7037. Object.defineProperty(this, 'selected', {
  7038. get() {
  7039. return selected;
  7040. },
  7041. set(newSelected) {
  7042. // an invalid or unchanged value
  7043. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7044. return;
  7045. }
  7046. selected = newSelected;
  7047. /**
  7048. * An event that fires when selected changes on this track. This allows
  7049. * the VideoTrackList that holds this track to act accordingly.
  7050. *
  7051. * > Note: This is not part of the spec! Native tracks will do
  7052. * this internally without an event.
  7053. *
  7054. * @event VideoTrack#selectedchange
  7055. * @type {Event}
  7056. */
  7057. this.trigger('selectedchange');
  7058. }
  7059. });
  7060. // if the user sets this track to selected then
  7061. // set selected to that true value otherwise
  7062. // we keep it false
  7063. if (settings.selected) {
  7064. this.selected = settings.selected;
  7065. }
  7066. }
  7067. }
  7068. /**
  7069. * @file html-track-element.js
  7070. */
  7071. /**
  7072. * A single track represented in the DOM.
  7073. *
  7074. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7075. * @extends EventTarget
  7076. */
  7077. class HTMLTrackElement extends EventTarget$2 {
  7078. /**
  7079. * Create an instance of this class.
  7080. *
  7081. * @param {Object} options={}
  7082. * Object of option names and values
  7083. *
  7084. * @param { import('../tech/tech').default } options.tech
  7085. * A reference to the tech that owns this HTMLTrackElement.
  7086. *
  7087. * @param {TextTrack~Kind} [options.kind='subtitles']
  7088. * A valid text track kind.
  7089. *
  7090. * @param {TextTrack~Mode} [options.mode='disabled']
  7091. * A valid text track mode.
  7092. *
  7093. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7094. * A unique id for this TextTrack.
  7095. *
  7096. * @param {string} [options.label='']
  7097. * The menu label for this track.
  7098. *
  7099. * @param {string} [options.language='']
  7100. * A valid two character language code.
  7101. *
  7102. * @param {string} [options.srclang='']
  7103. * A valid two character language code. An alternative, but deprioritized
  7104. * version of `options.language`
  7105. *
  7106. * @param {string} [options.src]
  7107. * A url to TextTrack cues.
  7108. *
  7109. * @param {boolean} [options.default]
  7110. * If this track should default to on or off.
  7111. */
  7112. constructor(options = {}) {
  7113. super();
  7114. let readyState;
  7115. const track = new TextTrack(options);
  7116. this.kind = track.kind;
  7117. this.src = track.src;
  7118. this.srclang = track.language;
  7119. this.label = track.label;
  7120. this.default = track.default;
  7121. Object.defineProperties(this, {
  7122. /**
  7123. * @memberof HTMLTrackElement
  7124. * @member {HTMLTrackElement~ReadyState} readyState
  7125. * The current ready state of the track element.
  7126. * @instance
  7127. */
  7128. readyState: {
  7129. get() {
  7130. return readyState;
  7131. }
  7132. },
  7133. /**
  7134. * @memberof HTMLTrackElement
  7135. * @member {TextTrack} track
  7136. * The underlying TextTrack object.
  7137. * @instance
  7138. *
  7139. */
  7140. track: {
  7141. get() {
  7142. return track;
  7143. }
  7144. }
  7145. });
  7146. readyState = HTMLTrackElement.NONE;
  7147. /**
  7148. * @listens TextTrack#loadeddata
  7149. * @fires HTMLTrackElement#load
  7150. */
  7151. track.addEventListener('loadeddata', () => {
  7152. readyState = HTMLTrackElement.LOADED;
  7153. this.trigger({
  7154. type: 'load',
  7155. target: this
  7156. });
  7157. });
  7158. }
  7159. }
  7160. HTMLTrackElement.prototype.allowedEvents_ = {
  7161. load: 'load'
  7162. };
  7163. /**
  7164. * The text track not loaded state.
  7165. *
  7166. * @type {number}
  7167. * @static
  7168. */
  7169. HTMLTrackElement.NONE = 0;
  7170. /**
  7171. * The text track loading state.
  7172. *
  7173. * @type {number}
  7174. * @static
  7175. */
  7176. HTMLTrackElement.LOADING = 1;
  7177. /**
  7178. * The text track loaded state.
  7179. *
  7180. * @type {number}
  7181. * @static
  7182. */
  7183. HTMLTrackElement.LOADED = 2;
  7184. /**
  7185. * The text track failed to load state.
  7186. *
  7187. * @type {number}
  7188. * @static
  7189. */
  7190. HTMLTrackElement.ERROR = 3;
  7191. /*
  7192. * This file contains all track properties that are used in
  7193. * player.js, tech.js, html5.js and possibly other techs in the future.
  7194. */
  7195. const NORMAL = {
  7196. audio: {
  7197. ListClass: AudioTrackList,
  7198. TrackClass: AudioTrack,
  7199. capitalName: 'Audio'
  7200. },
  7201. video: {
  7202. ListClass: VideoTrackList,
  7203. TrackClass: VideoTrack,
  7204. capitalName: 'Video'
  7205. },
  7206. text: {
  7207. ListClass: TextTrackList,
  7208. TrackClass: TextTrack,
  7209. capitalName: 'Text'
  7210. }
  7211. };
  7212. Object.keys(NORMAL).forEach(function (type) {
  7213. NORMAL[type].getterName = `${type}Tracks`;
  7214. NORMAL[type].privateName = `${type}Tracks_`;
  7215. });
  7216. const REMOTE = {
  7217. remoteText: {
  7218. ListClass: TextTrackList,
  7219. TrackClass: TextTrack,
  7220. capitalName: 'RemoteText',
  7221. getterName: 'remoteTextTracks',
  7222. privateName: 'remoteTextTracks_'
  7223. },
  7224. remoteTextEl: {
  7225. ListClass: HtmlTrackElementList,
  7226. TrackClass: HTMLTrackElement,
  7227. capitalName: 'RemoteTextTrackEls',
  7228. getterName: 'remoteTextTrackEls',
  7229. privateName: 'remoteTextTrackEls_'
  7230. }
  7231. };
  7232. const ALL = Object.assign({}, NORMAL, REMOTE);
  7233. REMOTE.names = Object.keys(REMOTE);
  7234. NORMAL.names = Object.keys(NORMAL);
  7235. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7236. /**
  7237. * @file tech.js
  7238. */
  7239. /**
  7240. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7241. * that just contains the src url alone.
  7242. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7243. * `var SourceString = 'http://example.com/some-video.mp4';`
  7244. *
  7245. * @typedef {Object|string} Tech~SourceObject
  7246. *
  7247. * @property {string} src
  7248. * The url to the source
  7249. *
  7250. * @property {string} type
  7251. * The mime type of the source
  7252. */
  7253. /**
  7254. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7255. *
  7256. * @private
  7257. *
  7258. * @param {Tech} self
  7259. * An instance of the Tech class.
  7260. *
  7261. * @param {string} kind
  7262. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7263. *
  7264. * @param {string} [label]
  7265. * Label to identify the text track
  7266. *
  7267. * @param {string} [language]
  7268. * Two letter language abbreviation
  7269. *
  7270. * @param {Object} [options={}]
  7271. * An object with additional text track options
  7272. *
  7273. * @return {TextTrack}
  7274. * The text track that was created.
  7275. */
  7276. function createTrackHelper(self, kind, label, language, options = {}) {
  7277. const tracks = self.textTracks();
  7278. options.kind = kind;
  7279. if (label) {
  7280. options.label = label;
  7281. }
  7282. if (language) {
  7283. options.language = language;
  7284. }
  7285. options.tech = self;
  7286. const track = new ALL.text.TrackClass(options);
  7287. tracks.addTrack(track);
  7288. return track;
  7289. }
  7290. /**
  7291. * This is the base class for media playback technology controllers, such as
  7292. * {@link HTML5}
  7293. *
  7294. * @extends Component
  7295. */
  7296. class Tech extends Component$1 {
  7297. /**
  7298. * Create an instance of this Tech.
  7299. *
  7300. * @param {Object} [options]
  7301. * The key/value store of player options.
  7302. *
  7303. * @param {Function} [ready]
  7304. * Callback function to call when the `HTML5` Tech is ready.
  7305. */
  7306. constructor(options = {}, ready = function () {}) {
  7307. // we don't want the tech to report user activity automatically.
  7308. // This is done manually in addControlsListeners
  7309. options.reportTouchActivity = false;
  7310. super(null, options, ready);
  7311. this.onDurationChange_ = e => this.onDurationChange(e);
  7312. this.trackProgress_ = e => this.trackProgress(e);
  7313. this.trackCurrentTime_ = e => this.trackCurrentTime(e);
  7314. this.stopTrackingCurrentTime_ = e => this.stopTrackingCurrentTime(e);
  7315. this.disposeSourceHandler_ = e => this.disposeSourceHandler(e);
  7316. this.queuedHanders_ = new Set();
  7317. // keep track of whether the current source has played at all to
  7318. // implement a very limited played()
  7319. this.hasStarted_ = false;
  7320. this.on('playing', function () {
  7321. this.hasStarted_ = true;
  7322. });
  7323. this.on('loadstart', function () {
  7324. this.hasStarted_ = false;
  7325. });
  7326. ALL.names.forEach(name => {
  7327. const props = ALL[name];
  7328. if (options && options[props.getterName]) {
  7329. this[props.privateName] = options[props.getterName];
  7330. }
  7331. });
  7332. // Manually track progress in cases where the browser/tech doesn't report it.
  7333. if (!this.featuresProgressEvents) {
  7334. this.manualProgressOn();
  7335. }
  7336. // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7337. if (!this.featuresTimeupdateEvents) {
  7338. this.manualTimeUpdatesOn();
  7339. }
  7340. ['Text', 'Audio', 'Video'].forEach(track => {
  7341. if (options[`native${track}Tracks`] === false) {
  7342. this[`featuresNative${track}Tracks`] = false;
  7343. }
  7344. });
  7345. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7346. this.featuresNativeTextTracks = false;
  7347. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7348. this.featuresNativeTextTracks = true;
  7349. }
  7350. if (!this.featuresNativeTextTracks) {
  7351. this.emulateTextTracks();
  7352. }
  7353. this.preloadTextTracks = options.preloadTextTracks !== false;
  7354. this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7355. this.initTrackListeners();
  7356. // Turn on component tap events only if not using native controls
  7357. if (!options.nativeControlsForTouch) {
  7358. this.emitTapEvents();
  7359. }
  7360. if (this.constructor) {
  7361. this.name_ = this.constructor.name || 'Unknown Tech';
  7362. }
  7363. }
  7364. /**
  7365. * A special function to trigger source set in a way that will allow player
  7366. * to re-trigger if the player or tech are not ready yet.
  7367. *
  7368. * @fires Tech#sourceset
  7369. * @param {string} src The source string at the time of the source changing.
  7370. */
  7371. triggerSourceset(src) {
  7372. if (!this.isReady_) {
  7373. // on initial ready we have to trigger source set
  7374. // 1ms after ready so that player can watch for it.
  7375. this.one('ready', () => this.setTimeout(() => this.triggerSourceset(src), 1));
  7376. }
  7377. /**
  7378. * Fired when the source is set on the tech causing the media element
  7379. * to reload.
  7380. *
  7381. * @see {@link Player#event:sourceset}
  7382. * @event Tech#sourceset
  7383. * @type {Event}
  7384. */
  7385. this.trigger({
  7386. src,
  7387. type: 'sourceset'
  7388. });
  7389. }
  7390. /* Fallbacks for unsupported event types
  7391. ================================================================================ */
  7392. /**
  7393. * Polyfill the `progress` event for browsers that don't support it natively.
  7394. *
  7395. * @see {@link Tech#trackProgress}
  7396. */
  7397. manualProgressOn() {
  7398. this.on('durationchange', this.onDurationChange_);
  7399. this.manualProgress = true;
  7400. // Trigger progress watching when a source begins loading
  7401. this.one('ready', this.trackProgress_);
  7402. }
  7403. /**
  7404. * Turn off the polyfill for `progress` events that was created in
  7405. * {@link Tech#manualProgressOn}
  7406. */
  7407. manualProgressOff() {
  7408. this.manualProgress = false;
  7409. this.stopTrackingProgress();
  7410. this.off('durationchange', this.onDurationChange_);
  7411. }
  7412. /**
  7413. * This is used to trigger a `progress` event when the buffered percent changes. It
  7414. * sets an interval function that will be called every 500 milliseconds to check if the
  7415. * buffer end percent has changed.
  7416. *
  7417. * > This function is called by {@link Tech#manualProgressOn}
  7418. *
  7419. * @param {Event} event
  7420. * The `ready` event that caused this to run.
  7421. *
  7422. * @listens Tech#ready
  7423. * @fires Tech#progress
  7424. */
  7425. trackProgress(event) {
  7426. this.stopTrackingProgress();
  7427. this.progressInterval = this.setInterval(bind_(this, function () {
  7428. // Don't trigger unless buffered amount is greater than last time
  7429. const numBufferedPercent = this.bufferedPercent();
  7430. if (this.bufferedPercent_ !== numBufferedPercent) {
  7431. /**
  7432. * See {@link Player#progress}
  7433. *
  7434. * @event Tech#progress
  7435. * @type {Event}
  7436. */
  7437. this.trigger('progress');
  7438. }
  7439. this.bufferedPercent_ = numBufferedPercent;
  7440. if (numBufferedPercent === 1) {
  7441. this.stopTrackingProgress();
  7442. }
  7443. }), 500);
  7444. }
  7445. /**
  7446. * Update our internal duration on a `durationchange` event by calling
  7447. * {@link Tech#duration}.
  7448. *
  7449. * @param {Event} event
  7450. * The `durationchange` event that caused this to run.
  7451. *
  7452. * @listens Tech#durationchange
  7453. */
  7454. onDurationChange(event) {
  7455. this.duration_ = this.duration();
  7456. }
  7457. /**
  7458. * Get and create a `TimeRange` object for buffering.
  7459. *
  7460. * @return { import('../utils/time').TimeRange }
  7461. * The time range object that was created.
  7462. */
  7463. buffered() {
  7464. return createTimeRanges$1(0, 0);
  7465. }
  7466. /**
  7467. * Get the percentage of the current video that is currently buffered.
  7468. *
  7469. * @return {number}
  7470. * A number from 0 to 1 that represents the decimal percentage of the
  7471. * video that is buffered.
  7472. *
  7473. */
  7474. bufferedPercent() {
  7475. return bufferedPercent(this.buffered(), this.duration_);
  7476. }
  7477. /**
  7478. * Turn off the polyfill for `progress` events that was created in
  7479. * {@link Tech#manualProgressOn}
  7480. * Stop manually tracking progress events by clearing the interval that was set in
  7481. * {@link Tech#trackProgress}.
  7482. */
  7483. stopTrackingProgress() {
  7484. this.clearInterval(this.progressInterval);
  7485. }
  7486. /**
  7487. * Polyfill the `timeupdate` event for browsers that don't support it.
  7488. *
  7489. * @see {@link Tech#trackCurrentTime}
  7490. */
  7491. manualTimeUpdatesOn() {
  7492. this.manualTimeUpdates = true;
  7493. this.on('play', this.trackCurrentTime_);
  7494. this.on('pause', this.stopTrackingCurrentTime_);
  7495. }
  7496. /**
  7497. * Turn off the polyfill for `timeupdate` events that was created in
  7498. * {@link Tech#manualTimeUpdatesOn}
  7499. */
  7500. manualTimeUpdatesOff() {
  7501. this.manualTimeUpdates = false;
  7502. this.stopTrackingCurrentTime();
  7503. this.off('play', this.trackCurrentTime_);
  7504. this.off('pause', this.stopTrackingCurrentTime_);
  7505. }
  7506. /**
  7507. * Sets up an interval function to track current time and trigger `timeupdate` every
  7508. * 250 milliseconds.
  7509. *
  7510. * @listens Tech#play
  7511. * @triggers Tech#timeupdate
  7512. */
  7513. trackCurrentTime() {
  7514. if (this.currentTimeInterval) {
  7515. this.stopTrackingCurrentTime();
  7516. }
  7517. this.currentTimeInterval = this.setInterval(function () {
  7518. /**
  7519. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  7520. *
  7521. * @event Tech#timeupdate
  7522. * @type {Event}
  7523. */
  7524. this.trigger({
  7525. type: 'timeupdate',
  7526. target: this,
  7527. manuallyTriggered: true
  7528. });
  7529. // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  7530. }, 250);
  7531. }
  7532. /**
  7533. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  7534. * `timeupdate` event is no longer triggered.
  7535. *
  7536. * @listens {Tech#pause}
  7537. */
  7538. stopTrackingCurrentTime() {
  7539. this.clearInterval(this.currentTimeInterval);
  7540. // #1002 - if the video ends right before the next timeupdate would happen,
  7541. // the progress bar won't make it all the way to the end
  7542. this.trigger({
  7543. type: 'timeupdate',
  7544. target: this,
  7545. manuallyTriggered: true
  7546. });
  7547. }
  7548. /**
  7549. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  7550. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  7551. *
  7552. * @fires Component#dispose
  7553. */
  7554. dispose() {
  7555. // clear out all tracks because we can't reuse them between techs
  7556. this.clearTracks(NORMAL.names);
  7557. // Turn off any manual progress or timeupdate tracking
  7558. if (this.manualProgress) {
  7559. this.manualProgressOff();
  7560. }
  7561. if (this.manualTimeUpdates) {
  7562. this.manualTimeUpdatesOff();
  7563. }
  7564. super.dispose();
  7565. }
  7566. /**
  7567. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  7568. *
  7569. * > Note: Techs without source handlers should call this between sources for `video`
  7570. * & `audio` tracks. You don't want to use them between tracks!
  7571. *
  7572. * @param {string[]|string} types
  7573. * TrackList names to clear, valid names are `video`, `audio`, and
  7574. * `text`.
  7575. */
  7576. clearTracks(types) {
  7577. types = [].concat(types);
  7578. // clear out all tracks because we can't reuse them between techs
  7579. types.forEach(type => {
  7580. const list = this[`${type}Tracks`]() || [];
  7581. let i = list.length;
  7582. while (i--) {
  7583. const track = list[i];
  7584. if (type === 'text') {
  7585. this.removeRemoteTextTrack(track);
  7586. }
  7587. list.removeTrack(track);
  7588. }
  7589. });
  7590. }
  7591. /**
  7592. * Remove any TextTracks added via addRemoteTextTrack that are
  7593. * flagged for automatic garbage collection
  7594. */
  7595. cleanupAutoTextTracks() {
  7596. const list = this.autoRemoteTextTracks_ || [];
  7597. let i = list.length;
  7598. while (i--) {
  7599. const track = list[i];
  7600. this.removeRemoteTextTrack(track);
  7601. }
  7602. }
  7603. /**
  7604. * Reset the tech, which will removes all sources and reset the internal readyState.
  7605. *
  7606. * @abstract
  7607. */
  7608. reset() {}
  7609. /**
  7610. * Get the value of `crossOrigin` from the tech.
  7611. *
  7612. * @abstract
  7613. *
  7614. * @see {Html5#crossOrigin}
  7615. */
  7616. crossOrigin() {}
  7617. /**
  7618. * Set the value of `crossOrigin` on the tech.
  7619. *
  7620. * @abstract
  7621. *
  7622. * @param {string} crossOrigin the crossOrigin value
  7623. * @see {Html5#setCrossOrigin}
  7624. */
  7625. setCrossOrigin() {}
  7626. /**
  7627. * Get or set an error on the Tech.
  7628. *
  7629. * @param {MediaError} [err]
  7630. * Error to set on the Tech
  7631. *
  7632. * @return {MediaError|null}
  7633. * The current error object on the tech, or null if there isn't one.
  7634. */
  7635. error(err) {
  7636. if (err !== undefined) {
  7637. this.error_ = new MediaError(err);
  7638. this.trigger('error');
  7639. }
  7640. return this.error_;
  7641. }
  7642. /**
  7643. * Returns the `TimeRange`s that have been played through for the current source.
  7644. *
  7645. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  7646. * It only checks whether the source has played at all or not.
  7647. *
  7648. * @return {TimeRange}
  7649. * - A single time range if this video has played
  7650. * - An empty set of ranges if not.
  7651. */
  7652. played() {
  7653. if (this.hasStarted_) {
  7654. return createTimeRanges$1(0, 0);
  7655. }
  7656. return createTimeRanges$1();
  7657. }
  7658. /**
  7659. * Start playback
  7660. *
  7661. * @abstract
  7662. *
  7663. * @see {Html5#play}
  7664. */
  7665. play() {}
  7666. /**
  7667. * Set whether we are scrubbing or not
  7668. *
  7669. * @abstract
  7670. * @param {boolean} _isScrubbing
  7671. * - true for we are currently scrubbing
  7672. * - false for we are no longer scrubbing
  7673. *
  7674. * @see {Html5#setScrubbing}
  7675. */
  7676. setScrubbing(_isScrubbing) {}
  7677. /**
  7678. * Get whether we are scrubbing or not
  7679. *
  7680. * @abstract
  7681. *
  7682. * @see {Html5#scrubbing}
  7683. */
  7684. scrubbing() {}
  7685. /**
  7686. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  7687. * previously called.
  7688. *
  7689. * @param {number} _seconds
  7690. * Set the current time of the media to this.
  7691. * @fires Tech#timeupdate
  7692. */
  7693. setCurrentTime(_seconds) {
  7694. // improve the accuracy of manual timeupdates
  7695. if (this.manualTimeUpdates) {
  7696. /**
  7697. * A manual `timeupdate` event.
  7698. *
  7699. * @event Tech#timeupdate
  7700. * @type {Event}
  7701. */
  7702. this.trigger({
  7703. type: 'timeupdate',
  7704. target: this,
  7705. manuallyTriggered: true
  7706. });
  7707. }
  7708. }
  7709. /**
  7710. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  7711. * {@link TextTrackList} events.
  7712. *
  7713. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  7714. *
  7715. * @fires Tech#audiotrackchange
  7716. * @fires Tech#videotrackchange
  7717. * @fires Tech#texttrackchange
  7718. */
  7719. initTrackListeners() {
  7720. /**
  7721. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  7722. *
  7723. * @event Tech#audiotrackchange
  7724. * @type {Event}
  7725. */
  7726. /**
  7727. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  7728. *
  7729. * @event Tech#videotrackchange
  7730. * @type {Event}
  7731. */
  7732. /**
  7733. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  7734. *
  7735. * @event Tech#texttrackchange
  7736. * @type {Event}
  7737. */
  7738. NORMAL.names.forEach(name => {
  7739. const props = NORMAL[name];
  7740. const trackListChanges = () => {
  7741. this.trigger(`${name}trackchange`);
  7742. };
  7743. const tracks = this[props.getterName]();
  7744. tracks.addEventListener('removetrack', trackListChanges);
  7745. tracks.addEventListener('addtrack', trackListChanges);
  7746. this.on('dispose', () => {
  7747. tracks.removeEventListener('removetrack', trackListChanges);
  7748. tracks.removeEventListener('addtrack', trackListChanges);
  7749. });
  7750. });
  7751. }
  7752. /**
  7753. * Emulate TextTracks using vtt.js if necessary
  7754. *
  7755. * @fires Tech#vttjsloaded
  7756. * @fires Tech#vttjserror
  7757. */
  7758. addWebVttScript_() {
  7759. if (window__default["default"].WebVTT) {
  7760. return;
  7761. }
  7762. // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  7763. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  7764. // before inserting the WebVTT script
  7765. if (document__default["default"].body.contains(this.el())) {
  7766. // load via require if available and vtt.js script location was not passed in
  7767. // as an option. novtt builds will turn the above require call into an empty object
  7768. // which will cause this if check to always fail.
  7769. if (!this.options_['vtt.js'] && isPlain(vtt__default["default"]) && Object.keys(vtt__default["default"]).length > 0) {
  7770. this.trigger('vttjsloaded');
  7771. return;
  7772. }
  7773. // load vtt.js via the script location option or the cdn of no location was
  7774. // passed in
  7775. const script = document__default["default"].createElement('script');
  7776. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  7777. script.onload = () => {
  7778. /**
  7779. * Fired when vtt.js is loaded.
  7780. *
  7781. * @event Tech#vttjsloaded
  7782. * @type {Event}
  7783. */
  7784. this.trigger('vttjsloaded');
  7785. };
  7786. script.onerror = () => {
  7787. /**
  7788. * Fired when vtt.js was not loaded due to an error
  7789. *
  7790. * @event Tech#vttjsloaded
  7791. * @type {Event}
  7792. */
  7793. this.trigger('vttjserror');
  7794. };
  7795. this.on('dispose', () => {
  7796. script.onload = null;
  7797. script.onerror = null;
  7798. });
  7799. // but have not loaded yet and we set it to true before the inject so that
  7800. // we don't overwrite the injected window.WebVTT if it loads right away
  7801. window__default["default"].WebVTT = true;
  7802. this.el().parentNode.appendChild(script);
  7803. } else {
  7804. this.ready(this.addWebVttScript_);
  7805. }
  7806. }
  7807. /**
  7808. * Emulate texttracks
  7809. *
  7810. */
  7811. emulateTextTracks() {
  7812. const tracks = this.textTracks();
  7813. const remoteTracks = this.remoteTextTracks();
  7814. const handleAddTrack = e => tracks.addTrack(e.track);
  7815. const handleRemoveTrack = e => tracks.removeTrack(e.track);
  7816. remoteTracks.on('addtrack', handleAddTrack);
  7817. remoteTracks.on('removetrack', handleRemoveTrack);
  7818. this.addWebVttScript_();
  7819. const updateDisplay = () => this.trigger('texttrackchange');
  7820. const textTracksChanges = () => {
  7821. updateDisplay();
  7822. for (let i = 0; i < tracks.length; i++) {
  7823. const track = tracks[i];
  7824. track.removeEventListener('cuechange', updateDisplay);
  7825. if (track.mode === 'showing') {
  7826. track.addEventListener('cuechange', updateDisplay);
  7827. }
  7828. }
  7829. };
  7830. textTracksChanges();
  7831. tracks.addEventListener('change', textTracksChanges);
  7832. tracks.addEventListener('addtrack', textTracksChanges);
  7833. tracks.addEventListener('removetrack', textTracksChanges);
  7834. this.on('dispose', function () {
  7835. remoteTracks.off('addtrack', handleAddTrack);
  7836. remoteTracks.off('removetrack', handleRemoveTrack);
  7837. tracks.removeEventListener('change', textTracksChanges);
  7838. tracks.removeEventListener('addtrack', textTracksChanges);
  7839. tracks.removeEventListener('removetrack', textTracksChanges);
  7840. for (let i = 0; i < tracks.length; i++) {
  7841. const track = tracks[i];
  7842. track.removeEventListener('cuechange', updateDisplay);
  7843. }
  7844. });
  7845. }
  7846. /**
  7847. * Create and returns a remote {@link TextTrack} object.
  7848. *
  7849. * @param {string} kind
  7850. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7851. *
  7852. * @param {string} [label]
  7853. * Label to identify the text track
  7854. *
  7855. * @param {string} [language]
  7856. * Two letter language abbreviation
  7857. *
  7858. * @return {TextTrack}
  7859. * The TextTrack that gets created.
  7860. */
  7861. addTextTrack(kind, label, language) {
  7862. if (!kind) {
  7863. throw new Error('TextTrack kind is required but was not provided');
  7864. }
  7865. return createTrackHelper(this, kind, label, language);
  7866. }
  7867. /**
  7868. * Create an emulated TextTrack for use by addRemoteTextTrack
  7869. *
  7870. * This is intended to be overridden by classes that inherit from
  7871. * Tech in order to create native or custom TextTracks.
  7872. *
  7873. * @param {Object} options
  7874. * The object should contain the options to initialize the TextTrack with.
  7875. *
  7876. * @param {string} [options.kind]
  7877. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  7878. *
  7879. * @param {string} [options.label].
  7880. * Label to identify the text track
  7881. *
  7882. * @param {string} [options.language]
  7883. * Two letter language abbreviation.
  7884. *
  7885. * @return {HTMLTrackElement}
  7886. * The track element that gets created.
  7887. */
  7888. createRemoteTextTrack(options) {
  7889. const track = merge$1(options, {
  7890. tech: this
  7891. });
  7892. return new REMOTE.remoteTextEl.TrackClass(track);
  7893. }
  7894. /**
  7895. * Creates a remote text track object and returns an html track element.
  7896. *
  7897. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  7898. *
  7899. * @param {Object} options
  7900. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  7901. *
  7902. * @param {boolean} [manualCleanup=false]
  7903. * - When false: the TextTrack will be automatically removed from the video
  7904. * element whenever the source changes
  7905. * - When True: The TextTrack will have to be cleaned up manually
  7906. *
  7907. * @return {HTMLTrackElement}
  7908. * An Html Track Element.
  7909. *
  7910. */
  7911. addRemoteTextTrack(options = {}, manualCleanup) {
  7912. const htmlTrackElement = this.createRemoteTextTrack(options);
  7913. if (typeof manualCleanup !== 'boolean') {
  7914. manualCleanup = false;
  7915. }
  7916. // store HTMLTrackElement and TextTrack to remote list
  7917. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  7918. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  7919. if (manualCleanup === false) {
  7920. // create the TextTrackList if it doesn't exist
  7921. this.ready(() => this.autoRemoteTextTracks_.addTrack(htmlTrackElement.track));
  7922. }
  7923. return htmlTrackElement;
  7924. }
  7925. /**
  7926. * Remove a remote text track from the remote `TextTrackList`.
  7927. *
  7928. * @param {TextTrack} track
  7929. * `TextTrack` to remove from the `TextTrackList`
  7930. */
  7931. removeRemoteTextTrack(track) {
  7932. const trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track);
  7933. // remove HTMLTrackElement and TextTrack from remote list
  7934. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  7935. this.remoteTextTracks().removeTrack(track);
  7936. this.autoRemoteTextTracks_.removeTrack(track);
  7937. }
  7938. /**
  7939. * Gets available media playback quality metrics as specified by the W3C's Media
  7940. * Playback Quality API.
  7941. *
  7942. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  7943. *
  7944. * @return {Object}
  7945. * An object with supported media playback quality metrics
  7946. *
  7947. * @abstract
  7948. */
  7949. getVideoPlaybackQuality() {
  7950. return {};
  7951. }
  7952. /**
  7953. * Attempt to create a floating video window always on top of other windows
  7954. * so that users may continue consuming media while they interact with other
  7955. * content sites, or applications on their device.
  7956. *
  7957. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  7958. *
  7959. * @return {Promise|undefined}
  7960. * A promise with a Picture-in-Picture window if the browser supports
  7961. * Promises (or one was passed in as an option). It returns undefined
  7962. * otherwise.
  7963. *
  7964. * @abstract
  7965. */
  7966. requestPictureInPicture() {
  7967. return Promise.reject();
  7968. }
  7969. /**
  7970. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  7971. * Defaults to true, as it should be considered disabled if the tech does not support pip
  7972. *
  7973. * @abstract
  7974. */
  7975. disablePictureInPicture() {
  7976. return true;
  7977. }
  7978. /**
  7979. * A method to set or unset the 'disablePictureInPicture' <video> property.
  7980. *
  7981. * @abstract
  7982. */
  7983. setDisablePictureInPicture() {}
  7984. /**
  7985. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  7986. *
  7987. * @param {function} cb
  7988. * @return {number} request id
  7989. */
  7990. requestVideoFrameCallback(cb) {
  7991. const id = newGUID();
  7992. if (!this.isReady_ || this.paused()) {
  7993. this.queuedHanders_.add(id);
  7994. this.one('playing', () => {
  7995. if (this.queuedHanders_.has(id)) {
  7996. this.queuedHanders_.delete(id);
  7997. cb();
  7998. }
  7999. });
  8000. } else {
  8001. this.requestNamedAnimationFrame(id, cb);
  8002. }
  8003. return id;
  8004. }
  8005. /**
  8006. * A fallback implementation of cancelVideoFrameCallback
  8007. *
  8008. * @param {number} id id of callback to be cancelled
  8009. */
  8010. cancelVideoFrameCallback(id) {
  8011. if (this.queuedHanders_.has(id)) {
  8012. this.queuedHanders_.delete(id);
  8013. } else {
  8014. this.cancelNamedAnimationFrame(id);
  8015. }
  8016. }
  8017. /**
  8018. * A method to set a poster from a `Tech`.
  8019. *
  8020. * @abstract
  8021. */
  8022. setPoster() {}
  8023. /**
  8024. * A method to check for the presence of the 'playsinline' <video> attribute.
  8025. *
  8026. * @abstract
  8027. */
  8028. playsinline() {}
  8029. /**
  8030. * A method to set or unset the 'playsinline' <video> attribute.
  8031. *
  8032. * @abstract
  8033. */
  8034. setPlaysinline() {}
  8035. /**
  8036. * Attempt to force override of native audio tracks.
  8037. *
  8038. * @param {boolean} override - If set to true native audio will be overridden,
  8039. * otherwise native audio will potentially be used.
  8040. *
  8041. * @abstract
  8042. */
  8043. overrideNativeAudioTracks(override) {}
  8044. /**
  8045. * Attempt to force override of native video tracks.
  8046. *
  8047. * @param {boolean} override - If set to true native video will be overridden,
  8048. * otherwise native video will potentially be used.
  8049. *
  8050. * @abstract
  8051. */
  8052. overrideNativeVideoTracks(override) {}
  8053. /**
  8054. * Check if the tech can support the given mime-type.
  8055. *
  8056. * The base tech does not support any type, but source handlers might
  8057. * overwrite this.
  8058. *
  8059. * @param {string} _type
  8060. * The mimetype to check for support
  8061. *
  8062. * @return {string}
  8063. * 'probably', 'maybe', or empty string
  8064. *
  8065. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8066. *
  8067. * @abstract
  8068. */
  8069. canPlayType(_type) {
  8070. return '';
  8071. }
  8072. /**
  8073. * Check if the type is supported by this tech.
  8074. *
  8075. * The base tech does not support any type, but source handlers might
  8076. * overwrite this.
  8077. *
  8078. * @param {string} _type
  8079. * The media type to check
  8080. * @return {string} Returns the native video element's response
  8081. */
  8082. static canPlayType(_type) {
  8083. return '';
  8084. }
  8085. /**
  8086. * Check if the tech can support the given source
  8087. *
  8088. * @param {Object} srcObj
  8089. * The source object
  8090. * @param {Object} options
  8091. * The options passed to the tech
  8092. * @return {string} 'probably', 'maybe', or '' (empty string)
  8093. */
  8094. static canPlaySource(srcObj, options) {
  8095. return Tech.canPlayType(srcObj.type);
  8096. }
  8097. /*
  8098. * Return whether the argument is a Tech or not.
  8099. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8100. *
  8101. * @param {Object} component
  8102. * The item to check
  8103. *
  8104. * @return {boolean}
  8105. * Whether it is a tech or not
  8106. * - True if it is a tech
  8107. * - False if it is not
  8108. */
  8109. static isTech(component) {
  8110. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8111. }
  8112. /**
  8113. * Registers a `Tech` into a shared list for videojs.
  8114. *
  8115. * @param {string} name
  8116. * Name of the `Tech` to register.
  8117. *
  8118. * @param {Object} tech
  8119. * The `Tech` class to register.
  8120. */
  8121. static registerTech(name, tech) {
  8122. if (!Tech.techs_) {
  8123. Tech.techs_ = {};
  8124. }
  8125. if (!Tech.isTech(tech)) {
  8126. throw new Error(`Tech ${name} must be a Tech`);
  8127. }
  8128. if (!Tech.canPlayType) {
  8129. throw new Error('Techs must have a static canPlayType method on them');
  8130. }
  8131. if (!Tech.canPlaySource) {
  8132. throw new Error('Techs must have a static canPlaySource method on them');
  8133. }
  8134. name = toTitleCase$1(name);
  8135. Tech.techs_[name] = tech;
  8136. Tech.techs_[toLowerCase(name)] = tech;
  8137. if (name !== 'Tech') {
  8138. // camel case the techName for use in techOrder
  8139. Tech.defaultTechOrder_.push(name);
  8140. }
  8141. return tech;
  8142. }
  8143. /**
  8144. * Get a `Tech` from the shared list by name.
  8145. *
  8146. * @param {string} name
  8147. * `camelCase` or `TitleCase` name of the Tech to get
  8148. *
  8149. * @return {Tech|undefined}
  8150. * The `Tech` or undefined if there was no tech with the name requested.
  8151. */
  8152. static getTech(name) {
  8153. if (!name) {
  8154. return;
  8155. }
  8156. if (Tech.techs_ && Tech.techs_[name]) {
  8157. return Tech.techs_[name];
  8158. }
  8159. name = toTitleCase$1(name);
  8160. if (window__default["default"] && window__default["default"].videojs && window__default["default"].videojs[name]) {
  8161. log$1.warn(`The ${name} tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)`);
  8162. return window__default["default"].videojs[name];
  8163. }
  8164. }
  8165. }
  8166. /**
  8167. * Get the {@link VideoTrackList}
  8168. *
  8169. * @returns {VideoTrackList}
  8170. * @method Tech.prototype.videoTracks
  8171. */
  8172. /**
  8173. * Get the {@link AudioTrackList}
  8174. *
  8175. * @returns {AudioTrackList}
  8176. * @method Tech.prototype.audioTracks
  8177. */
  8178. /**
  8179. * Get the {@link TextTrackList}
  8180. *
  8181. * @returns {TextTrackList}
  8182. * @method Tech.prototype.textTracks
  8183. */
  8184. /**
  8185. * Get the remote element {@link TextTrackList}
  8186. *
  8187. * @returns {TextTrackList}
  8188. * @method Tech.prototype.remoteTextTracks
  8189. */
  8190. /**
  8191. * Get the remote element {@link HtmlTrackElementList}
  8192. *
  8193. * @returns {HtmlTrackElementList}
  8194. * @method Tech.prototype.remoteTextTrackEls
  8195. */
  8196. ALL.names.forEach(function (name) {
  8197. const props = ALL[name];
  8198. Tech.prototype[props.getterName] = function () {
  8199. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8200. return this[props.privateName];
  8201. };
  8202. });
  8203. /**
  8204. * List of associated text tracks
  8205. *
  8206. * @type {TextTrackList}
  8207. * @private
  8208. * @property Tech#textTracks_
  8209. */
  8210. /**
  8211. * List of associated audio tracks.
  8212. *
  8213. * @type {AudioTrackList}
  8214. * @private
  8215. * @property Tech#audioTracks_
  8216. */
  8217. /**
  8218. * List of associated video tracks.
  8219. *
  8220. * @type {VideoTrackList}
  8221. * @private
  8222. * @property Tech#videoTracks_
  8223. */
  8224. /**
  8225. * Boolean indicating whether the `Tech` supports volume control.
  8226. *
  8227. * @type {boolean}
  8228. * @default
  8229. */
  8230. Tech.prototype.featuresVolumeControl = true;
  8231. /**
  8232. * Boolean indicating whether the `Tech` supports muting volume.
  8233. *
  8234. * @type {boolean}
  8235. * @default
  8236. */
  8237. Tech.prototype.featuresMuteControl = true;
  8238. /**
  8239. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8240. * Resizing plugins using request fullscreen reloads the plugin
  8241. *
  8242. * @type {boolean}
  8243. * @default
  8244. */
  8245. Tech.prototype.featuresFullscreenResize = false;
  8246. /**
  8247. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8248. * plays. Examples:
  8249. * - Set player to play 2x (twice) as fast
  8250. * - Set player to play 0.5x (half) as fast
  8251. *
  8252. * @type {boolean}
  8253. * @default
  8254. */
  8255. Tech.prototype.featuresPlaybackRate = false;
  8256. /**
  8257. * Boolean indicating whether the `Tech` supports the `progress` event.
  8258. * This will be used to determine if {@link Tech#manualProgressOn} should be called.
  8259. *
  8260. * @type {boolean}
  8261. * @default
  8262. */
  8263. Tech.prototype.featuresProgressEvents = false;
  8264. /**
  8265. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8266. *
  8267. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8268. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8269. * a new source.
  8270. *
  8271. * @type {boolean}
  8272. * @default
  8273. */
  8274. Tech.prototype.featuresSourceset = false;
  8275. /**
  8276. * Boolean indicating whether the `Tech` supports the `timeupdate` event.
  8277. * This will be used to determine if {@link Tech#manualTimeUpdates} should be called.
  8278. *
  8279. * @type {boolean}
  8280. * @default
  8281. */
  8282. Tech.prototype.featuresTimeupdateEvents = false;
  8283. /**
  8284. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8285. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8286. *
  8287. * @type {boolean}
  8288. * @default
  8289. */
  8290. Tech.prototype.featuresNativeTextTracks = false;
  8291. /**
  8292. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8293. *
  8294. * @type {boolean}
  8295. * @default
  8296. */
  8297. Tech.prototype.featuresVideoFrameCallback = false;
  8298. /**
  8299. * A functional mixin for techs that want to use the Source Handler pattern.
  8300. * Source handlers are scripts for handling specific formats.
  8301. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8302. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8303. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8304. *
  8305. * @param {Tech} _Tech
  8306. * The tech to add source handler functions to.
  8307. *
  8308. * @mixes Tech~SourceHandlerAdditions
  8309. */
  8310. Tech.withSourceHandlers = function (_Tech) {
  8311. /**
  8312. * Register a source handler
  8313. *
  8314. * @param {Function} handler
  8315. * The source handler class
  8316. *
  8317. * @param {number} [index]
  8318. * Register it at the following index
  8319. */
  8320. _Tech.registerSourceHandler = function (handler, index) {
  8321. let handlers = _Tech.sourceHandlers;
  8322. if (!handlers) {
  8323. handlers = _Tech.sourceHandlers = [];
  8324. }
  8325. if (index === undefined) {
  8326. // add to the end of the list
  8327. index = handlers.length;
  8328. }
  8329. handlers.splice(index, 0, handler);
  8330. };
  8331. /**
  8332. * Check if the tech can support the given type. Also checks the
  8333. * Techs sourceHandlers.
  8334. *
  8335. * @param {string} type
  8336. * The mimetype to check.
  8337. *
  8338. * @return {string}
  8339. * 'probably', 'maybe', or '' (empty string)
  8340. */
  8341. _Tech.canPlayType = function (type) {
  8342. const handlers = _Tech.sourceHandlers || [];
  8343. let can;
  8344. for (let i = 0; i < handlers.length; i++) {
  8345. can = handlers[i].canPlayType(type);
  8346. if (can) {
  8347. return can;
  8348. }
  8349. }
  8350. return '';
  8351. };
  8352. /**
  8353. * Returns the first source handler that supports the source.
  8354. *
  8355. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8356. *
  8357. * @param {Tech~SourceObject} source
  8358. * The source object
  8359. *
  8360. * @param {Object} options
  8361. * The options passed to the tech
  8362. *
  8363. * @return {SourceHandler|null}
  8364. * The first source handler that supports the source or null if
  8365. * no SourceHandler supports the source
  8366. */
  8367. _Tech.selectSourceHandler = function (source, options) {
  8368. const handlers = _Tech.sourceHandlers || [];
  8369. let can;
  8370. for (let i = 0; i < handlers.length; i++) {
  8371. can = handlers[i].canHandleSource(source, options);
  8372. if (can) {
  8373. return handlers[i];
  8374. }
  8375. }
  8376. return null;
  8377. };
  8378. /**
  8379. * Check if the tech can support the given source.
  8380. *
  8381. * @param {Tech~SourceObject} srcObj
  8382. * The source object
  8383. *
  8384. * @param {Object} options
  8385. * The options passed to the tech
  8386. *
  8387. * @return {string}
  8388. * 'probably', 'maybe', or '' (empty string)
  8389. */
  8390. _Tech.canPlaySource = function (srcObj, options) {
  8391. const sh = _Tech.selectSourceHandler(srcObj, options);
  8392. if (sh) {
  8393. return sh.canHandleSource(srcObj, options);
  8394. }
  8395. return '';
  8396. };
  8397. /**
  8398. * When using a source handler, prefer its implementation of
  8399. * any function normally provided by the tech.
  8400. */
  8401. const deferrable = ['seekable', 'seeking', 'duration'];
  8402. /**
  8403. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  8404. * function if it exists, with a fallback to the Techs seekable function.
  8405. *
  8406. * @method _Tech.seekable
  8407. */
  8408. /**
  8409. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  8410. * function if it exists, otherwise it will fallback to the techs duration function.
  8411. *
  8412. * @method _Tech.duration
  8413. */
  8414. deferrable.forEach(function (fnName) {
  8415. const originalFn = this[fnName];
  8416. if (typeof originalFn !== 'function') {
  8417. return;
  8418. }
  8419. this[fnName] = function () {
  8420. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  8421. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  8422. }
  8423. return originalFn.apply(this, arguments);
  8424. };
  8425. }, _Tech.prototype);
  8426. /**
  8427. * Create a function for setting the source using a source object
  8428. * and source handlers.
  8429. * Should never be called unless a source handler was found.
  8430. *
  8431. * @param {Tech~SourceObject} source
  8432. * A source object with src and type keys
  8433. */
  8434. _Tech.prototype.setSource = function (source) {
  8435. let sh = _Tech.selectSourceHandler(source, this.options_);
  8436. if (!sh) {
  8437. // Fall back to a native source handler when unsupported sources are
  8438. // deliberately set
  8439. if (_Tech.nativeSourceHandler) {
  8440. sh = _Tech.nativeSourceHandler;
  8441. } else {
  8442. log$1.error('No source handler found for the current source.');
  8443. }
  8444. }
  8445. // Dispose any existing source handler
  8446. this.disposeSourceHandler();
  8447. this.off('dispose', this.disposeSourceHandler_);
  8448. if (sh !== _Tech.nativeSourceHandler) {
  8449. this.currentSource_ = source;
  8450. }
  8451. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  8452. this.one('dispose', this.disposeSourceHandler_);
  8453. };
  8454. /**
  8455. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  8456. *
  8457. * @listens Tech#dispose
  8458. */
  8459. _Tech.prototype.disposeSourceHandler = function () {
  8460. // if we have a source and get another one
  8461. // then we are loading something new
  8462. // than clear all of our current tracks
  8463. if (this.currentSource_) {
  8464. this.clearTracks(['audio', 'video']);
  8465. this.currentSource_ = null;
  8466. }
  8467. // always clean up auto-text tracks
  8468. this.cleanupAutoTextTracks();
  8469. if (this.sourceHandler_) {
  8470. if (this.sourceHandler_.dispose) {
  8471. this.sourceHandler_.dispose();
  8472. }
  8473. this.sourceHandler_ = null;
  8474. }
  8475. };
  8476. };
  8477. // The base Tech class needs to be registered as a Component. It is the only
  8478. // Tech that can be registered as a Component.
  8479. Component$1.registerComponent('Tech', Tech);
  8480. Tech.registerTech('Tech', Tech);
  8481. /**
  8482. * A list of techs that should be added to techOrder on Players
  8483. *
  8484. * @private
  8485. */
  8486. Tech.defaultTechOrder_ = [];
  8487. /**
  8488. * @file middleware.js
  8489. * @module middleware
  8490. */
  8491. const middlewares = {};
  8492. const middlewareInstances = {};
  8493. const TERMINATOR = {};
  8494. /**
  8495. * A middleware object is a plain JavaScript object that has methods that
  8496. * match the {@link Tech} methods found in the lists of allowed
  8497. * {@link module:middleware.allowedGetters|getters},
  8498. * {@link module:middleware.allowedSetters|setters}, and
  8499. * {@link module:middleware.allowedMediators|mediators}.
  8500. *
  8501. * @typedef {Object} MiddlewareObject
  8502. */
  8503. /**
  8504. * A middleware factory function that should return a
  8505. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  8506. *
  8507. * This factory will be called for each player when needed, with the player
  8508. * passed in as an argument.
  8509. *
  8510. * @callback MiddlewareFactory
  8511. * @param { import('../player').default } player
  8512. * A Video.js player.
  8513. */
  8514. /**
  8515. * Define a middleware that the player should use by way of a factory function
  8516. * that returns a middleware object.
  8517. *
  8518. * @param {string} type
  8519. * The MIME type to match or `"*"` for all MIME types.
  8520. *
  8521. * @param {MiddlewareFactory} middleware
  8522. * A middleware factory function that will be executed for
  8523. * matching types.
  8524. */
  8525. function use(type, middleware) {
  8526. middlewares[type] = middlewares[type] || [];
  8527. middlewares[type].push(middleware);
  8528. }
  8529. /**
  8530. * Asynchronously sets a source using middleware by recursing through any
  8531. * matching middlewares and calling `setSource` on each, passing along the
  8532. * previous returned value each time.
  8533. *
  8534. * @param { import('../player').default } player
  8535. * A {@link Player} instance.
  8536. *
  8537. * @param {Tech~SourceObject} src
  8538. * A source object.
  8539. *
  8540. * @param {Function}
  8541. * The next middleware to run.
  8542. */
  8543. function setSource(player, src, next) {
  8544. player.setTimeout(() => setSourceHelper(src, middlewares[src.type], next, player), 1);
  8545. }
  8546. /**
  8547. * When the tech is set, passes the tech to each middleware's `setTech` method.
  8548. *
  8549. * @param {Object[]} middleware
  8550. * An array of middleware instances.
  8551. *
  8552. * @param { import('../tech/tech').default } tech
  8553. * A Video.js tech.
  8554. */
  8555. function setTech(middleware, tech) {
  8556. middleware.forEach(mw => mw.setTech && mw.setTech(tech));
  8557. }
  8558. /**
  8559. * Calls a getter on the tech first, through each middleware
  8560. * from right to left to the player.
  8561. *
  8562. * @param {Object[]} middleware
  8563. * An array of middleware instances.
  8564. *
  8565. * @param { import('../tech/tech').default } tech
  8566. * The current tech.
  8567. *
  8568. * @param {string} method
  8569. * A method name.
  8570. *
  8571. * @return {*}
  8572. * The final value from the tech after middleware has intercepted it.
  8573. */
  8574. function get(middleware, tech, method) {
  8575. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  8576. }
  8577. /**
  8578. * Takes the argument given to the player and calls the setter method on each
  8579. * middleware from left to right to the tech.
  8580. *
  8581. * @param {Object[]} middleware
  8582. * An array of middleware instances.
  8583. *
  8584. * @param { import('../tech/tech').default } tech
  8585. * The current tech.
  8586. *
  8587. * @param {string} method
  8588. * A method name.
  8589. *
  8590. * @param {*} arg
  8591. * The value to set on the tech.
  8592. *
  8593. * @return {*}
  8594. * The return value of the `method` of the `tech`.
  8595. */
  8596. function set(middleware, tech, method, arg) {
  8597. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  8598. }
  8599. /**
  8600. * Takes the argument given to the player and calls the `call` version of the
  8601. * method on each middleware from left to right.
  8602. *
  8603. * Then, call the passed in method on the tech and return the result unchanged
  8604. * back to the player, through middleware, this time from right to left.
  8605. *
  8606. * @param {Object[]} middleware
  8607. * An array of middleware instances.
  8608. *
  8609. * @param { import('../tech/tech').default } tech
  8610. * The current tech.
  8611. *
  8612. * @param {string} method
  8613. * A method name.
  8614. *
  8615. * @param {*} arg
  8616. * The value to set on the tech.
  8617. *
  8618. * @return {*}
  8619. * The return value of the `method` of the `tech`, regardless of the
  8620. * return values of middlewares.
  8621. */
  8622. function mediate(middleware, tech, method, arg = null) {
  8623. const callMethod = 'call' + toTitleCase$1(method);
  8624. const middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  8625. const terminated = middlewareValue === TERMINATOR;
  8626. // deprecated. The `null` return value should instead return TERMINATOR to
  8627. // prevent confusion if a techs method actually returns null.
  8628. const returnValue = terminated ? null : tech[method](middlewareValue);
  8629. executeRight(middleware, method, returnValue, terminated);
  8630. return returnValue;
  8631. }
  8632. /**
  8633. * Enumeration of allowed getters where the keys are method names.
  8634. *
  8635. * @type {Object}
  8636. */
  8637. const allowedGetters = {
  8638. buffered: 1,
  8639. currentTime: 1,
  8640. duration: 1,
  8641. muted: 1,
  8642. played: 1,
  8643. paused: 1,
  8644. seekable: 1,
  8645. volume: 1,
  8646. ended: 1
  8647. };
  8648. /**
  8649. * Enumeration of allowed setters where the keys are method names.
  8650. *
  8651. * @type {Object}
  8652. */
  8653. const allowedSetters = {
  8654. setCurrentTime: 1,
  8655. setMuted: 1,
  8656. setVolume: 1
  8657. };
  8658. /**
  8659. * Enumeration of allowed mediators where the keys are method names.
  8660. *
  8661. * @type {Object}
  8662. */
  8663. const allowedMediators = {
  8664. play: 1,
  8665. pause: 1
  8666. };
  8667. function middlewareIterator(method) {
  8668. return (value, mw) => {
  8669. // if the previous middleware terminated, pass along the termination
  8670. if (value === TERMINATOR) {
  8671. return TERMINATOR;
  8672. }
  8673. if (mw[method]) {
  8674. return mw[method](value);
  8675. }
  8676. return value;
  8677. };
  8678. }
  8679. function executeRight(mws, method, value, terminated) {
  8680. for (let i = mws.length - 1; i >= 0; i--) {
  8681. const mw = mws[i];
  8682. if (mw[method]) {
  8683. mw[method](terminated, value);
  8684. }
  8685. }
  8686. }
  8687. /**
  8688. * Clear the middleware cache for a player.
  8689. *
  8690. * @param { import('../player').default } player
  8691. * A {@link Player} instance.
  8692. */
  8693. function clearCacheForPlayer(player) {
  8694. middlewareInstances[player.id()] = null;
  8695. }
  8696. /**
  8697. * {
  8698. * [playerId]: [[mwFactory, mwInstance], ...]
  8699. * }
  8700. *
  8701. * @private
  8702. */
  8703. function getOrCreateFactory(player, mwFactory) {
  8704. const mws = middlewareInstances[player.id()];
  8705. let mw = null;
  8706. if (mws === undefined || mws === null) {
  8707. mw = mwFactory(player);
  8708. middlewareInstances[player.id()] = [[mwFactory, mw]];
  8709. return mw;
  8710. }
  8711. for (let i = 0; i < mws.length; i++) {
  8712. const [mwf, mwi] = mws[i];
  8713. if (mwf !== mwFactory) {
  8714. continue;
  8715. }
  8716. mw = mwi;
  8717. }
  8718. if (mw === null) {
  8719. mw = mwFactory(player);
  8720. mws.push([mwFactory, mw]);
  8721. }
  8722. return mw;
  8723. }
  8724. function setSourceHelper(src = {}, middleware = [], next, player, acc = [], lastRun = false) {
  8725. const [mwFactory, ...mwrest] = middleware;
  8726. // if mwFactory is a string, then we're at a fork in the road
  8727. if (typeof mwFactory === 'string') {
  8728. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun);
  8729. // if we have an mwFactory, call it with the player to get the mw,
  8730. // then call the mw's setSource method
  8731. } else if (mwFactory) {
  8732. const mw = getOrCreateFactory(player, mwFactory);
  8733. // if setSource isn't present, implicitly select this middleware
  8734. if (!mw.setSource) {
  8735. acc.push(mw);
  8736. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8737. }
  8738. mw.setSource(Object.assign({}, src), function (err, _src) {
  8739. // something happened, try the next middleware on the current level
  8740. // make sure to use the old src
  8741. if (err) {
  8742. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8743. }
  8744. // we've succeeded, now we need to go deeper
  8745. acc.push(mw);
  8746. // if it's the same type, continue down the current chain
  8747. // otherwise, we want to go down the new chain
  8748. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  8749. });
  8750. } else if (mwrest.length) {
  8751. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8752. } else if (lastRun) {
  8753. next(src, acc);
  8754. } else {
  8755. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  8756. }
  8757. }
  8758. /**
  8759. * Mimetypes
  8760. *
  8761. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  8762. * @typedef Mimetypes~Kind
  8763. * @enum
  8764. */
  8765. const MimetypesKind = {
  8766. opus: 'video/ogg',
  8767. ogv: 'video/ogg',
  8768. mp4: 'video/mp4',
  8769. mov: 'video/mp4',
  8770. m4v: 'video/mp4',
  8771. mkv: 'video/x-matroska',
  8772. m4a: 'audio/mp4',
  8773. mp3: 'audio/mpeg',
  8774. aac: 'audio/aac',
  8775. caf: 'audio/x-caf',
  8776. flac: 'audio/flac',
  8777. oga: 'audio/ogg',
  8778. wav: 'audio/wav',
  8779. m3u8: 'application/x-mpegURL',
  8780. mpd: 'application/dash+xml',
  8781. jpg: 'image/jpeg',
  8782. jpeg: 'image/jpeg',
  8783. gif: 'image/gif',
  8784. png: 'image/png',
  8785. svg: 'image/svg+xml',
  8786. webp: 'image/webp'
  8787. };
  8788. /**
  8789. * Get the mimetype of a given src url if possible
  8790. *
  8791. * @param {string} src
  8792. * The url to the src
  8793. *
  8794. * @return {string}
  8795. * return the mimetype if it was known or empty string otherwise
  8796. */
  8797. const getMimetype = function (src = '') {
  8798. const ext = getFileExtension(src);
  8799. const mimetype = MimetypesKind[ext.toLowerCase()];
  8800. return mimetype || '';
  8801. };
  8802. /**
  8803. * Find the mime type of a given source string if possible. Uses the player
  8804. * source cache.
  8805. *
  8806. * @param { import('../player').default } player
  8807. * The player object
  8808. *
  8809. * @param {string} src
  8810. * The source string
  8811. *
  8812. * @return {string}
  8813. * The type that was found
  8814. */
  8815. const findMimetype = (player, src) => {
  8816. if (!src) {
  8817. return '';
  8818. }
  8819. // 1. check for the type in the `source` cache
  8820. if (player.cache_.source.src === src && player.cache_.source.type) {
  8821. return player.cache_.source.type;
  8822. }
  8823. // 2. see if we have this source in our `currentSources` cache
  8824. const matchingSources = player.cache_.sources.filter(s => s.src === src);
  8825. if (matchingSources.length) {
  8826. return matchingSources[0].type;
  8827. }
  8828. // 3. look for the src url in source elements and use the type there
  8829. const sources = player.$$('source');
  8830. for (let i = 0; i < sources.length; i++) {
  8831. const s = sources[i];
  8832. if (s.type && s.src && s.src === src) {
  8833. return s.type;
  8834. }
  8835. }
  8836. // 4. finally fallback to our list of mime types based on src url extension
  8837. return getMimetype(src);
  8838. };
  8839. /**
  8840. * @module filter-source
  8841. */
  8842. /**
  8843. * Filter out single bad source objects or multiple source objects in an
  8844. * array. Also flattens nested source object arrays into a 1 dimensional
  8845. * array of source objects.
  8846. *
  8847. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  8848. * The src object to filter
  8849. *
  8850. * @return {Tech~SourceObject[]}
  8851. * An array of sourceobjects containing only valid sources
  8852. *
  8853. * @private
  8854. */
  8855. const filterSource = function (src) {
  8856. // traverse array
  8857. if (Array.isArray(src)) {
  8858. let newsrc = [];
  8859. src.forEach(function (srcobj) {
  8860. srcobj = filterSource(srcobj);
  8861. if (Array.isArray(srcobj)) {
  8862. newsrc = newsrc.concat(srcobj);
  8863. } else if (isObject(srcobj)) {
  8864. newsrc.push(srcobj);
  8865. }
  8866. });
  8867. src = newsrc;
  8868. } else if (typeof src === 'string' && src.trim()) {
  8869. // convert string into object
  8870. src = [fixSource({
  8871. src
  8872. })];
  8873. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  8874. // src is already valid
  8875. src = [fixSource(src)];
  8876. } else {
  8877. // invalid source, turn it into an empty array
  8878. src = [];
  8879. }
  8880. return src;
  8881. };
  8882. /**
  8883. * Checks src mimetype, adding it when possible
  8884. *
  8885. * @param {Tech~SourceObject} src
  8886. * The src object to check
  8887. * @return {Tech~SourceObject}
  8888. * src Object with known type
  8889. */
  8890. function fixSource(src) {
  8891. if (!src.type) {
  8892. const mimetype = getMimetype(src.src);
  8893. if (mimetype) {
  8894. src.type = mimetype;
  8895. }
  8896. }
  8897. return src;
  8898. }
  8899. /**
  8900. * @file loader.js
  8901. */
  8902. /**
  8903. * The `MediaLoader` is the `Component` that decides which playback technology to load
  8904. * when a player is initialized.
  8905. *
  8906. * @extends Component
  8907. */
  8908. class MediaLoader extends Component$1 {
  8909. /**
  8910. * Create an instance of this class.
  8911. *
  8912. * @param { import('../player').default } player
  8913. * The `Player` that this class should attach to.
  8914. *
  8915. * @param {Object} [options]
  8916. * The key/value store of player options.
  8917. *
  8918. * @param {Function} [ready]
  8919. * The function that is run when this component is ready.
  8920. */
  8921. constructor(player, options, ready) {
  8922. // MediaLoader has no element
  8923. const options_ = merge$1({
  8924. createEl: false
  8925. }, options);
  8926. super(player, options_, ready);
  8927. // If there are no sources when the player is initialized,
  8928. // load the first supported playback technology.
  8929. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  8930. for (let i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  8931. const techName = toTitleCase$1(j[i]);
  8932. let tech = Tech.getTech(techName);
  8933. // Support old behavior of techs being registered as components.
  8934. // Remove once that deprecated behavior is removed.
  8935. if (!techName) {
  8936. tech = Component$1.getComponent(techName);
  8937. }
  8938. // Check if the browser supports this technology
  8939. if (tech && tech.isSupported()) {
  8940. player.loadTech_(techName);
  8941. break;
  8942. }
  8943. }
  8944. } else {
  8945. // Loop through playback technologies (e.g. HTML5) and check for support.
  8946. // Then load the best source.
  8947. // A few assumptions here:
  8948. // All playback technologies respect preload false.
  8949. player.src(options.playerOptions.sources);
  8950. }
  8951. }
  8952. }
  8953. Component$1.registerComponent('MediaLoader', MediaLoader);
  8954. /**
  8955. * @file clickable-component.js
  8956. */
  8957. /**
  8958. * Component which is clickable or keyboard actionable, but is not a
  8959. * native HTML button.
  8960. *
  8961. * @extends Component
  8962. */
  8963. class ClickableComponent extends Component$1 {
  8964. /**
  8965. * Creates an instance of this class.
  8966. *
  8967. * @param { import('./player').default } player
  8968. * The `Player` that this class should be attached to.
  8969. *
  8970. * @param {Object} [options]
  8971. * The key/value store of component options.
  8972. *
  8973. * @param {function} [options.clickHandler]
  8974. * The function to call when the button is clicked / activated
  8975. *
  8976. * @param {string} [options.controlText]
  8977. * The text to set on the button
  8978. *
  8979. * @param {string} [options.className]
  8980. * A class or space separated list of classes to add the component
  8981. *
  8982. */
  8983. constructor(player, options) {
  8984. super(player, options);
  8985. if (this.options_.controlText) {
  8986. this.controlText(this.options_.controlText);
  8987. }
  8988. this.handleMouseOver_ = e => this.handleMouseOver(e);
  8989. this.handleMouseOut_ = e => this.handleMouseOut(e);
  8990. this.handleClick_ = e => this.handleClick(e);
  8991. this.handleKeyDown_ = e => this.handleKeyDown(e);
  8992. this.emitTapEvents();
  8993. this.enable();
  8994. }
  8995. /**
  8996. * Create the `ClickableComponent`s DOM element.
  8997. *
  8998. * @param {string} [tag=div]
  8999. * The element's node type.
  9000. *
  9001. * @param {Object} [props={}]
  9002. * An object of properties that should be set on the element.
  9003. *
  9004. * @param {Object} [attributes={}]
  9005. * An object of attributes that should be set on the element.
  9006. *
  9007. * @return {Element}
  9008. * The element that gets created.
  9009. */
  9010. createEl(tag = 'div', props = {}, attributes = {}) {
  9011. props = Object.assign({
  9012. className: this.buildCSSClass(),
  9013. tabIndex: 0
  9014. }, props);
  9015. if (tag === 'button') {
  9016. log$1.error(`Creating a ClickableComponent with an HTML element of ${tag} is not supported; use a Button instead.`);
  9017. }
  9018. // Add ARIA attributes for clickable element which is not a native HTML button
  9019. attributes = Object.assign({
  9020. role: 'button'
  9021. }, attributes);
  9022. this.tabIndex_ = props.tabIndex;
  9023. const el = createEl(tag, props, attributes);
  9024. el.appendChild(createEl('span', {
  9025. className: 'vjs-icon-placeholder'
  9026. }, {
  9027. 'aria-hidden': true
  9028. }));
  9029. this.createControlTextEl(el);
  9030. return el;
  9031. }
  9032. dispose() {
  9033. // remove controlTextEl_ on dispose
  9034. this.controlTextEl_ = null;
  9035. super.dispose();
  9036. }
  9037. /**
  9038. * Create a control text element on this `ClickableComponent`
  9039. *
  9040. * @param {Element} [el]
  9041. * Parent element for the control text.
  9042. *
  9043. * @return {Element}
  9044. * The control text element that gets created.
  9045. */
  9046. createControlTextEl(el) {
  9047. this.controlTextEl_ = createEl('span', {
  9048. className: 'vjs-control-text'
  9049. }, {
  9050. // let the screen reader user know that the text of the element may change
  9051. 'aria-live': 'polite'
  9052. });
  9053. if (el) {
  9054. el.appendChild(this.controlTextEl_);
  9055. }
  9056. this.controlText(this.controlText_, el);
  9057. return this.controlTextEl_;
  9058. }
  9059. /**
  9060. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9061. *
  9062. * @param {string} [text]
  9063. * Control text for element.
  9064. *
  9065. * @param {Element} [el=this.el()]
  9066. * Element to set the title on.
  9067. *
  9068. * @return {string}
  9069. * - The control text when getting
  9070. */
  9071. controlText(text, el = this.el()) {
  9072. if (text === undefined) {
  9073. return this.controlText_ || 'Need Text';
  9074. }
  9075. const localizedText = this.localize(text);
  9076. /** @protected */
  9077. this.controlText_ = text;
  9078. textContent(this.controlTextEl_, localizedText);
  9079. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9080. // Set title attribute if only an icon is shown
  9081. el.setAttribute('title', localizedText);
  9082. }
  9083. }
  9084. /**
  9085. * Builds the default DOM `className`.
  9086. *
  9087. * @return {string}
  9088. * The DOM `className` for this object.
  9089. */
  9090. buildCSSClass() {
  9091. return `vjs-control vjs-button ${super.buildCSSClass()}`;
  9092. }
  9093. /**
  9094. * Enable this `ClickableComponent`
  9095. */
  9096. enable() {
  9097. if (!this.enabled_) {
  9098. this.enabled_ = true;
  9099. this.removeClass('vjs-disabled');
  9100. this.el_.setAttribute('aria-disabled', 'false');
  9101. if (typeof this.tabIndex_ !== 'undefined') {
  9102. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9103. }
  9104. this.on(['tap', 'click'], this.handleClick_);
  9105. this.on('keydown', this.handleKeyDown_);
  9106. }
  9107. }
  9108. /**
  9109. * Disable this `ClickableComponent`
  9110. */
  9111. disable() {
  9112. this.enabled_ = false;
  9113. this.addClass('vjs-disabled');
  9114. this.el_.setAttribute('aria-disabled', 'true');
  9115. if (typeof this.tabIndex_ !== 'undefined') {
  9116. this.el_.removeAttribute('tabIndex');
  9117. }
  9118. this.off('mouseover', this.handleMouseOver_);
  9119. this.off('mouseout', this.handleMouseOut_);
  9120. this.off(['tap', 'click'], this.handleClick_);
  9121. this.off('keydown', this.handleKeyDown_);
  9122. }
  9123. /**
  9124. * Handles language change in ClickableComponent for the player in components
  9125. *
  9126. *
  9127. */
  9128. handleLanguagechange() {
  9129. this.controlText(this.controlText_);
  9130. }
  9131. /**
  9132. * Event handler that is called when a `ClickableComponent` receives a
  9133. * `click` or `tap` event.
  9134. *
  9135. * @param {Event} event
  9136. * The `tap` or `click` event that caused this function to be called.
  9137. *
  9138. * @listens tap
  9139. * @listens click
  9140. * @abstract
  9141. */
  9142. handleClick(event) {
  9143. if (this.options_.clickHandler) {
  9144. this.options_.clickHandler.call(this, arguments);
  9145. }
  9146. }
  9147. /**
  9148. * Event handler that is called when a `ClickableComponent` receives a
  9149. * `keydown` event.
  9150. *
  9151. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9152. *
  9153. * @param {Event} event
  9154. * The `keydown` event that caused this function to be called.
  9155. *
  9156. * @listens keydown
  9157. */
  9158. handleKeyDown(event) {
  9159. // Support Space or Enter key operation to fire a click event. Also,
  9160. // prevent the event from propagating through the DOM and triggering
  9161. // Player hotkeys.
  9162. if (keycode__default["default"].isEventKey(event, 'Space') || keycode__default["default"].isEventKey(event, 'Enter')) {
  9163. event.preventDefault();
  9164. event.stopPropagation();
  9165. this.trigger('click');
  9166. } else {
  9167. // Pass keypress handling up for unsupported keys
  9168. super.handleKeyDown(event);
  9169. }
  9170. }
  9171. }
  9172. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  9173. /**
  9174. * @file poster-image.js
  9175. */
  9176. /**
  9177. * A `ClickableComponent` that handles showing the poster image for the player.
  9178. *
  9179. * @extends ClickableComponent
  9180. */
  9181. class PosterImage extends ClickableComponent {
  9182. /**
  9183. * Create an instance of this class.
  9184. *
  9185. * @param { import('./player').default } player
  9186. * The `Player` that this class should attach to.
  9187. *
  9188. * @param {Object} [options]
  9189. * The key/value store of player options.
  9190. */
  9191. constructor(player, options) {
  9192. super(player, options);
  9193. this.update();
  9194. this.update_ = e => this.update(e);
  9195. player.on('posterchange', this.update_);
  9196. }
  9197. /**
  9198. * Clean up and dispose of the `PosterImage`.
  9199. */
  9200. dispose() {
  9201. this.player().off('posterchange', this.update_);
  9202. super.dispose();
  9203. }
  9204. /**
  9205. * Create the `PosterImage`s DOM element.
  9206. *
  9207. * @return {Element}
  9208. * The element that gets created.
  9209. */
  9210. createEl() {
  9211. // The el is an empty div to keep position in the DOM
  9212. // A picture and img el will be inserted when a source is set
  9213. return createEl('div', {
  9214. className: 'vjs-poster'
  9215. });
  9216. }
  9217. /**
  9218. * Get or set the `PosterImage`'s crossOrigin option.
  9219. *
  9220. * @param {string|null} [value]
  9221. * The value to set the crossOrigin to. If an argument is
  9222. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  9223. *
  9224. * @return {string|null}
  9225. * - The current crossOrigin value of the `Player` when getting.
  9226. * - undefined when setting
  9227. */
  9228. crossOrigin(value) {
  9229. // `null` can be set to unset a value
  9230. if (typeof value === 'undefined') {
  9231. if (this.$('img')) {
  9232. // If the poster's element exists, give its value
  9233. return this.$('img').crossOrigin;
  9234. } else if (this.player_.tech_ && this.player_.tech_.isReady_) {
  9235. // If not but the tech is ready, query the tech
  9236. return this.player_.crossOrigin();
  9237. }
  9238. // Otherwise check options as the poster is usually set before the state of crossorigin
  9239. // can be retrieved by the getter
  9240. return this.player_.options_.crossOrigin || this.player_.options_.crossorigin || null;
  9241. }
  9242. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  9243. this.player_.log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  9244. return;
  9245. }
  9246. if (this.$('img')) {
  9247. this.$('img').crossOrigin = value;
  9248. }
  9249. return;
  9250. }
  9251. /**
  9252. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9253. *
  9254. * @listens Player#posterchange
  9255. *
  9256. * @param {Event} [event]
  9257. * The `Player#posterchange` event that triggered this function.
  9258. */
  9259. update(event) {
  9260. const url = this.player().poster();
  9261. this.setSrc(url);
  9262. // If there's no poster source we should display:none on this component
  9263. // so it's not still clickable or right-clickable
  9264. if (url) {
  9265. this.show();
  9266. } else {
  9267. this.hide();
  9268. }
  9269. }
  9270. /**
  9271. * Set the source of the `PosterImage` depending on the display method. (Re)creates
  9272. * the inner picture and img elementss when needed.
  9273. *
  9274. * @param {string} [url]
  9275. * The URL to the source for the `PosterImage`. If not specified or falsy,
  9276. * any source and ant inner picture/img are removed.
  9277. */
  9278. setSrc(url) {
  9279. if (!url) {
  9280. this.el_.textContent = '';
  9281. return;
  9282. }
  9283. if (!this.$('img')) {
  9284. this.el_.appendChild(createEl('picture', {
  9285. className: 'vjs-poster',
  9286. // Don't want poster to be tabbable.
  9287. tabIndex: -1
  9288. }, {}, createEl('img', {
  9289. loading: 'lazy',
  9290. crossOrigin: this.crossOrigin()
  9291. }, {
  9292. alt: ''
  9293. })));
  9294. }
  9295. this.$('img').src = url;
  9296. }
  9297. /**
  9298. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9299. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9300. *
  9301. * @listens tap
  9302. * @listens click
  9303. * @listens keydown
  9304. *
  9305. * @param {Event} event
  9306. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9307. */
  9308. handleClick(event) {
  9309. // We don't want a click to trigger playback when controls are disabled
  9310. if (!this.player_.controls()) {
  9311. return;
  9312. }
  9313. if (this.player_.tech(true)) {
  9314. this.player_.tech(true).focus();
  9315. }
  9316. if (this.player_.paused()) {
  9317. silencePromise(this.player_.play());
  9318. } else {
  9319. this.player_.pause();
  9320. }
  9321. }
  9322. }
  9323. /**
  9324. * Get or set the `PosterImage`'s crossorigin option. For the HTML5 player, this
  9325. * sets the `crossOrigin` property on the `<img>` tag to control the CORS
  9326. * behavior.
  9327. *
  9328. * @param {string|null} [value]
  9329. * The value to set the `PosterImages`'s crossorigin to. If an argument is
  9330. * given, must be one of `anonymous` or `use-credentials`.
  9331. *
  9332. * @return {string|null|undefined}
  9333. * - The current crossorigin value of the `Player` when getting.
  9334. * - undefined when setting
  9335. */
  9336. PosterImage.prototype.crossorigin = PosterImage.prototype.crossOrigin;
  9337. Component$1.registerComponent('PosterImage', PosterImage);
  9338. /**
  9339. * @file text-track-display.js
  9340. */
  9341. const darkGray = '#222';
  9342. const lightGray = '#ccc';
  9343. const fontMap = {
  9344. monospace: 'monospace',
  9345. sansSerif: 'sans-serif',
  9346. serif: 'serif',
  9347. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9348. monospaceSerif: '"Courier New", monospace',
  9349. proportionalSansSerif: 'sans-serif',
  9350. proportionalSerif: 'serif',
  9351. casual: '"Comic Sans MS", Impact, fantasy',
  9352. script: '"Monotype Corsiva", cursive',
  9353. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9354. };
  9355. /**
  9356. * Construct an rgba color from a given hex color code.
  9357. *
  9358. * @param {number} color
  9359. * Hex number for color, like #f0e or #f604e2.
  9360. *
  9361. * @param {number} opacity
  9362. * Value for opacity, 0.0 - 1.0.
  9363. *
  9364. * @return {string}
  9365. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9366. */
  9367. function constructColor(color, opacity) {
  9368. let hex;
  9369. if (color.length === 4) {
  9370. // color looks like "#f0e"
  9371. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9372. } else if (color.length === 7) {
  9373. // color looks like "#f604e2"
  9374. hex = color.slice(1);
  9375. } else {
  9376. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9377. }
  9378. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9379. }
  9380. /**
  9381. * Try to update the style of a DOM element. Some style changes will throw an error,
  9382. * particularly in IE8. Those should be noops.
  9383. *
  9384. * @param {Element} el
  9385. * The DOM element to be styled.
  9386. *
  9387. * @param {string} style
  9388. * The CSS property on the element that should be styled.
  9389. *
  9390. * @param {string} rule
  9391. * The style rule that should be applied to the property.
  9392. *
  9393. * @private
  9394. */
  9395. function tryUpdateStyle(el, style, rule) {
  9396. try {
  9397. el.style[style] = rule;
  9398. } catch (e) {
  9399. // Satisfies linter.
  9400. return;
  9401. }
  9402. }
  9403. /**
  9404. * The component for displaying text track cues.
  9405. *
  9406. * @extends Component
  9407. */
  9408. class TextTrackDisplay extends Component$1 {
  9409. /**
  9410. * Creates an instance of this class.
  9411. *
  9412. * @param { import('../player').default } player
  9413. * The `Player` that this class should be attached to.
  9414. *
  9415. * @param {Object} [options]
  9416. * The key/value store of player options.
  9417. *
  9418. * @param {Function} [ready]
  9419. * The function to call when `TextTrackDisplay` is ready.
  9420. */
  9421. constructor(player, options, ready) {
  9422. super(player, options, ready);
  9423. const updateDisplayHandler = e => this.updateDisplay(e);
  9424. player.on('loadstart', e => this.toggleDisplay(e));
  9425. player.on('texttrackchange', updateDisplayHandler);
  9426. player.on('loadedmetadata', e => this.preselectTrack(e));
  9427. // This used to be called during player init, but was causing an error
  9428. // if a track should show by default and the display hadn't loaded yet.
  9429. // Should probably be moved to an external track loader when we support
  9430. // tracks that don't need a display.
  9431. player.ready(bind_(this, function () {
  9432. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  9433. this.hide();
  9434. return;
  9435. }
  9436. player.on('fullscreenchange', updateDisplayHandler);
  9437. player.on('playerresize', updateDisplayHandler);
  9438. const screenOrientation = window__default["default"].screen.orientation || window__default["default"];
  9439. const changeOrientationEvent = window__default["default"].screen.orientation ? 'change' : 'orientationchange';
  9440. screenOrientation.addEventListener(changeOrientationEvent, updateDisplayHandler);
  9441. player.on('dispose', () => screenOrientation.removeEventListener(changeOrientationEvent, updateDisplayHandler));
  9442. const tracks = this.options_.playerOptions.tracks || [];
  9443. for (let i = 0; i < tracks.length; i++) {
  9444. this.player_.addRemoteTextTrack(tracks[i], true);
  9445. }
  9446. this.preselectTrack();
  9447. }));
  9448. }
  9449. /**
  9450. * Preselect a track following this precedence:
  9451. * - matches the previously selected {@link TextTrack}'s language and kind
  9452. * - matches the previously selected {@link TextTrack}'s language only
  9453. * - is the first default captions track
  9454. * - is the first default descriptions track
  9455. *
  9456. * @listens Player#loadstart
  9457. */
  9458. preselectTrack() {
  9459. const modes = {
  9460. captions: 1,
  9461. subtitles: 1
  9462. };
  9463. const trackList = this.player_.textTracks();
  9464. const userPref = this.player_.cache_.selectedLanguage;
  9465. let firstDesc;
  9466. let firstCaptions;
  9467. let preferredTrack;
  9468. for (let i = 0; i < trackList.length; i++) {
  9469. const track = trackList[i];
  9470. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  9471. // Always choose the track that matches both language and kind
  9472. if (track.kind === userPref.kind) {
  9473. preferredTrack = track;
  9474. // or choose the first track that matches language
  9475. } else if (!preferredTrack) {
  9476. preferredTrack = track;
  9477. }
  9478. // clear everything if offTextTrackMenuItem was clicked
  9479. } else if (userPref && !userPref.enabled) {
  9480. preferredTrack = null;
  9481. firstDesc = null;
  9482. firstCaptions = null;
  9483. } else if (track.default) {
  9484. if (track.kind === 'descriptions' && !firstDesc) {
  9485. firstDesc = track;
  9486. } else if (track.kind in modes && !firstCaptions) {
  9487. firstCaptions = track;
  9488. }
  9489. }
  9490. }
  9491. // The preferredTrack matches the user preference and takes
  9492. // precedence over all the other tracks.
  9493. // So, display the preferredTrack before the first default track
  9494. // and the subtitles/captions track before the descriptions track
  9495. if (preferredTrack) {
  9496. preferredTrack.mode = 'showing';
  9497. } else if (firstCaptions) {
  9498. firstCaptions.mode = 'showing';
  9499. } else if (firstDesc) {
  9500. firstDesc.mode = 'showing';
  9501. }
  9502. }
  9503. /**
  9504. * Turn display of {@link TextTrack}'s from the current state into the other state.
  9505. * There are only two states:
  9506. * - 'shown'
  9507. * - 'hidden'
  9508. *
  9509. * @listens Player#loadstart
  9510. */
  9511. toggleDisplay() {
  9512. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  9513. this.hide();
  9514. } else {
  9515. this.show();
  9516. }
  9517. }
  9518. /**
  9519. * Create the {@link Component}'s DOM element.
  9520. *
  9521. * @return {Element}
  9522. * The element that was created.
  9523. */
  9524. createEl() {
  9525. return super.createEl('div', {
  9526. className: 'vjs-text-track-display'
  9527. }, {
  9528. 'translate': 'yes',
  9529. 'aria-live': 'off',
  9530. 'aria-atomic': 'true'
  9531. });
  9532. }
  9533. /**
  9534. * Clear all displayed {@link TextTrack}s.
  9535. */
  9536. clearDisplay() {
  9537. if (typeof window__default["default"].WebVTT === 'function') {
  9538. window__default["default"].WebVTT.processCues(window__default["default"], [], this.el_);
  9539. }
  9540. }
  9541. /**
  9542. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  9543. * a {@link Player#fullscreenchange} is fired.
  9544. *
  9545. * @listens Player#texttrackchange
  9546. * @listens Player#fullscreenchange
  9547. */
  9548. updateDisplay() {
  9549. const tracks = this.player_.textTracks();
  9550. const allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  9551. this.clearDisplay();
  9552. if (allowMultipleShowingTracks) {
  9553. const showingTracks = [];
  9554. for (let i = 0; i < tracks.length; ++i) {
  9555. const track = tracks[i];
  9556. if (track.mode !== 'showing') {
  9557. continue;
  9558. }
  9559. showingTracks.push(track);
  9560. }
  9561. this.updateForTrack(showingTracks);
  9562. return;
  9563. }
  9564. // Track display prioritization model: if multiple tracks are 'showing',
  9565. // display the first 'subtitles' or 'captions' track which is 'showing',
  9566. // otherwise display the first 'descriptions' track which is 'showing'
  9567. let descriptionsTrack = null;
  9568. let captionsSubtitlesTrack = null;
  9569. let i = tracks.length;
  9570. while (i--) {
  9571. const track = tracks[i];
  9572. if (track.mode === 'showing') {
  9573. if (track.kind === 'descriptions') {
  9574. descriptionsTrack = track;
  9575. } else {
  9576. captionsSubtitlesTrack = track;
  9577. }
  9578. }
  9579. }
  9580. if (captionsSubtitlesTrack) {
  9581. if (this.getAttribute('aria-live') !== 'off') {
  9582. this.setAttribute('aria-live', 'off');
  9583. }
  9584. this.updateForTrack(captionsSubtitlesTrack);
  9585. } else if (descriptionsTrack) {
  9586. if (this.getAttribute('aria-live') !== 'assertive') {
  9587. this.setAttribute('aria-live', 'assertive');
  9588. }
  9589. this.updateForTrack(descriptionsTrack);
  9590. }
  9591. }
  9592. /**
  9593. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  9594. *
  9595. * @param {TextTrack} track
  9596. * Text track object containing active cues to style.
  9597. */
  9598. updateDisplayState(track) {
  9599. const overrides = this.player_.textTrackSettings.getValues();
  9600. const cues = track.activeCues;
  9601. let i = cues.length;
  9602. while (i--) {
  9603. const cue = cues[i];
  9604. if (!cue) {
  9605. continue;
  9606. }
  9607. const cueDiv = cue.displayState;
  9608. if (overrides.color) {
  9609. cueDiv.firstChild.style.color = overrides.color;
  9610. }
  9611. if (overrides.textOpacity) {
  9612. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  9613. }
  9614. if (overrides.backgroundColor) {
  9615. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  9616. }
  9617. if (overrides.backgroundOpacity) {
  9618. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  9619. }
  9620. if (overrides.windowColor) {
  9621. if (overrides.windowOpacity) {
  9622. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  9623. } else {
  9624. cueDiv.style.backgroundColor = overrides.windowColor;
  9625. }
  9626. }
  9627. if (overrides.edgeStyle) {
  9628. if (overrides.edgeStyle === 'dropshadow') {
  9629. cueDiv.firstChild.style.textShadow = `2px 2px 3px ${darkGray}, 2px 2px 4px ${darkGray}, 2px 2px 5px ${darkGray}`;
  9630. } else if (overrides.edgeStyle === 'raised') {
  9631. cueDiv.firstChild.style.textShadow = `1px 1px ${darkGray}, 2px 2px ${darkGray}, 3px 3px ${darkGray}`;
  9632. } else if (overrides.edgeStyle === 'depressed') {
  9633. cueDiv.firstChild.style.textShadow = `1px 1px ${lightGray}, 0 1px ${lightGray}, -1px -1px ${darkGray}, 0 -1px ${darkGray}`;
  9634. } else if (overrides.edgeStyle === 'uniform') {
  9635. cueDiv.firstChild.style.textShadow = `0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}, 0 0 4px ${darkGray}`;
  9636. }
  9637. }
  9638. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  9639. const fontSize = window__default["default"].parseFloat(cueDiv.style.fontSize);
  9640. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  9641. cueDiv.style.height = 'auto';
  9642. cueDiv.style.top = 'auto';
  9643. }
  9644. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  9645. if (overrides.fontFamily === 'small-caps') {
  9646. cueDiv.firstChild.style.fontVariant = 'small-caps';
  9647. } else {
  9648. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  9649. }
  9650. }
  9651. }
  9652. }
  9653. /**
  9654. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  9655. *
  9656. * @param {TextTrack|TextTrack[]} tracks
  9657. * Text track object or text track array to be added to the list.
  9658. */
  9659. updateForTrack(tracks) {
  9660. if (!Array.isArray(tracks)) {
  9661. tracks = [tracks];
  9662. }
  9663. if (typeof window__default["default"].WebVTT !== 'function' || tracks.every(track => {
  9664. return !track.activeCues;
  9665. })) {
  9666. return;
  9667. }
  9668. const cues = [];
  9669. // push all active track cues
  9670. for (let i = 0; i < tracks.length; ++i) {
  9671. const track = tracks[i];
  9672. for (let j = 0; j < track.activeCues.length; ++j) {
  9673. cues.push(track.activeCues[j]);
  9674. }
  9675. }
  9676. // removes all cues before it processes new ones
  9677. window__default["default"].WebVTT.processCues(window__default["default"], cues, this.el_);
  9678. // add unique class to each language text track & add settings styling if necessary
  9679. for (let i = 0; i < tracks.length; ++i) {
  9680. const track = tracks[i];
  9681. for (let j = 0; j < track.activeCues.length; ++j) {
  9682. const cueEl = track.activeCues[j].displayState;
  9683. addClass(cueEl, 'vjs-text-track-cue', 'vjs-text-track-cue-' + (track.language ? track.language : i));
  9684. if (track.language) {
  9685. setAttribute(cueEl, 'lang', track.language);
  9686. }
  9687. }
  9688. if (this.player_.textTrackSettings) {
  9689. this.updateDisplayState(track);
  9690. }
  9691. }
  9692. }
  9693. }
  9694. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  9695. /**
  9696. * @file loading-spinner.js
  9697. */
  9698. /**
  9699. * A loading spinner for use during waiting/loading events.
  9700. *
  9701. * @extends Component
  9702. */
  9703. class LoadingSpinner extends Component$1 {
  9704. /**
  9705. * Create the `LoadingSpinner`s DOM element.
  9706. *
  9707. * @return {Element}
  9708. * The dom element that gets created.
  9709. */
  9710. createEl() {
  9711. const isAudio = this.player_.isAudio();
  9712. const playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  9713. const controlText = createEl('span', {
  9714. className: 'vjs-control-text',
  9715. textContent: this.localize('{1} is loading.', [playerType])
  9716. });
  9717. const el = super.createEl('div', {
  9718. className: 'vjs-loading-spinner',
  9719. dir: 'ltr'
  9720. });
  9721. el.appendChild(controlText);
  9722. return el;
  9723. }
  9724. /**
  9725. * Update control text on languagechange
  9726. */
  9727. handleLanguagechange() {
  9728. this.$('.vjs-control-text').textContent = this.localize('{1} is loading.', [this.player_.isAudio() ? 'Audio Player' : 'Video Player']);
  9729. }
  9730. }
  9731. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  9732. /**
  9733. * @file button.js
  9734. */
  9735. /**
  9736. * Base class for all buttons.
  9737. *
  9738. * @extends ClickableComponent
  9739. */
  9740. class Button extends ClickableComponent {
  9741. /**
  9742. * Create the `Button`s DOM element.
  9743. *
  9744. * @param {string} [tag="button"]
  9745. * The element's node type. This argument is IGNORED: no matter what
  9746. * is passed, it will always create a `button` element.
  9747. *
  9748. * @param {Object} [props={}]
  9749. * An object of properties that should be set on the element.
  9750. *
  9751. * @param {Object} [attributes={}]
  9752. * An object of attributes that should be set on the element.
  9753. *
  9754. * @return {Element}
  9755. * The element that gets created.
  9756. */
  9757. createEl(tag, props = {}, attributes = {}) {
  9758. tag = 'button';
  9759. props = Object.assign({
  9760. className: this.buildCSSClass()
  9761. }, props);
  9762. // Add attributes for button element
  9763. attributes = Object.assign({
  9764. // Necessary since the default button type is "submit"
  9765. type: 'button'
  9766. }, attributes);
  9767. const el = createEl(tag, props, attributes);
  9768. el.appendChild(createEl('span', {
  9769. className: 'vjs-icon-placeholder'
  9770. }, {
  9771. 'aria-hidden': true
  9772. }));
  9773. this.createControlTextEl(el);
  9774. return el;
  9775. }
  9776. /**
  9777. * Add a child `Component` inside of this `Button`.
  9778. *
  9779. * @param {string|Component} child
  9780. * The name or instance of a child to add.
  9781. *
  9782. * @param {Object} [options={}]
  9783. * The key/value store of options that will get passed to children of
  9784. * the child.
  9785. *
  9786. * @return {Component}
  9787. * The `Component` that gets added as a child. When using a string the
  9788. * `Component` will get created by this process.
  9789. *
  9790. * @deprecated since version 5
  9791. */
  9792. addChild(child, options = {}) {
  9793. const className = this.constructor.name;
  9794. log$1.warn(`Adding an actionable (user controllable) child to a Button (${className}) is not supported; use a ClickableComponent instead.`);
  9795. // Avoid the error message generated by ClickableComponent's addChild method
  9796. return Component$1.prototype.addChild.call(this, child, options);
  9797. }
  9798. /**
  9799. * Enable the `Button` element so that it can be activated or clicked. Use this with
  9800. * {@link Button#disable}.
  9801. */
  9802. enable() {
  9803. super.enable();
  9804. this.el_.removeAttribute('disabled');
  9805. }
  9806. /**
  9807. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  9808. * {@link Button#enable}.
  9809. */
  9810. disable() {
  9811. super.disable();
  9812. this.el_.setAttribute('disabled', 'disabled');
  9813. }
  9814. /**
  9815. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  9816. * press.
  9817. *
  9818. * @param {Event} event
  9819. * The event that caused this function to get called.
  9820. *
  9821. * @listens keydown
  9822. */
  9823. handleKeyDown(event) {
  9824. // Ignore Space or Enter key operation, which is handled by the browser for
  9825. // a button - though not for its super class, ClickableComponent. Also,
  9826. // prevent the event from propagating through the DOM and triggering Player
  9827. // hotkeys. We do not preventDefault here because we _want_ the browser to
  9828. // handle it.
  9829. if (keycode__default["default"].isEventKey(event, 'Space') || keycode__default["default"].isEventKey(event, 'Enter')) {
  9830. event.stopPropagation();
  9831. return;
  9832. }
  9833. // Pass keypress handling up for unsupported keys
  9834. super.handleKeyDown(event);
  9835. }
  9836. }
  9837. Component$1.registerComponent('Button', Button);
  9838. /**
  9839. * @file big-play-button.js
  9840. */
  9841. /**
  9842. * The initial play button that shows before the video has played. The hiding of the
  9843. * `BigPlayButton` get done via CSS and `Player` states.
  9844. *
  9845. * @extends Button
  9846. */
  9847. class BigPlayButton extends Button {
  9848. constructor(player, options) {
  9849. super(player, options);
  9850. this.mouseused_ = false;
  9851. this.on('mousedown', e => this.handleMouseDown(e));
  9852. }
  9853. /**
  9854. * Builds the default DOM `className`.
  9855. *
  9856. * @return {string}
  9857. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  9858. */
  9859. buildCSSClass() {
  9860. return 'vjs-big-play-button';
  9861. }
  9862. /**
  9863. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  9864. * for more detailed information on what a click can be.
  9865. *
  9866. * @param {KeyboardEvent} event
  9867. * The `keydown`, `tap`, or `click` event that caused this function to be
  9868. * called.
  9869. *
  9870. * @listens tap
  9871. * @listens click
  9872. */
  9873. handleClick(event) {
  9874. const playPromise = this.player_.play();
  9875. // exit early if clicked via the mouse
  9876. if (this.mouseused_ && event.clientX && event.clientY) {
  9877. silencePromise(playPromise);
  9878. if (this.player_.tech(true)) {
  9879. this.player_.tech(true).focus();
  9880. }
  9881. return;
  9882. }
  9883. const cb = this.player_.getChild('controlBar');
  9884. const playToggle = cb && cb.getChild('playToggle');
  9885. if (!playToggle) {
  9886. this.player_.tech(true).focus();
  9887. return;
  9888. }
  9889. const playFocus = () => playToggle.focus();
  9890. if (isPromise(playPromise)) {
  9891. playPromise.then(playFocus, () => {});
  9892. } else {
  9893. this.setTimeout(playFocus, 1);
  9894. }
  9895. }
  9896. handleKeyDown(event) {
  9897. this.mouseused_ = false;
  9898. super.handleKeyDown(event);
  9899. }
  9900. handleMouseDown(event) {
  9901. this.mouseused_ = true;
  9902. }
  9903. }
  9904. /**
  9905. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  9906. *
  9907. * @type {string}
  9908. * @protected
  9909. */
  9910. BigPlayButton.prototype.controlText_ = 'Play Video';
  9911. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  9912. /**
  9913. * @file close-button.js
  9914. */
  9915. /**
  9916. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  9917. * it gets clicked.
  9918. *
  9919. * @extends Button
  9920. */
  9921. class CloseButton extends Button {
  9922. /**
  9923. * Creates an instance of the this class.
  9924. *
  9925. * @param { import('./player').default } player
  9926. * The `Player` that this class should be attached to.
  9927. *
  9928. * @param {Object} [options]
  9929. * The key/value store of player options.
  9930. */
  9931. constructor(player, options) {
  9932. super(player, options);
  9933. this.controlText(options && options.controlText || this.localize('Close'));
  9934. }
  9935. /**
  9936. * Builds the default DOM `className`.
  9937. *
  9938. * @return {string}
  9939. * The DOM `className` for this object.
  9940. */
  9941. buildCSSClass() {
  9942. return `vjs-close-button ${super.buildCSSClass()}`;
  9943. }
  9944. /**
  9945. * This gets called when a `CloseButton` gets clicked. See
  9946. * {@link ClickableComponent#handleClick} for more information on when
  9947. * this will be triggered
  9948. *
  9949. * @param {Event} event
  9950. * The `keydown`, `tap`, or `click` event that caused this function to be
  9951. * called.
  9952. *
  9953. * @listens tap
  9954. * @listens click
  9955. * @fires CloseButton#close
  9956. */
  9957. handleClick(event) {
  9958. /**
  9959. * Triggered when the a `CloseButton` is clicked.
  9960. *
  9961. * @event CloseButton#close
  9962. * @type {Event}
  9963. *
  9964. * @property {boolean} [bubbles=false]
  9965. * set to false so that the close event does not
  9966. * bubble up to parents if there is no listener
  9967. */
  9968. this.trigger({
  9969. type: 'close',
  9970. bubbles: false
  9971. });
  9972. }
  9973. /**
  9974. * Event handler that is called when a `CloseButton` receives a
  9975. * `keydown` event.
  9976. *
  9977. * By default, if the key is Esc, it will trigger a `click` event.
  9978. *
  9979. * @param {Event} event
  9980. * The `keydown` event that caused this function to be called.
  9981. *
  9982. * @listens keydown
  9983. */
  9984. handleKeyDown(event) {
  9985. // Esc button will trigger `click` event
  9986. if (keycode__default["default"].isEventKey(event, 'Esc')) {
  9987. event.preventDefault();
  9988. event.stopPropagation();
  9989. this.trigger('click');
  9990. } else {
  9991. // Pass keypress handling up for unsupported keys
  9992. super.handleKeyDown(event);
  9993. }
  9994. }
  9995. }
  9996. Component$1.registerComponent('CloseButton', CloseButton);
  9997. /**
  9998. * @file play-toggle.js
  9999. */
  10000. /**
  10001. * Button to toggle between play and pause.
  10002. *
  10003. * @extends Button
  10004. */
  10005. class PlayToggle extends Button {
  10006. /**
  10007. * Creates an instance of this class.
  10008. *
  10009. * @param { import('./player').default } player
  10010. * The `Player` that this class should be attached to.
  10011. *
  10012. * @param {Object} [options={}]
  10013. * The key/value store of player options.
  10014. */
  10015. constructor(player, options = {}) {
  10016. super(player, options);
  10017. // show or hide replay icon
  10018. options.replay = options.replay === undefined || options.replay;
  10019. this.on(player, 'play', e => this.handlePlay(e));
  10020. this.on(player, 'pause', e => this.handlePause(e));
  10021. if (options.replay) {
  10022. this.on(player, 'ended', e => this.handleEnded(e));
  10023. }
  10024. }
  10025. /**
  10026. * Builds the default DOM `className`.
  10027. *
  10028. * @return {string}
  10029. * The DOM `className` for this object.
  10030. */
  10031. buildCSSClass() {
  10032. return `vjs-play-control ${super.buildCSSClass()}`;
  10033. }
  10034. /**
  10035. * This gets called when an `PlayToggle` is "clicked". See
  10036. * {@link ClickableComponent} for more detailed information on what a click can be.
  10037. *
  10038. * @param {Event} [event]
  10039. * The `keydown`, `tap`, or `click` event that caused this function to be
  10040. * called.
  10041. *
  10042. * @listens tap
  10043. * @listens click
  10044. */
  10045. handleClick(event) {
  10046. if (this.player_.paused()) {
  10047. silencePromise(this.player_.play());
  10048. } else {
  10049. this.player_.pause();
  10050. }
  10051. }
  10052. /**
  10053. * This gets called once after the video has ended and the user seeks so that
  10054. * we can change the replay button back to a play button.
  10055. *
  10056. * @param {Event} [event]
  10057. * The event that caused this function to run.
  10058. *
  10059. * @listens Player#seeked
  10060. */
  10061. handleSeeked(event) {
  10062. this.removeClass('vjs-ended');
  10063. if (this.player_.paused()) {
  10064. this.handlePause(event);
  10065. } else {
  10066. this.handlePlay(event);
  10067. }
  10068. }
  10069. /**
  10070. * Add the vjs-playing class to the element so it can change appearance.
  10071. *
  10072. * @param {Event} [event]
  10073. * The event that caused this function to run.
  10074. *
  10075. * @listens Player#play
  10076. */
  10077. handlePlay(event) {
  10078. this.removeClass('vjs-ended', 'vjs-paused');
  10079. this.addClass('vjs-playing');
  10080. // change the button text to "Pause"
  10081. this.controlText('Pause');
  10082. }
  10083. /**
  10084. * Add the vjs-paused class to the element so it can change appearance.
  10085. *
  10086. * @param {Event} [event]
  10087. * The event that caused this function to run.
  10088. *
  10089. * @listens Player#pause
  10090. */
  10091. handlePause(event) {
  10092. this.removeClass('vjs-playing');
  10093. this.addClass('vjs-paused');
  10094. // change the button text to "Play"
  10095. this.controlText('Play');
  10096. }
  10097. /**
  10098. * Add the vjs-ended class to the element so it can change appearance
  10099. *
  10100. * @param {Event} [event]
  10101. * The event that caused this function to run.
  10102. *
  10103. * @listens Player#ended
  10104. */
  10105. handleEnded(event) {
  10106. this.removeClass('vjs-playing');
  10107. this.addClass('vjs-ended');
  10108. // change the button text to "Replay"
  10109. this.controlText('Replay');
  10110. // on the next seek remove the replay button
  10111. this.one(this.player_, 'seeked', e => this.handleSeeked(e));
  10112. }
  10113. }
  10114. /**
  10115. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10116. *
  10117. * @type {string}
  10118. * @protected
  10119. */
  10120. PlayToggle.prototype.controlText_ = 'Play';
  10121. Component$1.registerComponent('PlayToggle', PlayToggle);
  10122. /**
  10123. * @file time-display.js
  10124. */
  10125. /**
  10126. * Displays time information about the video
  10127. *
  10128. * @extends Component
  10129. */
  10130. class TimeDisplay extends Component$1 {
  10131. /**
  10132. * Creates an instance of this class.
  10133. *
  10134. * @param { import('../../player').default } player
  10135. * The `Player` that this class should be attached to.
  10136. *
  10137. * @param {Object} [options]
  10138. * The key/value store of player options.
  10139. */
  10140. constructor(player, options) {
  10141. super(player, options);
  10142. this.on(player, ['timeupdate', 'ended'], e => this.updateContent(e));
  10143. this.updateTextNode_();
  10144. }
  10145. /**
  10146. * Create the `Component`'s DOM element
  10147. *
  10148. * @return {Element}
  10149. * The element that was created.
  10150. */
  10151. createEl() {
  10152. const className = this.buildCSSClass();
  10153. const el = super.createEl('div', {
  10154. className: `${className} vjs-time-control vjs-control`
  10155. });
  10156. const span = createEl('span', {
  10157. className: 'vjs-control-text',
  10158. textContent: `${this.localize(this.labelText_)}\u00a0`
  10159. }, {
  10160. role: 'presentation'
  10161. });
  10162. el.appendChild(span);
  10163. this.contentEl_ = createEl('span', {
  10164. className: `${className}-display`
  10165. }, {
  10166. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10167. // treat them as a break between items in the DOM when using arrow keys
  10168. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10169. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10170. role: 'presentation'
  10171. });
  10172. el.appendChild(this.contentEl_);
  10173. return el;
  10174. }
  10175. dispose() {
  10176. this.contentEl_ = null;
  10177. this.textNode_ = null;
  10178. super.dispose();
  10179. }
  10180. /**
  10181. * Updates the time display text node with a new time
  10182. *
  10183. * @param {number} [time=0] the time to update to
  10184. *
  10185. * @private
  10186. */
  10187. updateTextNode_(time = 0) {
  10188. time = formatTime(time);
  10189. if (this.formattedTime_ === time) {
  10190. return;
  10191. }
  10192. this.formattedTime_ = time;
  10193. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', () => {
  10194. if (!this.contentEl_) {
  10195. return;
  10196. }
  10197. let oldNode = this.textNode_;
  10198. if (oldNode && this.contentEl_.firstChild !== oldNode) {
  10199. oldNode = null;
  10200. log$1.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');
  10201. }
  10202. this.textNode_ = document__default["default"].createTextNode(this.formattedTime_);
  10203. if (!this.textNode_) {
  10204. return;
  10205. }
  10206. if (oldNode) {
  10207. this.contentEl_.replaceChild(this.textNode_, oldNode);
  10208. } else {
  10209. this.contentEl_.appendChild(this.textNode_);
  10210. }
  10211. });
  10212. }
  10213. /**
  10214. * To be filled out in the child class, should update the displayed time
  10215. * in accordance with the fact that the current time has changed.
  10216. *
  10217. * @param {Event} [event]
  10218. * The `timeupdate` event that caused this to run.
  10219. *
  10220. * @listens Player#timeupdate
  10221. */
  10222. updateContent(event) {}
  10223. }
  10224. /**
  10225. * The text that is added to the `TimeDisplay` for screen reader users.
  10226. *
  10227. * @type {string}
  10228. * @private
  10229. */
  10230. TimeDisplay.prototype.labelText_ = 'Time';
  10231. /**
  10232. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10233. *
  10234. * @type {string}
  10235. * @protected
  10236. *
  10237. * @deprecated in v7; controlText_ is not used in non-active display Components
  10238. */
  10239. TimeDisplay.prototype.controlText_ = 'Time';
  10240. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  10241. /**
  10242. * @file current-time-display.js
  10243. */
  10244. /**
  10245. * Displays the current time
  10246. *
  10247. * @extends Component
  10248. */
  10249. class CurrentTimeDisplay extends TimeDisplay {
  10250. /**
  10251. * Builds the default DOM `className`.
  10252. *
  10253. * @return {string}
  10254. * The DOM `className` for this object.
  10255. */
  10256. buildCSSClass() {
  10257. return 'vjs-current-time';
  10258. }
  10259. /**
  10260. * Update current time display
  10261. *
  10262. * @param {Event} [event]
  10263. * The `timeupdate` event that caused this function to run.
  10264. *
  10265. * @listens Player#timeupdate
  10266. */
  10267. updateContent(event) {
  10268. // Allows for smooth scrubbing, when player can't keep up.
  10269. let time;
  10270. if (this.player_.ended()) {
  10271. time = this.player_.duration();
  10272. } else {
  10273. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  10274. }
  10275. this.updateTextNode_(time);
  10276. }
  10277. }
  10278. /**
  10279. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  10280. *
  10281. * @type {string}
  10282. * @private
  10283. */
  10284. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  10285. /**
  10286. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  10287. *
  10288. * @type {string}
  10289. * @protected
  10290. *
  10291. * @deprecated in v7; controlText_ is not used in non-active display Components
  10292. */
  10293. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  10294. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  10295. /**
  10296. * @file duration-display.js
  10297. */
  10298. /**
  10299. * Displays the duration
  10300. *
  10301. * @extends Component
  10302. */
  10303. class DurationDisplay extends TimeDisplay {
  10304. /**
  10305. * Creates an instance of this class.
  10306. *
  10307. * @param { import('../../player').default } player
  10308. * The `Player` that this class should be attached to.
  10309. *
  10310. * @param {Object} [options]
  10311. * The key/value store of player options.
  10312. */
  10313. constructor(player, options) {
  10314. super(player, options);
  10315. const updateContent = e => this.updateContent(e);
  10316. // we do not want to/need to throttle duration changes,
  10317. // as they should always display the changed duration as
  10318. // it has changed
  10319. this.on(player, 'durationchange', updateContent);
  10320. // Listen to loadstart because the player duration is reset when a new media element is loaded,
  10321. // but the durationchange on the user agent will not fire.
  10322. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  10323. this.on(player, 'loadstart', updateContent);
  10324. // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  10325. // listeners could have broken dependent applications/libraries. These
  10326. // can likely be removed for 7.0.
  10327. this.on(player, 'loadedmetadata', updateContent);
  10328. }
  10329. /**
  10330. * Builds the default DOM `className`.
  10331. *
  10332. * @return {string}
  10333. * The DOM `className` for this object.
  10334. */
  10335. buildCSSClass() {
  10336. return 'vjs-duration';
  10337. }
  10338. /**
  10339. * Update duration time display.
  10340. *
  10341. * @param {Event} [event]
  10342. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  10343. * this function to be called.
  10344. *
  10345. * @listens Player#durationchange
  10346. * @listens Player#timeupdate
  10347. * @listens Player#loadedmetadata
  10348. */
  10349. updateContent(event) {
  10350. const duration = this.player_.duration();
  10351. this.updateTextNode_(duration);
  10352. }
  10353. }
  10354. /**
  10355. * The text that is added to the `DurationDisplay` for screen reader users.
  10356. *
  10357. * @type {string}
  10358. * @private
  10359. */
  10360. DurationDisplay.prototype.labelText_ = 'Duration';
  10361. /**
  10362. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  10363. *
  10364. * @type {string}
  10365. * @protected
  10366. *
  10367. * @deprecated in v7; controlText_ is not used in non-active display Components
  10368. */
  10369. DurationDisplay.prototype.controlText_ = 'Duration';
  10370. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  10371. /**
  10372. * @file time-divider.js
  10373. */
  10374. /**
  10375. * The separator between the current time and duration.
  10376. * Can be hidden if it's not needed in the design.
  10377. *
  10378. * @extends Component
  10379. */
  10380. class TimeDivider extends Component$1 {
  10381. /**
  10382. * Create the component's DOM element
  10383. *
  10384. * @return {Element}
  10385. * The element that was created.
  10386. */
  10387. createEl() {
  10388. const el = super.createEl('div', {
  10389. className: 'vjs-time-control vjs-time-divider'
  10390. }, {
  10391. // this element and its contents can be hidden from assistive techs since
  10392. // it is made extraneous by the announcement of the control text
  10393. // for the current time and duration displays
  10394. 'aria-hidden': true
  10395. });
  10396. const div = super.createEl('div');
  10397. const span = super.createEl('span', {
  10398. textContent: '/'
  10399. });
  10400. div.appendChild(span);
  10401. el.appendChild(div);
  10402. return el;
  10403. }
  10404. }
  10405. Component$1.registerComponent('TimeDivider', TimeDivider);
  10406. /**
  10407. * @file remaining-time-display.js
  10408. */
  10409. /**
  10410. * Displays the time left in the video
  10411. *
  10412. * @extends Component
  10413. */
  10414. class RemainingTimeDisplay extends TimeDisplay {
  10415. /**
  10416. * Creates an instance of this class.
  10417. *
  10418. * @param { import('../../player').default } player
  10419. * The `Player` that this class should be attached to.
  10420. *
  10421. * @param {Object} [options]
  10422. * The key/value store of player options.
  10423. */
  10424. constructor(player, options) {
  10425. super(player, options);
  10426. this.on(player, 'durationchange', e => this.updateContent(e));
  10427. }
  10428. /**
  10429. * Builds the default DOM `className`.
  10430. *
  10431. * @return {string}
  10432. * The DOM `className` for this object.
  10433. */
  10434. buildCSSClass() {
  10435. return 'vjs-remaining-time';
  10436. }
  10437. /**
  10438. * Create the `Component`'s DOM element with the "minus" character prepend to the time
  10439. *
  10440. * @return {Element}
  10441. * The element that was created.
  10442. */
  10443. createEl() {
  10444. const el = super.createEl();
  10445. if (this.options_.displayNegative !== false) {
  10446. el.insertBefore(createEl('span', {}, {
  10447. 'aria-hidden': true
  10448. }, '-'), this.contentEl_);
  10449. }
  10450. return el;
  10451. }
  10452. /**
  10453. * Update remaining time display.
  10454. *
  10455. * @param {Event} [event]
  10456. * The `timeupdate` or `durationchange` event that caused this to run.
  10457. *
  10458. * @listens Player#timeupdate
  10459. * @listens Player#durationchange
  10460. */
  10461. updateContent(event) {
  10462. if (typeof this.player_.duration() !== 'number') {
  10463. return;
  10464. }
  10465. let time;
  10466. // @deprecated We should only use remainingTimeDisplay
  10467. // as of video.js 7
  10468. if (this.player_.ended()) {
  10469. time = 0;
  10470. } else if (this.player_.remainingTimeDisplay) {
  10471. time = this.player_.remainingTimeDisplay();
  10472. } else {
  10473. time = this.player_.remainingTime();
  10474. }
  10475. this.updateTextNode_(time);
  10476. }
  10477. }
  10478. /**
  10479. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  10480. *
  10481. * @type {string}
  10482. * @private
  10483. */
  10484. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  10485. /**
  10486. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  10487. *
  10488. * @type {string}
  10489. * @protected
  10490. *
  10491. * @deprecated in v7; controlText_ is not used in non-active display Components
  10492. */
  10493. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  10494. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  10495. /**
  10496. * @file live-display.js
  10497. */
  10498. // TODO - Future make it click to snap to live
  10499. /**
  10500. * Displays the live indicator when duration is Infinity.
  10501. *
  10502. * @extends Component
  10503. */
  10504. class LiveDisplay extends Component$1 {
  10505. /**
  10506. * Creates an instance of this class.
  10507. *
  10508. * @param { import('./player').default } player
  10509. * The `Player` that this class should be attached to.
  10510. *
  10511. * @param {Object} [options]
  10512. * The key/value store of player options.
  10513. */
  10514. constructor(player, options) {
  10515. super(player, options);
  10516. this.updateShowing();
  10517. this.on(this.player(), 'durationchange', e => this.updateShowing(e));
  10518. }
  10519. /**
  10520. * Create the `Component`'s DOM element
  10521. *
  10522. * @return {Element}
  10523. * The element that was created.
  10524. */
  10525. createEl() {
  10526. const el = super.createEl('div', {
  10527. className: 'vjs-live-control vjs-control'
  10528. });
  10529. this.contentEl_ = createEl('div', {
  10530. className: 'vjs-live-display'
  10531. }, {
  10532. 'aria-live': 'off'
  10533. });
  10534. this.contentEl_.appendChild(createEl('span', {
  10535. className: 'vjs-control-text',
  10536. textContent: `${this.localize('Stream Type')}\u00a0`
  10537. }));
  10538. this.contentEl_.appendChild(document__default["default"].createTextNode(this.localize('LIVE')));
  10539. el.appendChild(this.contentEl_);
  10540. return el;
  10541. }
  10542. dispose() {
  10543. this.contentEl_ = null;
  10544. super.dispose();
  10545. }
  10546. /**
  10547. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  10548. * it accordingly
  10549. *
  10550. * @param {Event} [event]
  10551. * The {@link Player#durationchange} event that caused this function to run.
  10552. *
  10553. * @listens Player#durationchange
  10554. */
  10555. updateShowing(event) {
  10556. if (this.player().duration() === Infinity) {
  10557. this.show();
  10558. } else {
  10559. this.hide();
  10560. }
  10561. }
  10562. }
  10563. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  10564. /**
  10565. * @file seek-to-live.js
  10566. */
  10567. /**
  10568. * Displays the live indicator when duration is Infinity.
  10569. *
  10570. * @extends Component
  10571. */
  10572. class SeekToLive extends Button {
  10573. /**
  10574. * Creates an instance of this class.
  10575. *
  10576. * @param { import('./player').default } player
  10577. * The `Player` that this class should be attached to.
  10578. *
  10579. * @param {Object} [options]
  10580. * The key/value store of player options.
  10581. */
  10582. constructor(player, options) {
  10583. super(player, options);
  10584. this.updateLiveEdgeStatus();
  10585. if (this.player_.liveTracker) {
  10586. this.updateLiveEdgeStatusHandler_ = e => this.updateLiveEdgeStatus(e);
  10587. this.on(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10588. }
  10589. }
  10590. /**
  10591. * Create the `Component`'s DOM element
  10592. *
  10593. * @return {Element}
  10594. * The element that was created.
  10595. */
  10596. createEl() {
  10597. const el = super.createEl('button', {
  10598. className: 'vjs-seek-to-live-control vjs-control'
  10599. });
  10600. this.textEl_ = createEl('span', {
  10601. className: 'vjs-seek-to-live-text',
  10602. textContent: this.localize('LIVE')
  10603. }, {
  10604. 'aria-hidden': 'true'
  10605. });
  10606. el.appendChild(this.textEl_);
  10607. return el;
  10608. }
  10609. /**
  10610. * Update the state of this button if we are at the live edge
  10611. * or not
  10612. */
  10613. updateLiveEdgeStatus() {
  10614. // default to live edge
  10615. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  10616. this.setAttribute('aria-disabled', true);
  10617. this.addClass('vjs-at-live-edge');
  10618. this.controlText('Seek to live, currently playing live');
  10619. } else {
  10620. this.setAttribute('aria-disabled', false);
  10621. this.removeClass('vjs-at-live-edge');
  10622. this.controlText('Seek to live, currently behind live');
  10623. }
  10624. }
  10625. /**
  10626. * On click bring us as near to the live point as possible.
  10627. * This requires that we wait for the next `live-seekable-change`
  10628. * event which will happen every segment length seconds.
  10629. */
  10630. handleClick() {
  10631. this.player_.liveTracker.seekToLiveEdge();
  10632. }
  10633. /**
  10634. * Dispose of the element and stop tracking
  10635. */
  10636. dispose() {
  10637. if (this.player_.liveTracker) {
  10638. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10639. }
  10640. this.textEl_ = null;
  10641. super.dispose();
  10642. }
  10643. }
  10644. /**
  10645. * The text that should display over the `SeekToLive`s control. Added for localization.
  10646. *
  10647. * @type {string}
  10648. * @protected
  10649. */
  10650. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  10651. Component$1.registerComponent('SeekToLive', SeekToLive);
  10652. /**
  10653. * @file num.js
  10654. * @module num
  10655. */
  10656. /**
  10657. * Keep a number between a min and a max value
  10658. *
  10659. * @param {number} number
  10660. * The number to clamp
  10661. *
  10662. * @param {number} min
  10663. * The minimum value
  10664. * @param {number} max
  10665. * The maximum value
  10666. *
  10667. * @return {number}
  10668. * the clamped number
  10669. */
  10670. function clamp(number, min, max) {
  10671. number = Number(number);
  10672. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  10673. }
  10674. var Num = /*#__PURE__*/Object.freeze({
  10675. __proto__: null,
  10676. clamp: clamp
  10677. });
  10678. /**
  10679. * @file slider.js
  10680. */
  10681. /**
  10682. * The base functionality for a slider. Can be vertical or horizontal.
  10683. * For instance the volume bar or the seek bar on a video is a slider.
  10684. *
  10685. * @extends Component
  10686. */
  10687. class Slider extends Component$1 {
  10688. /**
  10689. * Create an instance of this class
  10690. *
  10691. * @param { import('../player').default } player
  10692. * The `Player` that this class should be attached to.
  10693. *
  10694. * @param {Object} [options]
  10695. * The key/value store of player options.
  10696. */
  10697. constructor(player, options) {
  10698. super(player, options);
  10699. this.handleMouseDown_ = e => this.handleMouseDown(e);
  10700. this.handleMouseUp_ = e => this.handleMouseUp(e);
  10701. this.handleKeyDown_ = e => this.handleKeyDown(e);
  10702. this.handleClick_ = e => this.handleClick(e);
  10703. this.handleMouseMove_ = e => this.handleMouseMove(e);
  10704. this.update_ = e => this.update(e);
  10705. // Set property names to bar to match with the child Slider class is looking for
  10706. this.bar = this.getChild(this.options_.barName);
  10707. // Set a horizontal or vertical class on the slider depending on the slider type
  10708. this.vertical(!!this.options_.vertical);
  10709. this.enable();
  10710. }
  10711. /**
  10712. * Are controls are currently enabled for this slider or not.
  10713. *
  10714. * @return {boolean}
  10715. * true if controls are enabled, false otherwise
  10716. */
  10717. enabled() {
  10718. return this.enabled_;
  10719. }
  10720. /**
  10721. * Enable controls for this slider if they are disabled
  10722. */
  10723. enable() {
  10724. if (this.enabled()) {
  10725. return;
  10726. }
  10727. this.on('mousedown', this.handleMouseDown_);
  10728. this.on('touchstart', this.handleMouseDown_);
  10729. this.on('keydown', this.handleKeyDown_);
  10730. this.on('click', this.handleClick_);
  10731. // TODO: deprecated, controlsvisible does not seem to be fired
  10732. this.on(this.player_, 'controlsvisible', this.update);
  10733. if (this.playerEvent) {
  10734. this.on(this.player_, this.playerEvent, this.update);
  10735. }
  10736. this.removeClass('disabled');
  10737. this.setAttribute('tabindex', 0);
  10738. this.enabled_ = true;
  10739. }
  10740. /**
  10741. * Disable controls for this slider if they are enabled
  10742. */
  10743. disable() {
  10744. if (!this.enabled()) {
  10745. return;
  10746. }
  10747. const doc = this.bar.el_.ownerDocument;
  10748. this.off('mousedown', this.handleMouseDown_);
  10749. this.off('touchstart', this.handleMouseDown_);
  10750. this.off('keydown', this.handleKeyDown_);
  10751. this.off('click', this.handleClick_);
  10752. this.off(this.player_, 'controlsvisible', this.update_);
  10753. this.off(doc, 'mousemove', this.handleMouseMove_);
  10754. this.off(doc, 'mouseup', this.handleMouseUp_);
  10755. this.off(doc, 'touchmove', this.handleMouseMove_);
  10756. this.off(doc, 'touchend', this.handleMouseUp_);
  10757. this.removeAttribute('tabindex');
  10758. this.addClass('disabled');
  10759. if (this.playerEvent) {
  10760. this.off(this.player_, this.playerEvent, this.update);
  10761. }
  10762. this.enabled_ = false;
  10763. }
  10764. /**
  10765. * Create the `Slider`s DOM element.
  10766. *
  10767. * @param {string} type
  10768. * Type of element to create.
  10769. *
  10770. * @param {Object} [props={}]
  10771. * List of properties in Object form.
  10772. *
  10773. * @param {Object} [attributes={}]
  10774. * list of attributes in Object form.
  10775. *
  10776. * @return {Element}
  10777. * The element that gets created.
  10778. */
  10779. createEl(type, props = {}, attributes = {}) {
  10780. // Add the slider element class to all sub classes
  10781. props.className = props.className + ' vjs-slider';
  10782. props = Object.assign({
  10783. tabIndex: 0
  10784. }, props);
  10785. attributes = Object.assign({
  10786. 'role': 'slider',
  10787. 'aria-valuenow': 0,
  10788. 'aria-valuemin': 0,
  10789. 'aria-valuemax': 100
  10790. }, attributes);
  10791. return super.createEl(type, props, attributes);
  10792. }
  10793. /**
  10794. * Handle `mousedown` or `touchstart` events on the `Slider`.
  10795. *
  10796. * @param {MouseEvent} event
  10797. * `mousedown` or `touchstart` event that triggered this function
  10798. *
  10799. * @listens mousedown
  10800. * @listens touchstart
  10801. * @fires Slider#slideractive
  10802. */
  10803. handleMouseDown(event) {
  10804. const doc = this.bar.el_.ownerDocument;
  10805. if (event.type === 'mousedown') {
  10806. event.preventDefault();
  10807. }
  10808. // Do not call preventDefault() on touchstart in Chrome
  10809. // to avoid console warnings. Use a 'touch-action: none' style
  10810. // instead to prevent unintended scrolling.
  10811. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  10812. if (event.type === 'touchstart' && !IS_CHROME) {
  10813. event.preventDefault();
  10814. }
  10815. blockTextSelection();
  10816. this.addClass('vjs-sliding');
  10817. /**
  10818. * Triggered when the slider is in an active state
  10819. *
  10820. * @event Slider#slideractive
  10821. * @type {MouseEvent}
  10822. */
  10823. this.trigger('slideractive');
  10824. this.on(doc, 'mousemove', this.handleMouseMove_);
  10825. this.on(doc, 'mouseup', this.handleMouseUp_);
  10826. this.on(doc, 'touchmove', this.handleMouseMove_);
  10827. this.on(doc, 'touchend', this.handleMouseUp_);
  10828. this.handleMouseMove(event, true);
  10829. }
  10830. /**
  10831. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  10832. * The `mousemove` and `touchmove` events will only only trigger this function during
  10833. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  10834. * {@link Slider#handleMouseUp}.
  10835. *
  10836. * @param {MouseEvent} event
  10837. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  10838. * this function
  10839. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false.
  10840. *
  10841. * @listens mousemove
  10842. * @listens touchmove
  10843. */
  10844. handleMouseMove(event) {}
  10845. /**
  10846. * Handle `mouseup` or `touchend` events on the `Slider`.
  10847. *
  10848. * @param {MouseEvent} event
  10849. * `mouseup` or `touchend` event that triggered this function.
  10850. *
  10851. * @listens touchend
  10852. * @listens mouseup
  10853. * @fires Slider#sliderinactive
  10854. */
  10855. handleMouseUp(event) {
  10856. const doc = this.bar.el_.ownerDocument;
  10857. unblockTextSelection();
  10858. this.removeClass('vjs-sliding');
  10859. /**
  10860. * Triggered when the slider is no longer in an active state.
  10861. *
  10862. * @event Slider#sliderinactive
  10863. * @type {Event}
  10864. */
  10865. this.trigger('sliderinactive');
  10866. this.off(doc, 'mousemove', this.handleMouseMove_);
  10867. this.off(doc, 'mouseup', this.handleMouseUp_);
  10868. this.off(doc, 'touchmove', this.handleMouseMove_);
  10869. this.off(doc, 'touchend', this.handleMouseUp_);
  10870. this.update();
  10871. }
  10872. /**
  10873. * Update the progress bar of the `Slider`.
  10874. *
  10875. * @return {number}
  10876. * The percentage of progress the progress bar represents as a
  10877. * number from 0 to 1.
  10878. */
  10879. update() {
  10880. // In VolumeBar init we have a setTimeout for update that pops and update
  10881. // to the end of the execution stack. The player is destroyed before then
  10882. // update will cause an error
  10883. // If there's no bar...
  10884. if (!this.el_ || !this.bar) {
  10885. return;
  10886. }
  10887. // clamp progress between 0 and 1
  10888. // and only round to four decimal places, as we round to two below
  10889. const progress = this.getProgress();
  10890. if (progress === this.progress_) {
  10891. return progress;
  10892. }
  10893. this.progress_ = progress;
  10894. this.requestNamedAnimationFrame('Slider#update', () => {
  10895. // Set the new bar width or height
  10896. const sizeKey = this.vertical() ? 'height' : 'width';
  10897. // Convert to a percentage for css value
  10898. this.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  10899. });
  10900. return progress;
  10901. }
  10902. /**
  10903. * Get the percentage of the bar that should be filled
  10904. * but clamped and rounded.
  10905. *
  10906. * @return {number}
  10907. * percentage filled that the slider is
  10908. */
  10909. getProgress() {
  10910. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  10911. }
  10912. /**
  10913. * Calculate distance for slider
  10914. *
  10915. * @param {Event} event
  10916. * The event that caused this function to run.
  10917. *
  10918. * @return {number}
  10919. * The current position of the Slider.
  10920. * - position.x for vertical `Slider`s
  10921. * - position.y for horizontal `Slider`s
  10922. */
  10923. calculateDistance(event) {
  10924. const position = getPointerPosition(this.el_, event);
  10925. if (this.vertical()) {
  10926. return position.y;
  10927. }
  10928. return position.x;
  10929. }
  10930. /**
  10931. * Handle a `keydown` event on the `Slider`. Watches for left, right, up, and down
  10932. * arrow keys. This function will only be called when the slider has focus. See
  10933. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  10934. *
  10935. * @param {KeyboardEvent} event
  10936. * the `keydown` event that caused this function to run.
  10937. *
  10938. * @listens keydown
  10939. */
  10940. handleKeyDown(event) {
  10941. // Left and Down Arrows
  10942. if (keycode__default["default"].isEventKey(event, 'Left') || keycode__default["default"].isEventKey(event, 'Down')) {
  10943. event.preventDefault();
  10944. event.stopPropagation();
  10945. this.stepBack();
  10946. // Up and Right Arrows
  10947. } else if (keycode__default["default"].isEventKey(event, 'Right') || keycode__default["default"].isEventKey(event, 'Up')) {
  10948. event.preventDefault();
  10949. event.stopPropagation();
  10950. this.stepForward();
  10951. } else {
  10952. // Pass keydown handling up for unsupported keys
  10953. super.handleKeyDown(event);
  10954. }
  10955. }
  10956. /**
  10957. * Listener for click events on slider, used to prevent clicks
  10958. * from bubbling up to parent elements like button menus.
  10959. *
  10960. * @param {Object} event
  10961. * Event that caused this object to run
  10962. */
  10963. handleClick(event) {
  10964. event.stopPropagation();
  10965. event.preventDefault();
  10966. }
  10967. /**
  10968. * Get/set if slider is horizontal for vertical
  10969. *
  10970. * @param {boolean} [bool]
  10971. * - true if slider is vertical,
  10972. * - false is horizontal
  10973. *
  10974. * @return {boolean}
  10975. * - true if slider is vertical, and getting
  10976. * - false if the slider is horizontal, and getting
  10977. */
  10978. vertical(bool) {
  10979. if (bool === undefined) {
  10980. return this.vertical_ || false;
  10981. }
  10982. this.vertical_ = !!bool;
  10983. if (this.vertical_) {
  10984. this.addClass('vjs-slider-vertical');
  10985. } else {
  10986. this.addClass('vjs-slider-horizontal');
  10987. }
  10988. }
  10989. }
  10990. Component$1.registerComponent('Slider', Slider);
  10991. /**
  10992. * @file load-progress-bar.js
  10993. */
  10994. // get the percent width of a time compared to the total end
  10995. const percentify = (time, end) => clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  10996. /**
  10997. * Shows loading progress
  10998. *
  10999. * @extends Component
  11000. */
  11001. class LoadProgressBar extends Component$1 {
  11002. /**
  11003. * Creates an instance of this class.
  11004. *
  11005. * @param { import('../../player').default } player
  11006. * The `Player` that this class should be attached to.
  11007. *
  11008. * @param {Object} [options]
  11009. * The key/value store of player options.
  11010. */
  11011. constructor(player, options) {
  11012. super(player, options);
  11013. this.partEls_ = [];
  11014. this.on(player, 'progress', e => this.update(e));
  11015. }
  11016. /**
  11017. * Create the `Component`'s DOM element
  11018. *
  11019. * @return {Element}
  11020. * The element that was created.
  11021. */
  11022. createEl() {
  11023. const el = super.createEl('div', {
  11024. className: 'vjs-load-progress'
  11025. });
  11026. const wrapper = createEl('span', {
  11027. className: 'vjs-control-text'
  11028. });
  11029. const loadedText = createEl('span', {
  11030. textContent: this.localize('Loaded')
  11031. });
  11032. const separator = document__default["default"].createTextNode(': ');
  11033. this.percentageEl_ = createEl('span', {
  11034. className: 'vjs-control-text-loaded-percentage',
  11035. textContent: '0%'
  11036. });
  11037. el.appendChild(wrapper);
  11038. wrapper.appendChild(loadedText);
  11039. wrapper.appendChild(separator);
  11040. wrapper.appendChild(this.percentageEl_);
  11041. return el;
  11042. }
  11043. dispose() {
  11044. this.partEls_ = null;
  11045. this.percentageEl_ = null;
  11046. super.dispose();
  11047. }
  11048. /**
  11049. * Update progress bar
  11050. *
  11051. * @param {Event} [event]
  11052. * The `progress` event that caused this function to run.
  11053. *
  11054. * @listens Player#progress
  11055. */
  11056. update(event) {
  11057. this.requestNamedAnimationFrame('LoadProgressBar#update', () => {
  11058. const liveTracker = this.player_.liveTracker;
  11059. const buffered = this.player_.buffered();
  11060. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  11061. const bufferedEnd = this.player_.bufferedEnd();
  11062. const children = this.partEls_;
  11063. const percent = percentify(bufferedEnd, duration);
  11064. if (this.percent_ !== percent) {
  11065. // update the width of the progress bar
  11066. this.el_.style.width = percent;
  11067. // update the control-text
  11068. textContent(this.percentageEl_, percent);
  11069. this.percent_ = percent;
  11070. }
  11071. // add child elements to represent the individual buffered time ranges
  11072. for (let i = 0; i < buffered.length; i++) {
  11073. const start = buffered.start(i);
  11074. const end = buffered.end(i);
  11075. let part = children[i];
  11076. if (!part) {
  11077. part = this.el_.appendChild(createEl());
  11078. children[i] = part;
  11079. }
  11080. // only update if changed
  11081. if (part.dataset.start === start && part.dataset.end === end) {
  11082. continue;
  11083. }
  11084. part.dataset.start = start;
  11085. part.dataset.end = end;
  11086. // set the percent based on the width of the progress bar (bufferedEnd)
  11087. part.style.left = percentify(start, bufferedEnd);
  11088. part.style.width = percentify(end - start, bufferedEnd);
  11089. }
  11090. // remove unused buffered range elements
  11091. for (let i = children.length; i > buffered.length; i--) {
  11092. this.el_.removeChild(children[i - 1]);
  11093. }
  11094. children.length = buffered.length;
  11095. });
  11096. }
  11097. }
  11098. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  11099. /**
  11100. * @file time-tooltip.js
  11101. */
  11102. /**
  11103. * Time tooltips display a time above the progress bar.
  11104. *
  11105. * @extends Component
  11106. */
  11107. class TimeTooltip extends Component$1 {
  11108. /**
  11109. * Creates an instance of this class.
  11110. *
  11111. * @param { import('../../player').default } player
  11112. * The {@link Player} that this class should be attached to.
  11113. *
  11114. * @param {Object} [options]
  11115. * The key/value store of player options.
  11116. */
  11117. constructor(player, options) {
  11118. super(player, options);
  11119. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11120. }
  11121. /**
  11122. * Create the time tooltip DOM element
  11123. *
  11124. * @return {Element}
  11125. * The element that was created.
  11126. */
  11127. createEl() {
  11128. return super.createEl('div', {
  11129. className: 'vjs-time-tooltip'
  11130. }, {
  11131. 'aria-hidden': 'true'
  11132. });
  11133. }
  11134. /**
  11135. * Updates the position of the time tooltip relative to the `SeekBar`.
  11136. *
  11137. * @param {Object} seekBarRect
  11138. * The `ClientRect` for the {@link SeekBar} element.
  11139. *
  11140. * @param {number} seekBarPoint
  11141. * A number from 0 to 1, representing a horizontal reference point
  11142. * from the left edge of the {@link SeekBar}
  11143. */
  11144. update(seekBarRect, seekBarPoint, content) {
  11145. const tooltipRect = findPosition(this.el_);
  11146. const playerRect = getBoundingClientRect(this.player_.el());
  11147. const seekBarPointPx = seekBarRect.width * seekBarPoint;
  11148. // do nothing if either rect isn't available
  11149. // for example, if the player isn't in the DOM for testing
  11150. if (!playerRect || !tooltipRect) {
  11151. return;
  11152. }
  11153. // This is the space left of the `seekBarPoint` available within the bounds
  11154. // of the player. We calculate any gap between the left edge of the player
  11155. // and the left edge of the `SeekBar` and add the number of pixels in the
  11156. // `SeekBar` before hitting the `seekBarPoint`
  11157. const spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx;
  11158. // This is the space right of the `seekBarPoint` available within the bounds
  11159. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11160. // to the right edge of the `SeekBar` and add to that any gap between the
  11161. // right edge of the `SeekBar` and the player.
  11162. const spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right);
  11163. // This is the number of pixels by which the tooltip will need to be pulled
  11164. // further to the right to center it over the `seekBarPoint`.
  11165. let pullTooltipBy = tooltipRect.width / 2;
  11166. // Adjust the `pullTooltipBy` distance to the left or right depending on
  11167. // the results of the space calculations above.
  11168. if (spaceLeftOfPoint < pullTooltipBy) {
  11169. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11170. } else if (spaceRightOfPoint < pullTooltipBy) {
  11171. pullTooltipBy = spaceRightOfPoint;
  11172. }
  11173. // Due to the imprecision of decimal/ratio based calculations and varying
  11174. // rounding behaviors, there are cases where the spacing adjustment is off
  11175. // by a pixel or two. This adds insurance to these calculations.
  11176. if (pullTooltipBy < 0) {
  11177. pullTooltipBy = 0;
  11178. } else if (pullTooltipBy > tooltipRect.width) {
  11179. pullTooltipBy = tooltipRect.width;
  11180. }
  11181. // prevent small width fluctuations within 0.4px from
  11182. // changing the value below.
  11183. // This really helps for live to prevent the play
  11184. // progress time tooltip from jittering
  11185. pullTooltipBy = Math.round(pullTooltipBy);
  11186. this.el_.style.right = `-${pullTooltipBy}px`;
  11187. this.write(content);
  11188. }
  11189. /**
  11190. * Write the time to the tooltip DOM element.
  11191. *
  11192. * @param {string} content
  11193. * The formatted time for the tooltip.
  11194. */
  11195. write(content) {
  11196. textContent(this.el_, content);
  11197. }
  11198. /**
  11199. * Updates the position of the time tooltip relative to the `SeekBar`.
  11200. *
  11201. * @param {Object} seekBarRect
  11202. * The `ClientRect` for the {@link SeekBar} element.
  11203. *
  11204. * @param {number} seekBarPoint
  11205. * A number from 0 to 1, representing a horizontal reference point
  11206. * from the left edge of the {@link SeekBar}
  11207. *
  11208. * @param {number} time
  11209. * The time to update the tooltip to, not used during live playback
  11210. *
  11211. * @param {Function} cb
  11212. * A function that will be called during the request animation frame
  11213. * for tooltips that need to do additional animations from the default
  11214. */
  11215. updateTime(seekBarRect, seekBarPoint, time, cb) {
  11216. this.requestNamedAnimationFrame('TimeTooltip#updateTime', () => {
  11217. let content;
  11218. const duration = this.player_.duration();
  11219. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11220. const liveWindow = this.player_.liveTracker.liveWindow();
  11221. const secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11222. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11223. } else {
  11224. content = formatTime(time, duration);
  11225. }
  11226. this.update(seekBarRect, seekBarPoint, content);
  11227. if (cb) {
  11228. cb();
  11229. }
  11230. });
  11231. }
  11232. }
  11233. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  11234. /**
  11235. * @file play-progress-bar.js
  11236. */
  11237. /**
  11238. * Used by {@link SeekBar} to display media playback progress as part of the
  11239. * {@link ProgressControl}.
  11240. *
  11241. * @extends Component
  11242. */
  11243. class PlayProgressBar extends Component$1 {
  11244. /**
  11245. * Creates an instance of this class.
  11246. *
  11247. * @param { import('../../player').default } player
  11248. * The {@link Player} that this class should be attached to.
  11249. *
  11250. * @param {Object} [options]
  11251. * The key/value store of player options.
  11252. */
  11253. constructor(player, options) {
  11254. super(player, options);
  11255. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11256. }
  11257. /**
  11258. * Create the the DOM element for this class.
  11259. *
  11260. * @return {Element}
  11261. * The element that was created.
  11262. */
  11263. createEl() {
  11264. return super.createEl('div', {
  11265. className: 'vjs-play-progress vjs-slider-bar'
  11266. }, {
  11267. 'aria-hidden': 'true'
  11268. });
  11269. }
  11270. /**
  11271. * Enqueues updates to its own DOM as well as the DOM of its
  11272. * {@link TimeTooltip} child.
  11273. *
  11274. * @param {Object} seekBarRect
  11275. * The `ClientRect` for the {@link SeekBar} element.
  11276. *
  11277. * @param {number} seekBarPoint
  11278. * A number from 0 to 1, representing a horizontal reference point
  11279. * from the left edge of the {@link SeekBar}
  11280. */
  11281. update(seekBarRect, seekBarPoint) {
  11282. const timeTooltip = this.getChild('timeTooltip');
  11283. if (!timeTooltip) {
  11284. return;
  11285. }
  11286. const time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11287. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  11288. }
  11289. }
  11290. /**
  11291. * Default options for {@link PlayProgressBar}.
  11292. *
  11293. * @type {Object}
  11294. * @private
  11295. */
  11296. PlayProgressBar.prototype.options_ = {
  11297. children: []
  11298. };
  11299. // Time tooltips should not be added to a player on mobile devices
  11300. if (!IS_IOS && !IS_ANDROID) {
  11301. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  11302. }
  11303. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  11304. /**
  11305. * @file mouse-time-display.js
  11306. */
  11307. /**
  11308. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  11309. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  11310. * indicating the time which is represented by a given point in the
  11311. * {@link ProgressControl}.
  11312. *
  11313. * @extends Component
  11314. */
  11315. class MouseTimeDisplay extends Component$1 {
  11316. /**
  11317. * Creates an instance of this class.
  11318. *
  11319. * @param { import('../../player').default } player
  11320. * The {@link Player} that this class should be attached to.
  11321. *
  11322. * @param {Object} [options]
  11323. * The key/value store of player options.
  11324. */
  11325. constructor(player, options) {
  11326. super(player, options);
  11327. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  11328. }
  11329. /**
  11330. * Create the DOM element for this class.
  11331. *
  11332. * @return {Element}
  11333. * The element that was created.
  11334. */
  11335. createEl() {
  11336. return super.createEl('div', {
  11337. className: 'vjs-mouse-display'
  11338. });
  11339. }
  11340. /**
  11341. * Enqueues updates to its own DOM as well as the DOM of its
  11342. * {@link TimeTooltip} child.
  11343. *
  11344. * @param {Object} seekBarRect
  11345. * The `ClientRect` for the {@link SeekBar} element.
  11346. *
  11347. * @param {number} seekBarPoint
  11348. * A number from 0 to 1, representing a horizontal reference point
  11349. * from the left edge of the {@link SeekBar}
  11350. */
  11351. update(seekBarRect, seekBarPoint) {
  11352. const time = seekBarPoint * this.player_.duration();
  11353. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, () => {
  11354. this.el_.style.left = `${seekBarRect.width * seekBarPoint}px`;
  11355. });
  11356. }
  11357. }
  11358. /**
  11359. * Default options for `MouseTimeDisplay`
  11360. *
  11361. * @type {Object}
  11362. * @private
  11363. */
  11364. MouseTimeDisplay.prototype.options_ = {
  11365. children: ['timeTooltip']
  11366. };
  11367. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  11368. /**
  11369. * @file seek-bar.js
  11370. */
  11371. // The number of seconds the `step*` functions move the timeline.
  11372. const STEP_SECONDS = 5;
  11373. // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  11374. const PAGE_KEY_MULTIPLIER = 12;
  11375. /**
  11376. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  11377. * as its `bar`.
  11378. *
  11379. * @extends Slider
  11380. */
  11381. class SeekBar extends Slider {
  11382. /**
  11383. * Creates an instance of this class.
  11384. *
  11385. * @param { import('../../player').default } player
  11386. * The `Player` that this class should be attached to.
  11387. *
  11388. * @param {Object} [options]
  11389. * The key/value store of player options.
  11390. */
  11391. constructor(player, options) {
  11392. super(player, options);
  11393. this.setEventHandlers_();
  11394. }
  11395. /**
  11396. * Sets the event handlers
  11397. *
  11398. * @private
  11399. */
  11400. setEventHandlers_() {
  11401. this.update_ = bind_(this, this.update);
  11402. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  11403. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11404. if (this.player_.liveTracker) {
  11405. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  11406. }
  11407. // when playing, let's ensure we smoothly update the play progress bar
  11408. // via an interval
  11409. this.updateInterval = null;
  11410. this.enableIntervalHandler_ = e => this.enableInterval_(e);
  11411. this.disableIntervalHandler_ = e => this.disableInterval_(e);
  11412. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  11413. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11414. // we don't need to update the play progress if the document is hidden,
  11415. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11416. if ('hidden' in document__default["default"] && 'visibilityState' in document__default["default"]) {
  11417. this.on(document__default["default"], 'visibilitychange', this.toggleVisibility_);
  11418. }
  11419. }
  11420. toggleVisibility_(e) {
  11421. if (document__default["default"].visibilityState === 'hidden') {
  11422. this.cancelNamedAnimationFrame('SeekBar#update');
  11423. this.cancelNamedAnimationFrame('Slider#update');
  11424. this.disableInterval_(e);
  11425. } else {
  11426. if (!this.player_.ended() && !this.player_.paused()) {
  11427. this.enableInterval_();
  11428. }
  11429. // we just switched back to the page and someone may be looking, so, update ASAP
  11430. this.update();
  11431. }
  11432. }
  11433. enableInterval_() {
  11434. if (this.updateInterval) {
  11435. return;
  11436. }
  11437. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  11438. }
  11439. disableInterval_(e) {
  11440. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  11441. return;
  11442. }
  11443. if (!this.updateInterval) {
  11444. return;
  11445. }
  11446. this.clearInterval(this.updateInterval);
  11447. this.updateInterval = null;
  11448. }
  11449. /**
  11450. * Create the `Component`'s DOM element
  11451. *
  11452. * @return {Element}
  11453. * The element that was created.
  11454. */
  11455. createEl() {
  11456. return super.createEl('div', {
  11457. className: 'vjs-progress-holder'
  11458. }, {
  11459. 'aria-label': this.localize('Progress Bar')
  11460. });
  11461. }
  11462. /**
  11463. * This function updates the play progress bar and accessibility
  11464. * attributes to whatever is passed in.
  11465. *
  11466. * @param {Event} [event]
  11467. * The `timeupdate` or `ended` event that caused this to run.
  11468. *
  11469. * @listens Player#timeupdate
  11470. *
  11471. * @return {number}
  11472. * The current percent at a number from 0-1
  11473. */
  11474. update(event) {
  11475. // ignore updates while the tab is hidden
  11476. if (document__default["default"].visibilityState === 'hidden') {
  11477. return;
  11478. }
  11479. const percent = super.update();
  11480. this.requestNamedAnimationFrame('SeekBar#update', () => {
  11481. const currentTime = this.player_.ended() ? this.player_.duration() : this.getCurrentTime_();
  11482. const liveTracker = this.player_.liveTracker;
  11483. let duration = this.player_.duration();
  11484. if (liveTracker && liveTracker.isLive()) {
  11485. duration = this.player_.liveTracker.liveCurrentTime();
  11486. }
  11487. if (this.percent_ !== percent) {
  11488. // machine readable value of progress bar (percentage complete)
  11489. this.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  11490. this.percent_ = percent;
  11491. }
  11492. if (this.currentTime_ !== currentTime || this.duration_ !== duration) {
  11493. // human readable value of progress bar (time complete)
  11494. this.el_.setAttribute('aria-valuetext', this.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  11495. this.currentTime_ = currentTime;
  11496. this.duration_ = duration;
  11497. }
  11498. // update the progress bar time tooltip with the current time
  11499. if (this.bar) {
  11500. this.bar.update(getBoundingClientRect(this.el()), this.getProgress());
  11501. }
  11502. });
  11503. return percent;
  11504. }
  11505. /**
  11506. * Prevent liveThreshold from causing seeks to seem like they
  11507. * are not happening from a user perspective.
  11508. *
  11509. * @param {number} ct
  11510. * current time to seek to
  11511. */
  11512. userSeek_(ct) {
  11513. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11514. this.player_.liveTracker.nextSeekedFromUser();
  11515. }
  11516. this.player_.currentTime(ct);
  11517. }
  11518. /**
  11519. * Get the value of current time but allows for smooth scrubbing,
  11520. * when player can't keep up.
  11521. *
  11522. * @return {number}
  11523. * The current time value to display
  11524. *
  11525. * @private
  11526. */
  11527. getCurrentTime_() {
  11528. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11529. }
  11530. /**
  11531. * Get the percentage of media played so far.
  11532. *
  11533. * @return {number}
  11534. * The percentage of media played so far (0 to 1).
  11535. */
  11536. getPercent() {
  11537. const currentTime = this.getCurrentTime_();
  11538. let percent;
  11539. const liveTracker = this.player_.liveTracker;
  11540. if (liveTracker && liveTracker.isLive()) {
  11541. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow();
  11542. // prevent the percent from changing at the live edge
  11543. if (liveTracker.atLiveEdge()) {
  11544. percent = 1;
  11545. }
  11546. } else {
  11547. percent = currentTime / this.player_.duration();
  11548. }
  11549. return percent;
  11550. }
  11551. /**
  11552. * Handle mouse down on seek bar
  11553. *
  11554. * @param {MouseEvent} event
  11555. * The `mousedown` event that caused this to run.
  11556. *
  11557. * @listens mousedown
  11558. */
  11559. handleMouseDown(event) {
  11560. if (!isSingleLeftClick(event)) {
  11561. return;
  11562. }
  11563. // Stop event propagation to prevent double fire in progress-control.js
  11564. event.stopPropagation();
  11565. this.videoWasPlaying = !this.player_.paused();
  11566. this.player_.pause();
  11567. super.handleMouseDown(event);
  11568. }
  11569. /**
  11570. * Handle mouse move on seek bar
  11571. *
  11572. * @param {MouseEvent} event
  11573. * The `mousemove` event that caused this to run.
  11574. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false
  11575. *
  11576. * @listens mousemove
  11577. */
  11578. handleMouseMove(event, mouseDown = false) {
  11579. if (!isSingleLeftClick(event)) {
  11580. return;
  11581. }
  11582. if (!mouseDown && !this.player_.scrubbing()) {
  11583. this.player_.scrubbing(true);
  11584. }
  11585. let newTime;
  11586. const distance = this.calculateDistance(event);
  11587. const liveTracker = this.player_.liveTracker;
  11588. if (!liveTracker || !liveTracker.isLive()) {
  11589. newTime = distance * this.player_.duration();
  11590. // Don't let video end while scrubbing.
  11591. if (newTime === this.player_.duration()) {
  11592. newTime = newTime - 0.1;
  11593. }
  11594. } else {
  11595. if (distance >= 0.99) {
  11596. liveTracker.seekToLiveEdge();
  11597. return;
  11598. }
  11599. const seekableStart = liveTracker.seekableStart();
  11600. const seekableEnd = liveTracker.liveCurrentTime();
  11601. newTime = seekableStart + distance * liveTracker.liveWindow();
  11602. // Don't let video end while scrubbing.
  11603. if (newTime >= seekableEnd) {
  11604. newTime = seekableEnd;
  11605. }
  11606. // Compensate for precision differences so that currentTime is not less
  11607. // than seekable start
  11608. if (newTime <= seekableStart) {
  11609. newTime = seekableStart + 0.1;
  11610. }
  11611. // On android seekableEnd can be Infinity sometimes,
  11612. // this will cause newTime to be Infinity, which is
  11613. // not a valid currentTime.
  11614. if (newTime === Infinity) {
  11615. return;
  11616. }
  11617. }
  11618. // Set new time (tell player to seek to new time)
  11619. this.userSeek_(newTime);
  11620. }
  11621. enable() {
  11622. super.enable();
  11623. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11624. if (!mouseTimeDisplay) {
  11625. return;
  11626. }
  11627. mouseTimeDisplay.show();
  11628. }
  11629. disable() {
  11630. super.disable();
  11631. const mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11632. if (!mouseTimeDisplay) {
  11633. return;
  11634. }
  11635. mouseTimeDisplay.hide();
  11636. }
  11637. /**
  11638. * Handle mouse up on seek bar
  11639. *
  11640. * @param {MouseEvent} event
  11641. * The `mouseup` event that caused this to run.
  11642. *
  11643. * @listens mouseup
  11644. */
  11645. handleMouseUp(event) {
  11646. super.handleMouseUp(event);
  11647. // Stop event propagation to prevent double fire in progress-control.js
  11648. if (event) {
  11649. event.stopPropagation();
  11650. }
  11651. this.player_.scrubbing(false);
  11652. /**
  11653. * Trigger timeupdate because we're done seeking and the time has changed.
  11654. * This is particularly useful for if the player is paused to time the time displays.
  11655. *
  11656. * @event Tech#timeupdate
  11657. * @type {Event}
  11658. */
  11659. this.player_.trigger({
  11660. type: 'timeupdate',
  11661. target: this,
  11662. manuallyTriggered: true
  11663. });
  11664. if (this.videoWasPlaying) {
  11665. silencePromise(this.player_.play());
  11666. } else {
  11667. // We're done seeking and the time has changed.
  11668. // If the player is paused, make sure we display the correct time on the seek bar.
  11669. this.update_();
  11670. }
  11671. }
  11672. /**
  11673. * Move more quickly fast forward for keyboard-only users
  11674. */
  11675. stepForward() {
  11676. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  11677. }
  11678. /**
  11679. * Move more quickly rewind for keyboard-only users
  11680. */
  11681. stepBack() {
  11682. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  11683. }
  11684. /**
  11685. * Toggles the playback state of the player
  11686. * This gets called when enter or space is used on the seekbar
  11687. *
  11688. * @param {KeyboardEvent} event
  11689. * The `keydown` event that caused this function to be called
  11690. *
  11691. */
  11692. handleAction(event) {
  11693. if (this.player_.paused()) {
  11694. this.player_.play();
  11695. } else {
  11696. this.player_.pause();
  11697. }
  11698. }
  11699. /**
  11700. * Called when this SeekBar has focus and a key gets pressed down.
  11701. * Supports the following keys:
  11702. *
  11703. * Space or Enter key fire a click event
  11704. * Home key moves to start of the timeline
  11705. * End key moves to end of the timeline
  11706. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  11707. * PageDown key moves back a larger step than ArrowDown
  11708. * PageUp key moves forward a large step
  11709. *
  11710. * @param {KeyboardEvent} event
  11711. * The `keydown` event that caused this function to be called.
  11712. *
  11713. * @listens keydown
  11714. */
  11715. handleKeyDown(event) {
  11716. const liveTracker = this.player_.liveTracker;
  11717. if (keycode__default["default"].isEventKey(event, 'Space') || keycode__default["default"].isEventKey(event, 'Enter')) {
  11718. event.preventDefault();
  11719. event.stopPropagation();
  11720. this.handleAction(event);
  11721. } else if (keycode__default["default"].isEventKey(event, 'Home')) {
  11722. event.preventDefault();
  11723. event.stopPropagation();
  11724. this.userSeek_(0);
  11725. } else if (keycode__default["default"].isEventKey(event, 'End')) {
  11726. event.preventDefault();
  11727. event.stopPropagation();
  11728. if (liveTracker && liveTracker.isLive()) {
  11729. this.userSeek_(liveTracker.liveCurrentTime());
  11730. } else {
  11731. this.userSeek_(this.player_.duration());
  11732. }
  11733. } else if (/^[0-9]$/.test(keycode__default["default"](event))) {
  11734. event.preventDefault();
  11735. event.stopPropagation();
  11736. const gotoFraction = (keycode__default["default"].codes[keycode__default["default"](event)] - keycode__default["default"].codes['0']) * 10.0 / 100.0;
  11737. if (liveTracker && liveTracker.isLive()) {
  11738. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  11739. } else {
  11740. this.userSeek_(this.player_.duration() * gotoFraction);
  11741. }
  11742. } else if (keycode__default["default"].isEventKey(event, 'PgDn')) {
  11743. event.preventDefault();
  11744. event.stopPropagation();
  11745. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11746. } else if (keycode__default["default"].isEventKey(event, 'PgUp')) {
  11747. event.preventDefault();
  11748. event.stopPropagation();
  11749. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  11750. } else {
  11751. // Pass keydown handling up for unsupported keys
  11752. super.handleKeyDown(event);
  11753. }
  11754. }
  11755. dispose() {
  11756. this.disableInterval_();
  11757. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11758. if (this.player_.liveTracker) {
  11759. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  11760. }
  11761. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  11762. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_);
  11763. // we don't need to update the play progress if the document is hidden,
  11764. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11765. if ('hidden' in document__default["default"] && 'visibilityState' in document__default["default"]) {
  11766. this.off(document__default["default"], 'visibilitychange', this.toggleVisibility_);
  11767. }
  11768. super.dispose();
  11769. }
  11770. }
  11771. /**
  11772. * Default options for the `SeekBar`
  11773. *
  11774. * @type {Object}
  11775. * @private
  11776. */
  11777. SeekBar.prototype.options_ = {
  11778. children: ['loadProgressBar', 'playProgressBar'],
  11779. barName: 'playProgressBar'
  11780. };
  11781. // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  11782. if (!IS_IOS && !IS_ANDROID) {
  11783. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  11784. }
  11785. Component$1.registerComponent('SeekBar', SeekBar);
  11786. /**
  11787. * @file progress-control.js
  11788. */
  11789. /**
  11790. * The Progress Control component contains the seek bar, load progress,
  11791. * and play progress.
  11792. *
  11793. * @extends Component
  11794. */
  11795. class ProgressControl extends Component$1 {
  11796. /**
  11797. * Creates an instance of this class.
  11798. *
  11799. * @param { import('../../player').default } player
  11800. * The `Player` that this class should be attached to.
  11801. *
  11802. * @param {Object} [options]
  11803. * The key/value store of player options.
  11804. */
  11805. constructor(player, options) {
  11806. super(player, options);
  11807. this.handleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  11808. this.throttledHandleMouseSeek = throttle(bind_(this, this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  11809. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  11810. this.handleMouseDownHandler_ = e => this.handleMouseDown(e);
  11811. this.enable();
  11812. }
  11813. /**
  11814. * Create the `Component`'s DOM element
  11815. *
  11816. * @return {Element}
  11817. * The element that was created.
  11818. */
  11819. createEl() {
  11820. return super.createEl('div', {
  11821. className: 'vjs-progress-control vjs-control'
  11822. });
  11823. }
  11824. /**
  11825. * When the mouse moves over the `ProgressControl`, the pointer position
  11826. * gets passed down to the `MouseTimeDisplay` component.
  11827. *
  11828. * @param {Event} event
  11829. * The `mousemove` event that caused this function to run.
  11830. *
  11831. * @listen mousemove
  11832. */
  11833. handleMouseMove(event) {
  11834. const seekBar = this.getChild('seekBar');
  11835. if (!seekBar) {
  11836. return;
  11837. }
  11838. const playProgressBar = seekBar.getChild('playProgressBar');
  11839. const mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  11840. if (!playProgressBar && !mouseTimeDisplay) {
  11841. return;
  11842. }
  11843. const seekBarEl = seekBar.el();
  11844. const seekBarRect = findPosition(seekBarEl);
  11845. let seekBarPoint = getPointerPosition(seekBarEl, event).x;
  11846. // The default skin has a gap on either side of the `SeekBar`. This means
  11847. // that it's possible to trigger this behavior outside the boundaries of
  11848. // the `SeekBar`. This ensures we stay within it at all times.
  11849. seekBarPoint = clamp(seekBarPoint, 0, 1);
  11850. if (mouseTimeDisplay) {
  11851. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  11852. }
  11853. if (playProgressBar) {
  11854. playProgressBar.update(seekBarRect, seekBar.getProgress());
  11855. }
  11856. }
  11857. /**
  11858. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  11859. *
  11860. * @method ProgressControl#throttledHandleMouseSeek
  11861. * @param {Event} event
  11862. * The `mousemove` event that caused this function to run.
  11863. *
  11864. * @listen mousemove
  11865. * @listen touchmove
  11866. */
  11867. /**
  11868. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  11869. *
  11870. * @param {Event} event
  11871. * `mousedown` or `touchstart` event that triggered this function
  11872. *
  11873. * @listens mousemove
  11874. * @listens touchmove
  11875. */
  11876. handleMouseSeek(event) {
  11877. const seekBar = this.getChild('seekBar');
  11878. if (seekBar) {
  11879. seekBar.handleMouseMove(event);
  11880. }
  11881. }
  11882. /**
  11883. * Are controls are currently enabled for this progress control.
  11884. *
  11885. * @return {boolean}
  11886. * true if controls are enabled, false otherwise
  11887. */
  11888. enabled() {
  11889. return this.enabled_;
  11890. }
  11891. /**
  11892. * Disable all controls on the progress control and its children
  11893. */
  11894. disable() {
  11895. this.children().forEach(child => child.disable && child.disable());
  11896. if (!this.enabled()) {
  11897. return;
  11898. }
  11899. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11900. this.off(this.el_, 'mousemove', this.handleMouseMove);
  11901. this.removeListenersAddedOnMousedownAndTouchstart();
  11902. this.addClass('disabled');
  11903. this.enabled_ = false;
  11904. // Restore normal playback state if controls are disabled while scrubbing
  11905. if (this.player_.scrubbing()) {
  11906. const seekBar = this.getChild('seekBar');
  11907. this.player_.scrubbing(false);
  11908. if (seekBar.videoWasPlaying) {
  11909. silencePromise(this.player_.play());
  11910. }
  11911. }
  11912. }
  11913. /**
  11914. * Enable all controls on the progress control and its children
  11915. */
  11916. enable() {
  11917. this.children().forEach(child => child.enable && child.enable());
  11918. if (this.enabled()) {
  11919. return;
  11920. }
  11921. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  11922. this.on(this.el_, 'mousemove', this.handleMouseMove);
  11923. this.removeClass('disabled');
  11924. this.enabled_ = true;
  11925. }
  11926. /**
  11927. * Cleanup listeners after the user finishes interacting with the progress controls
  11928. */
  11929. removeListenersAddedOnMousedownAndTouchstart() {
  11930. const doc = this.el_.ownerDocument;
  11931. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  11932. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  11933. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  11934. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  11935. }
  11936. /**
  11937. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  11938. *
  11939. * @param {Event} event
  11940. * `mousedown` or `touchstart` event that triggered this function
  11941. *
  11942. * @listens mousedown
  11943. * @listens touchstart
  11944. */
  11945. handleMouseDown(event) {
  11946. const doc = this.el_.ownerDocument;
  11947. const seekBar = this.getChild('seekBar');
  11948. if (seekBar) {
  11949. seekBar.handleMouseDown(event);
  11950. }
  11951. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  11952. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  11953. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  11954. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  11955. }
  11956. /**
  11957. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  11958. *
  11959. * @param {Event} event
  11960. * `mouseup` or `touchend` event that triggered this function.
  11961. *
  11962. * @listens touchend
  11963. * @listens mouseup
  11964. */
  11965. handleMouseUp(event) {
  11966. const seekBar = this.getChild('seekBar');
  11967. if (seekBar) {
  11968. seekBar.handleMouseUp(event);
  11969. }
  11970. this.removeListenersAddedOnMousedownAndTouchstart();
  11971. }
  11972. }
  11973. /**
  11974. * Default options for `ProgressControl`
  11975. *
  11976. * @type {Object}
  11977. * @private
  11978. */
  11979. ProgressControl.prototype.options_ = {
  11980. children: ['seekBar']
  11981. };
  11982. Component$1.registerComponent('ProgressControl', ProgressControl);
  11983. /**
  11984. * @file picture-in-picture-toggle.js
  11985. */
  11986. /**
  11987. * Toggle Picture-in-Picture mode
  11988. *
  11989. * @extends Button
  11990. */
  11991. class PictureInPictureToggle extends Button {
  11992. /**
  11993. * Creates an instance of this class.
  11994. *
  11995. * @param { import('./player').default } player
  11996. * The `Player` that this class should be attached to.
  11997. *
  11998. * @param {Object} [options]
  11999. * The key/value store of player options.
  12000. *
  12001. * @listens Player#enterpictureinpicture
  12002. * @listens Player#leavepictureinpicture
  12003. */
  12004. constructor(player, options) {
  12005. super(player, options);
  12006. this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], e => this.handlePictureInPictureChange(e));
  12007. this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], e => this.handlePictureInPictureEnabledChange(e));
  12008. this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], () => {
  12009. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  12010. const isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  12011. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  12012. if (player.isInPictureInPicture()) {
  12013. player.exitPictureInPicture();
  12014. }
  12015. this.hide();
  12016. } else {
  12017. this.show();
  12018. }
  12019. });
  12020. // TODO: Deactivate button on player emptied event.
  12021. this.disable();
  12022. }
  12023. /**
  12024. * Builds the default DOM `className`.
  12025. *
  12026. * @return {string}
  12027. * The DOM `className` for this object.
  12028. */
  12029. buildCSSClass() {
  12030. return `vjs-picture-in-picture-control ${super.buildCSSClass()}`;
  12031. }
  12032. /**
  12033. * Enables or disables button based on availability of a Picture-In-Picture mode.
  12034. *
  12035. * Enabled if
  12036. * - `player.options().enableDocumentPictureInPicture` is true and
  12037. * window.documentPictureInPicture is available; or
  12038. * - `player.disablePictureInPicture()` is false and
  12039. * element.requestPictureInPicture is available
  12040. */
  12041. handlePictureInPictureEnabledChange() {
  12042. if (document__default["default"].pictureInPictureEnabled && this.player_.disablePictureInPicture() === false || this.player_.options_.enableDocumentPictureInPicture && 'documentPictureInPicture' in window__default["default"]) {
  12043. this.enable();
  12044. } else {
  12045. this.disable();
  12046. }
  12047. }
  12048. /**
  12049. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12050. *
  12051. * @param {Event} [event]
  12052. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12053. * called.
  12054. *
  12055. * @listens Player#enterpictureinpicture
  12056. * @listens Player#leavepictureinpicture
  12057. */
  12058. handlePictureInPictureChange(event) {
  12059. if (this.player_.isInPictureInPicture()) {
  12060. this.controlText('Exit Picture-in-Picture');
  12061. } else {
  12062. this.controlText('Picture-in-Picture');
  12063. }
  12064. this.handlePictureInPictureEnabledChange();
  12065. }
  12066. /**
  12067. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12068. * {@link ClickableComponent} for more detailed information on what a click can be.
  12069. *
  12070. * @param {Event} [event]
  12071. * The `keydown`, `tap`, or `click` event that caused this function to be
  12072. * called.
  12073. *
  12074. * @listens tap
  12075. * @listens click
  12076. */
  12077. handleClick(event) {
  12078. if (!this.player_.isInPictureInPicture()) {
  12079. this.player_.requestPictureInPicture();
  12080. } else {
  12081. this.player_.exitPictureInPicture();
  12082. }
  12083. }
  12084. }
  12085. /**
  12086. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12087. *
  12088. * @type {string}
  12089. * @protected
  12090. */
  12091. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12092. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12093. /**
  12094. * @file fullscreen-toggle.js
  12095. */
  12096. /**
  12097. * Toggle fullscreen video
  12098. *
  12099. * @extends Button
  12100. */
  12101. class FullscreenToggle extends Button {
  12102. /**
  12103. * Creates an instance of this class.
  12104. *
  12105. * @param { import('./player').default } player
  12106. * The `Player` that this class should be attached to.
  12107. *
  12108. * @param {Object} [options]
  12109. * The key/value store of player options.
  12110. */
  12111. constructor(player, options) {
  12112. super(player, options);
  12113. this.on(player, 'fullscreenchange', e => this.handleFullscreenChange(e));
  12114. if (document__default["default"][player.fsApi_.fullscreenEnabled] === false) {
  12115. this.disable();
  12116. }
  12117. }
  12118. /**
  12119. * Builds the default DOM `className`.
  12120. *
  12121. * @return {string}
  12122. * The DOM `className` for this object.
  12123. */
  12124. buildCSSClass() {
  12125. return `vjs-fullscreen-control ${super.buildCSSClass()}`;
  12126. }
  12127. /**
  12128. * Handles fullscreenchange on the player and change control text accordingly.
  12129. *
  12130. * @param {Event} [event]
  12131. * The {@link Player#fullscreenchange} event that caused this function to be
  12132. * called.
  12133. *
  12134. * @listens Player#fullscreenchange
  12135. */
  12136. handleFullscreenChange(event) {
  12137. if (this.player_.isFullscreen()) {
  12138. this.controlText('Exit Fullscreen');
  12139. } else {
  12140. this.controlText('Fullscreen');
  12141. }
  12142. }
  12143. /**
  12144. * This gets called when an `FullscreenToggle` is "clicked". See
  12145. * {@link ClickableComponent} for more detailed information on what a click can be.
  12146. *
  12147. * @param {Event} [event]
  12148. * The `keydown`, `tap`, or `click` event that caused this function to be
  12149. * called.
  12150. *
  12151. * @listens tap
  12152. * @listens click
  12153. */
  12154. handleClick(event) {
  12155. if (!this.player_.isFullscreen()) {
  12156. this.player_.requestFullscreen();
  12157. } else {
  12158. this.player_.exitFullscreen();
  12159. }
  12160. }
  12161. }
  12162. /**
  12163. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12164. *
  12165. * @type {string}
  12166. * @protected
  12167. */
  12168. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12169. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  12170. /**
  12171. * Check if volume control is supported and if it isn't hide the
  12172. * `Component` that was passed using the `vjs-hidden` class.
  12173. *
  12174. * @param { import('../../component').default } self
  12175. * The component that should be hidden if volume is unsupported
  12176. *
  12177. * @param { import('../../player').default } player
  12178. * A reference to the player
  12179. *
  12180. * @private
  12181. */
  12182. const checkVolumeSupport = function (self, player) {
  12183. // hide volume controls when they're not supported by the current tech
  12184. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12185. self.addClass('vjs-hidden');
  12186. }
  12187. self.on(player, 'loadstart', function () {
  12188. if (!player.tech_.featuresVolumeControl) {
  12189. self.addClass('vjs-hidden');
  12190. } else {
  12191. self.removeClass('vjs-hidden');
  12192. }
  12193. });
  12194. };
  12195. /**
  12196. * @file volume-level.js
  12197. */
  12198. /**
  12199. * Shows volume level
  12200. *
  12201. * @extends Component
  12202. */
  12203. class VolumeLevel extends Component$1 {
  12204. /**
  12205. * Create the `Component`'s DOM element
  12206. *
  12207. * @return {Element}
  12208. * The element that was created.
  12209. */
  12210. createEl() {
  12211. const el = super.createEl('div', {
  12212. className: 'vjs-volume-level'
  12213. });
  12214. el.appendChild(super.createEl('span', {
  12215. className: 'vjs-control-text'
  12216. }));
  12217. return el;
  12218. }
  12219. }
  12220. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  12221. /**
  12222. * @file volume-level-tooltip.js
  12223. */
  12224. /**
  12225. * Volume level tooltips display a volume above or side by side the volume bar.
  12226. *
  12227. * @extends Component
  12228. */
  12229. class VolumeLevelTooltip extends Component$1 {
  12230. /**
  12231. * Creates an instance of this class.
  12232. *
  12233. * @param { import('../../player').default } player
  12234. * The {@link Player} that this class should be attached to.
  12235. *
  12236. * @param {Object} [options]
  12237. * The key/value store of player options.
  12238. */
  12239. constructor(player, options) {
  12240. super(player, options);
  12241. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12242. }
  12243. /**
  12244. * Create the volume tooltip DOM element
  12245. *
  12246. * @return {Element}
  12247. * The element that was created.
  12248. */
  12249. createEl() {
  12250. return super.createEl('div', {
  12251. className: 'vjs-volume-tooltip'
  12252. }, {
  12253. 'aria-hidden': 'true'
  12254. });
  12255. }
  12256. /**
  12257. * Updates the position of the tooltip relative to the `VolumeBar` and
  12258. * its content text.
  12259. *
  12260. * @param {Object} rangeBarRect
  12261. * The `ClientRect` for the {@link VolumeBar} element.
  12262. *
  12263. * @param {number} rangeBarPoint
  12264. * A number from 0 to 1, representing a horizontal/vertical reference point
  12265. * from the left edge of the {@link VolumeBar}
  12266. *
  12267. * @param {boolean} vertical
  12268. * Referees to the Volume control position
  12269. * in the control bar{@link VolumeControl}
  12270. *
  12271. */
  12272. update(rangeBarRect, rangeBarPoint, vertical, content) {
  12273. if (!vertical) {
  12274. const tooltipRect = getBoundingClientRect(this.el_);
  12275. const playerRect = getBoundingClientRect(this.player_.el());
  12276. const volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  12277. if (!playerRect || !tooltipRect) {
  12278. return;
  12279. }
  12280. const spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  12281. const spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  12282. let pullTooltipBy = tooltipRect.width / 2;
  12283. if (spaceLeftOfPoint < pullTooltipBy) {
  12284. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12285. } else if (spaceRightOfPoint < pullTooltipBy) {
  12286. pullTooltipBy = spaceRightOfPoint;
  12287. }
  12288. if (pullTooltipBy < 0) {
  12289. pullTooltipBy = 0;
  12290. } else if (pullTooltipBy > tooltipRect.width) {
  12291. pullTooltipBy = tooltipRect.width;
  12292. }
  12293. this.el_.style.right = `-${pullTooltipBy}px`;
  12294. }
  12295. this.write(`${content}%`);
  12296. }
  12297. /**
  12298. * Write the volume to the tooltip DOM element.
  12299. *
  12300. * @param {string} content
  12301. * The formatted volume for the tooltip.
  12302. */
  12303. write(content) {
  12304. textContent(this.el_, content);
  12305. }
  12306. /**
  12307. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  12308. *
  12309. * @param {Object} rangeBarRect
  12310. * The `ClientRect` for the {@link VolumeBar} element.
  12311. *
  12312. * @param {number} rangeBarPoint
  12313. * A number from 0 to 1, representing a horizontal/vertical reference point
  12314. * from the left edge of the {@link VolumeBar}
  12315. *
  12316. * @param {boolean} vertical
  12317. * Referees to the Volume control position
  12318. * in the control bar{@link VolumeControl}
  12319. *
  12320. * @param {number} volume
  12321. * The volume level to update the tooltip to
  12322. *
  12323. * @param {Function} cb
  12324. * A function that will be called during the request animation frame
  12325. * for tooltips that need to do additional animations from the default
  12326. */
  12327. updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  12328. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', () => {
  12329. this.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  12330. if (cb) {
  12331. cb();
  12332. }
  12333. });
  12334. }
  12335. }
  12336. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  12337. /**
  12338. * @file mouse-volume-level-display.js
  12339. */
  12340. /**
  12341. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  12342. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  12343. * indicating the volume level which is represented by a given point in the
  12344. * {@link VolumeBar}.
  12345. *
  12346. * @extends Component
  12347. */
  12348. class MouseVolumeLevelDisplay extends Component$1 {
  12349. /**
  12350. * Creates an instance of this class.
  12351. *
  12352. * @param { import('../../player').default } player
  12353. * The {@link Player} that this class should be attached to.
  12354. *
  12355. * @param {Object} [options]
  12356. * The key/value store of player options.
  12357. */
  12358. constructor(player, options) {
  12359. super(player, options);
  12360. this.update = throttle(bind_(this, this.update), UPDATE_REFRESH_INTERVAL);
  12361. }
  12362. /**
  12363. * Create the DOM element for this class.
  12364. *
  12365. * @return {Element}
  12366. * The element that was created.
  12367. */
  12368. createEl() {
  12369. return super.createEl('div', {
  12370. className: 'vjs-mouse-display'
  12371. });
  12372. }
  12373. /**
  12374. * Enquires updates to its own DOM as well as the DOM of its
  12375. * {@link VolumeLevelTooltip} child.
  12376. *
  12377. * @param {Object} rangeBarRect
  12378. * The `ClientRect` for the {@link VolumeBar} element.
  12379. *
  12380. * @param {number} rangeBarPoint
  12381. * A number from 0 to 1, representing a horizontal/vertical reference point
  12382. * from the left edge of the {@link VolumeBar}
  12383. *
  12384. * @param {boolean} vertical
  12385. * Referees to the Volume control position
  12386. * in the control bar{@link VolumeControl}
  12387. *
  12388. */
  12389. update(rangeBarRect, rangeBarPoint, vertical) {
  12390. const volume = 100 * rangeBarPoint;
  12391. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, () => {
  12392. if (vertical) {
  12393. this.el_.style.bottom = `${rangeBarRect.height * rangeBarPoint}px`;
  12394. } else {
  12395. this.el_.style.left = `${rangeBarRect.width * rangeBarPoint}px`;
  12396. }
  12397. });
  12398. }
  12399. }
  12400. /**
  12401. * Default options for `MouseVolumeLevelDisplay`
  12402. *
  12403. * @type {Object}
  12404. * @private
  12405. */
  12406. MouseVolumeLevelDisplay.prototype.options_ = {
  12407. children: ['volumeLevelTooltip']
  12408. };
  12409. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  12410. /**
  12411. * @file volume-bar.js
  12412. */
  12413. /**
  12414. * The bar that contains the volume level and can be clicked on to adjust the level
  12415. *
  12416. * @extends Slider
  12417. */
  12418. class VolumeBar extends Slider {
  12419. /**
  12420. * Creates an instance of this class.
  12421. *
  12422. * @param { import('../../player').default } player
  12423. * The `Player` that this class should be attached to.
  12424. *
  12425. * @param {Object} [options]
  12426. * The key/value store of player options.
  12427. */
  12428. constructor(player, options) {
  12429. super(player, options);
  12430. this.on('slideractive', e => this.updateLastVolume_(e));
  12431. this.on(player, 'volumechange', e => this.updateARIAAttributes(e));
  12432. player.ready(() => this.updateARIAAttributes());
  12433. }
  12434. /**
  12435. * Create the `Component`'s DOM element
  12436. *
  12437. * @return {Element}
  12438. * The element that was created.
  12439. */
  12440. createEl() {
  12441. return super.createEl('div', {
  12442. className: 'vjs-volume-bar vjs-slider-bar'
  12443. }, {
  12444. 'aria-label': this.localize('Volume Level'),
  12445. 'aria-live': 'polite'
  12446. });
  12447. }
  12448. /**
  12449. * Handle mouse down on volume bar
  12450. *
  12451. * @param {Event} event
  12452. * The `mousedown` event that caused this to run.
  12453. *
  12454. * @listens mousedown
  12455. */
  12456. handleMouseDown(event) {
  12457. if (!isSingleLeftClick(event)) {
  12458. return;
  12459. }
  12460. super.handleMouseDown(event);
  12461. }
  12462. /**
  12463. * Handle movement events on the {@link VolumeMenuButton}.
  12464. *
  12465. * @param {Event} event
  12466. * The event that caused this function to run.
  12467. *
  12468. * @listens mousemove
  12469. */
  12470. handleMouseMove(event) {
  12471. const mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  12472. if (mouseVolumeLevelDisplay) {
  12473. const volumeBarEl = this.el();
  12474. const volumeBarRect = getBoundingClientRect(volumeBarEl);
  12475. const vertical = this.vertical();
  12476. let volumeBarPoint = getPointerPosition(volumeBarEl, event);
  12477. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x;
  12478. // The default skin has a gap on either side of the `VolumeBar`. This means
  12479. // that it's possible to trigger this behavior outside the boundaries of
  12480. // the `VolumeBar`. This ensures we stay within it at all times.
  12481. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  12482. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  12483. }
  12484. if (!isSingleLeftClick(event)) {
  12485. return;
  12486. }
  12487. this.checkMuted();
  12488. this.player_.volume(this.calculateDistance(event));
  12489. }
  12490. /**
  12491. * If the player is muted unmute it.
  12492. */
  12493. checkMuted() {
  12494. if (this.player_.muted()) {
  12495. this.player_.muted(false);
  12496. }
  12497. }
  12498. /**
  12499. * Get percent of volume level
  12500. *
  12501. * @return {number}
  12502. * Volume level percent as a decimal number.
  12503. */
  12504. getPercent() {
  12505. if (this.player_.muted()) {
  12506. return 0;
  12507. }
  12508. return this.player_.volume();
  12509. }
  12510. /**
  12511. * Increase volume level for keyboard users
  12512. */
  12513. stepForward() {
  12514. this.checkMuted();
  12515. this.player_.volume(this.player_.volume() + 0.1);
  12516. }
  12517. /**
  12518. * Decrease volume level for keyboard users
  12519. */
  12520. stepBack() {
  12521. this.checkMuted();
  12522. this.player_.volume(this.player_.volume() - 0.1);
  12523. }
  12524. /**
  12525. * Update ARIA accessibility attributes
  12526. *
  12527. * @param {Event} [event]
  12528. * The `volumechange` event that caused this function to run.
  12529. *
  12530. * @listens Player#volumechange
  12531. */
  12532. updateARIAAttributes(event) {
  12533. const ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  12534. this.el_.setAttribute('aria-valuenow', ariaValue);
  12535. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  12536. }
  12537. /**
  12538. * Returns the current value of the player volume as a percentage
  12539. *
  12540. * @private
  12541. */
  12542. volumeAsPercentage_() {
  12543. return Math.round(this.player_.volume() * 100);
  12544. }
  12545. /**
  12546. * When user starts dragging the VolumeBar, store the volume and listen for
  12547. * the end of the drag. When the drag ends, if the volume was set to zero,
  12548. * set lastVolume to the stored volume.
  12549. *
  12550. * @listens slideractive
  12551. * @private
  12552. */
  12553. updateLastVolume_() {
  12554. const volumeBeforeDrag = this.player_.volume();
  12555. this.one('sliderinactive', () => {
  12556. if (this.player_.volume() === 0) {
  12557. this.player_.lastVolume_(volumeBeforeDrag);
  12558. }
  12559. });
  12560. }
  12561. }
  12562. /**
  12563. * Default options for the `VolumeBar`
  12564. *
  12565. * @type {Object}
  12566. * @private
  12567. */
  12568. VolumeBar.prototype.options_ = {
  12569. children: ['volumeLevel'],
  12570. barName: 'volumeLevel'
  12571. };
  12572. // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  12573. if (!IS_IOS && !IS_ANDROID) {
  12574. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  12575. }
  12576. /**
  12577. * Call the update event for this Slider when this event happens on the player.
  12578. *
  12579. * @type {string}
  12580. */
  12581. VolumeBar.prototype.playerEvent = 'volumechange';
  12582. Component$1.registerComponent('VolumeBar', VolumeBar);
  12583. /**
  12584. * @file volume-control.js
  12585. */
  12586. /**
  12587. * The component for controlling the volume level
  12588. *
  12589. * @extends Component
  12590. */
  12591. class VolumeControl extends Component$1 {
  12592. /**
  12593. * Creates an instance of this class.
  12594. *
  12595. * @param { import('../../player').default } player
  12596. * The `Player` that this class should be attached to.
  12597. *
  12598. * @param {Object} [options={}]
  12599. * The key/value store of player options.
  12600. */
  12601. constructor(player, options = {}) {
  12602. options.vertical = options.vertical || false;
  12603. // Pass the vertical option down to the VolumeBar if
  12604. // the VolumeBar is turned on.
  12605. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  12606. options.volumeBar = options.volumeBar || {};
  12607. options.volumeBar.vertical = options.vertical;
  12608. }
  12609. super(player, options);
  12610. // hide this control if volume support is missing
  12611. checkVolumeSupport(this, player);
  12612. this.throttledHandleMouseMove = throttle(bind_(this, this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12613. this.handleMouseUpHandler_ = e => this.handleMouseUp(e);
  12614. this.on('mousedown', e => this.handleMouseDown(e));
  12615. this.on('touchstart', e => this.handleMouseDown(e));
  12616. this.on('mousemove', e => this.handleMouseMove(e));
  12617. // while the slider is active (the mouse has been pressed down and
  12618. // is dragging) or in focus we do not want to hide the VolumeBar
  12619. this.on(this.volumeBar, ['focus', 'slideractive'], () => {
  12620. this.volumeBar.addClass('vjs-slider-active');
  12621. this.addClass('vjs-slider-active');
  12622. this.trigger('slideractive');
  12623. });
  12624. this.on(this.volumeBar, ['blur', 'sliderinactive'], () => {
  12625. this.volumeBar.removeClass('vjs-slider-active');
  12626. this.removeClass('vjs-slider-active');
  12627. this.trigger('sliderinactive');
  12628. });
  12629. }
  12630. /**
  12631. * Create the `Component`'s DOM element
  12632. *
  12633. * @return {Element}
  12634. * The element that was created.
  12635. */
  12636. createEl() {
  12637. let orientationClass = 'vjs-volume-horizontal';
  12638. if (this.options_.vertical) {
  12639. orientationClass = 'vjs-volume-vertical';
  12640. }
  12641. return super.createEl('div', {
  12642. className: `vjs-volume-control vjs-control ${orientationClass}`
  12643. });
  12644. }
  12645. /**
  12646. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12647. *
  12648. * @param {Event} event
  12649. * `mousedown` or `touchstart` event that triggered this function
  12650. *
  12651. * @listens mousedown
  12652. * @listens touchstart
  12653. */
  12654. handleMouseDown(event) {
  12655. const doc = this.el_.ownerDocument;
  12656. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  12657. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  12658. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12659. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12660. }
  12661. /**
  12662. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  12663. *
  12664. * @param {Event} event
  12665. * `mouseup` or `touchend` event that triggered this function.
  12666. *
  12667. * @listens touchend
  12668. * @listens mouseup
  12669. */
  12670. handleMouseUp(event) {
  12671. const doc = this.el_.ownerDocument;
  12672. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  12673. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  12674. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12675. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12676. }
  12677. /**
  12678. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  12679. *
  12680. * @param {Event} event
  12681. * `mousedown` or `touchstart` event that triggered this function
  12682. *
  12683. * @listens mousedown
  12684. * @listens touchstart
  12685. */
  12686. handleMouseMove(event) {
  12687. this.volumeBar.handleMouseMove(event);
  12688. }
  12689. }
  12690. /**
  12691. * Default options for the `VolumeControl`
  12692. *
  12693. * @type {Object}
  12694. * @private
  12695. */
  12696. VolumeControl.prototype.options_ = {
  12697. children: ['volumeBar']
  12698. };
  12699. Component$1.registerComponent('VolumeControl', VolumeControl);
  12700. /**
  12701. * Check if muting volume is supported and if it isn't hide the mute toggle
  12702. * button.
  12703. *
  12704. * @param { import('../../component').default } self
  12705. * A reference to the mute toggle button
  12706. *
  12707. * @param { import('../../player').default } player
  12708. * A reference to the player
  12709. *
  12710. * @private
  12711. */
  12712. const checkMuteSupport = function (self, player) {
  12713. // hide mute toggle button if it's not supported by the current tech
  12714. if (player.tech_ && !player.tech_.featuresMuteControl) {
  12715. self.addClass('vjs-hidden');
  12716. }
  12717. self.on(player, 'loadstart', function () {
  12718. if (!player.tech_.featuresMuteControl) {
  12719. self.addClass('vjs-hidden');
  12720. } else {
  12721. self.removeClass('vjs-hidden');
  12722. }
  12723. });
  12724. };
  12725. /**
  12726. * @file mute-toggle.js
  12727. */
  12728. /**
  12729. * A button component for muting the audio.
  12730. *
  12731. * @extends Button
  12732. */
  12733. class MuteToggle extends Button {
  12734. /**
  12735. * Creates an instance of this class.
  12736. *
  12737. * @param { import('./player').default } player
  12738. * The `Player` that this class should be attached to.
  12739. *
  12740. * @param {Object} [options]
  12741. * The key/value store of player options.
  12742. */
  12743. constructor(player, options) {
  12744. super(player, options);
  12745. // hide this control if volume support is missing
  12746. checkMuteSupport(this, player);
  12747. this.on(player, ['loadstart', 'volumechange'], e => this.update(e));
  12748. }
  12749. /**
  12750. * Builds the default DOM `className`.
  12751. *
  12752. * @return {string}
  12753. * The DOM `className` for this object.
  12754. */
  12755. buildCSSClass() {
  12756. return `vjs-mute-control ${super.buildCSSClass()}`;
  12757. }
  12758. /**
  12759. * This gets called when an `MuteToggle` is "clicked". See
  12760. * {@link ClickableComponent} for more detailed information on what a click can be.
  12761. *
  12762. * @param {Event} [event]
  12763. * The `keydown`, `tap`, or `click` event that caused this function to be
  12764. * called.
  12765. *
  12766. * @listens tap
  12767. * @listens click
  12768. */
  12769. handleClick(event) {
  12770. const vol = this.player_.volume();
  12771. const lastVolume = this.player_.lastVolume_();
  12772. if (vol === 0) {
  12773. const volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  12774. this.player_.volume(volumeToSet);
  12775. this.player_.muted(false);
  12776. } else {
  12777. this.player_.muted(this.player_.muted() ? false : true);
  12778. }
  12779. }
  12780. /**
  12781. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  12782. * on the player.
  12783. *
  12784. * @param {Event} [event]
  12785. * The {@link Player#loadstart} event if this function was called
  12786. * through an event.
  12787. *
  12788. * @listens Player#loadstart
  12789. * @listens Player#volumechange
  12790. */
  12791. update(event) {
  12792. this.updateIcon_();
  12793. this.updateControlText_();
  12794. }
  12795. /**
  12796. * Update the appearance of the `MuteToggle` icon.
  12797. *
  12798. * Possible states (given `level` variable below):
  12799. * - 0: crossed out
  12800. * - 1: zero bars of volume
  12801. * - 2: one bar of volume
  12802. * - 3: two bars of volume
  12803. *
  12804. * @private
  12805. */
  12806. updateIcon_() {
  12807. const vol = this.player_.volume();
  12808. let level = 3;
  12809. // in iOS when a player is loaded with muted attribute
  12810. // and volume is changed with a native mute button
  12811. // we want to make sure muted state is updated
  12812. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  12813. this.player_.muted(this.player_.tech_.el_.muted);
  12814. }
  12815. if (vol === 0 || this.player_.muted()) {
  12816. level = 0;
  12817. } else if (vol < 0.33) {
  12818. level = 1;
  12819. } else if (vol < 0.67) {
  12820. level = 2;
  12821. }
  12822. removeClass(this.el_, [0, 1, 2, 3].reduce((str, i) => str + `${i ? ' ' : ''}vjs-vol-${i}`, ''));
  12823. addClass(this.el_, `vjs-vol-${level}`);
  12824. }
  12825. /**
  12826. * If `muted` has changed on the player, update the control text
  12827. * (`title` attribute on `vjs-mute-control` element and content of
  12828. * `vjs-control-text` element).
  12829. *
  12830. * @private
  12831. */
  12832. updateControlText_() {
  12833. const soundOff = this.player_.muted() || this.player_.volume() === 0;
  12834. const text = soundOff ? 'Unmute' : 'Mute';
  12835. if (this.controlText() !== text) {
  12836. this.controlText(text);
  12837. }
  12838. }
  12839. }
  12840. /**
  12841. * The text that should display over the `MuteToggle`s controls. Added for localization.
  12842. *
  12843. * @type {string}
  12844. * @protected
  12845. */
  12846. MuteToggle.prototype.controlText_ = 'Mute';
  12847. Component$1.registerComponent('MuteToggle', MuteToggle);
  12848. /**
  12849. * @file volume-control.js
  12850. */
  12851. /**
  12852. * A Component to contain the MuteToggle and VolumeControl so that
  12853. * they can work together.
  12854. *
  12855. * @extends Component
  12856. */
  12857. class VolumePanel extends Component$1 {
  12858. /**
  12859. * Creates an instance of this class.
  12860. *
  12861. * @param { import('./player').default } player
  12862. * The `Player` that this class should be attached to.
  12863. *
  12864. * @param {Object} [options={}]
  12865. * The key/value store of player options.
  12866. */
  12867. constructor(player, options = {}) {
  12868. if (typeof options.inline !== 'undefined') {
  12869. options.inline = options.inline;
  12870. } else {
  12871. options.inline = true;
  12872. }
  12873. // pass the inline option down to the VolumeControl as vertical if
  12874. // the VolumeControl is on.
  12875. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  12876. options.volumeControl = options.volumeControl || {};
  12877. options.volumeControl.vertical = !options.inline;
  12878. }
  12879. super(player, options);
  12880. // this handler is used by mouse handler methods below
  12881. this.handleKeyPressHandler_ = e => this.handleKeyPress(e);
  12882. this.on(player, ['loadstart'], e => this.volumePanelState_(e));
  12883. this.on(this.muteToggle, 'keyup', e => this.handleKeyPress(e));
  12884. this.on(this.volumeControl, 'keyup', e => this.handleVolumeControlKeyUp(e));
  12885. this.on('keydown', e => this.handleKeyPress(e));
  12886. this.on('mouseover', e => this.handleMouseOver(e));
  12887. this.on('mouseout', e => this.handleMouseOut(e));
  12888. // while the slider is active (the mouse has been pressed down and
  12889. // is dragging) we do not want to hide the VolumeBar
  12890. this.on(this.volumeControl, ['slideractive'], this.sliderActive_);
  12891. this.on(this.volumeControl, ['sliderinactive'], this.sliderInactive_);
  12892. }
  12893. /**
  12894. * Add vjs-slider-active class to the VolumePanel
  12895. *
  12896. * @listens VolumeControl#slideractive
  12897. * @private
  12898. */
  12899. sliderActive_() {
  12900. this.addClass('vjs-slider-active');
  12901. }
  12902. /**
  12903. * Removes vjs-slider-active class to the VolumePanel
  12904. *
  12905. * @listens VolumeControl#sliderinactive
  12906. * @private
  12907. */
  12908. sliderInactive_() {
  12909. this.removeClass('vjs-slider-active');
  12910. }
  12911. /**
  12912. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  12913. * depending on MuteToggle and VolumeControl state
  12914. *
  12915. * @listens Player#loadstart
  12916. * @private
  12917. */
  12918. volumePanelState_() {
  12919. // hide volume panel if neither volume control or mute toggle
  12920. // are displayed
  12921. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  12922. this.addClass('vjs-hidden');
  12923. }
  12924. // if only mute toggle is visible we don't want
  12925. // volume panel expanding when hovered or active
  12926. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  12927. this.addClass('vjs-mute-toggle-only');
  12928. }
  12929. }
  12930. /**
  12931. * Create the `Component`'s DOM element
  12932. *
  12933. * @return {Element}
  12934. * The element that was created.
  12935. */
  12936. createEl() {
  12937. let orientationClass = 'vjs-volume-panel-horizontal';
  12938. if (!this.options_.inline) {
  12939. orientationClass = 'vjs-volume-panel-vertical';
  12940. }
  12941. return super.createEl('div', {
  12942. className: `vjs-volume-panel vjs-control ${orientationClass}`
  12943. });
  12944. }
  12945. /**
  12946. * Dispose of the `volume-panel` and all child components.
  12947. */
  12948. dispose() {
  12949. this.handleMouseOut();
  12950. super.dispose();
  12951. }
  12952. /**
  12953. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  12954. * the volume panel and sets focus on `MuteToggle`.
  12955. *
  12956. * @param {Event} event
  12957. * The `keyup` event that caused this function to be called.
  12958. *
  12959. * @listens keyup
  12960. */
  12961. handleVolumeControlKeyUp(event) {
  12962. if (keycode__default["default"].isEventKey(event, 'Esc')) {
  12963. this.muteToggle.focus();
  12964. }
  12965. }
  12966. /**
  12967. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  12968. * Turns on listening for `mouseover` event. When they happen it
  12969. * calls `this.handleMouseOver`.
  12970. *
  12971. * @param {Event} event
  12972. * The `mouseover` event that caused this function to be called.
  12973. *
  12974. * @listens mouseover
  12975. */
  12976. handleMouseOver(event) {
  12977. this.addClass('vjs-hover');
  12978. on(document__default["default"], 'keyup', this.handleKeyPressHandler_);
  12979. }
  12980. /**
  12981. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  12982. * Turns on listening for `mouseout` event. When they happen it
  12983. * calls `this.handleMouseOut`.
  12984. *
  12985. * @param {Event} event
  12986. * The `mouseout` event that caused this function to be called.
  12987. *
  12988. * @listens mouseout
  12989. */
  12990. handleMouseOut(event) {
  12991. this.removeClass('vjs-hover');
  12992. off(document__default["default"], 'keyup', this.handleKeyPressHandler_);
  12993. }
  12994. /**
  12995. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  12996. * looking for ESC, which hides the `VolumeControl`.
  12997. *
  12998. * @param {Event} event
  12999. * The keypress that triggered this event.
  13000. *
  13001. * @listens keydown | keyup
  13002. */
  13003. handleKeyPress(event) {
  13004. if (keycode__default["default"].isEventKey(event, 'Esc')) {
  13005. this.handleMouseOut();
  13006. }
  13007. }
  13008. }
  13009. /**
  13010. * Default options for the `VolumeControl`
  13011. *
  13012. * @type {Object}
  13013. * @private
  13014. */
  13015. VolumePanel.prototype.options_ = {
  13016. children: ['muteToggle', 'volumeControl']
  13017. };
  13018. Component$1.registerComponent('VolumePanel', VolumePanel);
  13019. /**
  13020. * Button to skip forward a configurable amount of time
  13021. * through a video. Renders in the control bar.
  13022. *
  13023. * e.g. options: {controlBar: {skipButtons: forward: 5}}
  13024. *
  13025. * @extends Button
  13026. */
  13027. class SkipForward extends Button {
  13028. constructor(player, options) {
  13029. super(player, options);
  13030. this.validOptions = [5, 10, 30];
  13031. this.skipTime = this.getSkipForwardTime();
  13032. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13033. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13034. this.show();
  13035. } else {
  13036. this.hide();
  13037. }
  13038. }
  13039. getSkipForwardTime() {
  13040. const playerOptions = this.options_.playerOptions;
  13041. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.forward;
  13042. }
  13043. buildCSSClass() {
  13044. return `vjs-skip-forward-${this.getSkipForwardTime()} ${super.buildCSSClass()}`;
  13045. }
  13046. /**
  13047. * On click, skips forward in the duration/seekable range by a configurable amount of seconds.
  13048. * If the time left in the duration/seekable range is less than the configured 'skip forward' time,
  13049. * skips to end of duration/seekable range.
  13050. *
  13051. * Handle a click on a `SkipForward` button
  13052. *
  13053. * @param {EventTarget~Event} event
  13054. * The `click` event that caused this function
  13055. * to be called
  13056. */
  13057. handleClick(event) {
  13058. const currentVideoTime = this.player_.currentTime();
  13059. const liveTracker = this.player_.liveTracker;
  13060. const duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : this.player_.duration();
  13061. let newTime;
  13062. if (currentVideoTime + this.skipTime <= duration) {
  13063. newTime = currentVideoTime + this.skipTime;
  13064. } else {
  13065. newTime = duration;
  13066. }
  13067. this.player_.currentTime(newTime);
  13068. }
  13069. /**
  13070. * Update control text on languagechange
  13071. */
  13072. handleLanguagechange() {
  13073. this.controlText(this.localize('Skip forward {1} seconds', [this.skipTime]));
  13074. }
  13075. }
  13076. Component$1.registerComponent('SkipForward', SkipForward);
  13077. /**
  13078. * Button to skip backward a configurable amount of time
  13079. * through a video. Renders in the control bar.
  13080. *
  13081. * * e.g. options: {controlBar: {skipButtons: backward: 5}}
  13082. *
  13083. * @extends Button
  13084. */
  13085. class SkipBackward extends Button {
  13086. constructor(player, options) {
  13087. super(player, options);
  13088. this.validOptions = [5, 10, 30];
  13089. this.skipTime = this.getSkipBackwardTime();
  13090. if (this.skipTime && this.validOptions.includes(this.skipTime)) {
  13091. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13092. this.show();
  13093. } else {
  13094. this.hide();
  13095. }
  13096. }
  13097. getSkipBackwardTime() {
  13098. const playerOptions = this.options_.playerOptions;
  13099. return playerOptions.controlBar && playerOptions.controlBar.skipButtons && playerOptions.controlBar.skipButtons.backward;
  13100. }
  13101. buildCSSClass() {
  13102. return `vjs-skip-backward-${this.getSkipBackwardTime()} ${super.buildCSSClass()}`;
  13103. }
  13104. /**
  13105. * On click, skips backward in the video by a configurable amount of seconds.
  13106. * If the current time in the video is less than the configured 'skip backward' time,
  13107. * skips to beginning of video or seekable range.
  13108. *
  13109. * Handle a click on a `SkipBackward` button
  13110. *
  13111. * @param {EventTarget~Event} event
  13112. * The `click` event that caused this function
  13113. * to be called
  13114. */
  13115. handleClick(event) {
  13116. const currentVideoTime = this.player_.currentTime();
  13117. const liveTracker = this.player_.liveTracker;
  13118. const seekableStart = liveTracker && liveTracker.isLive() && liveTracker.seekableStart();
  13119. let newTime;
  13120. if (seekableStart && currentVideoTime - this.skipTime <= seekableStart) {
  13121. newTime = seekableStart;
  13122. } else if (currentVideoTime >= this.skipTime) {
  13123. newTime = currentVideoTime - this.skipTime;
  13124. } else {
  13125. newTime = 0;
  13126. }
  13127. this.player_.currentTime(newTime);
  13128. }
  13129. /**
  13130. * Update control text on languagechange
  13131. */
  13132. handleLanguagechange() {
  13133. this.controlText(this.localize('Skip backward {1} seconds', [this.skipTime]));
  13134. }
  13135. }
  13136. SkipBackward.prototype.controlText_ = 'Skip Backward';
  13137. Component$1.registerComponent('SkipBackward', SkipBackward);
  13138. /**
  13139. * @file menu.js
  13140. */
  13141. /**
  13142. * The Menu component is used to build popup menus, including subtitle and
  13143. * captions selection menus.
  13144. *
  13145. * @extends Component
  13146. */
  13147. class Menu extends Component$1 {
  13148. /**
  13149. * Create an instance of this class.
  13150. *
  13151. * @param { import('../player').default } player
  13152. * the player that this component should attach to
  13153. *
  13154. * @param {Object} [options]
  13155. * Object of option names and values
  13156. *
  13157. */
  13158. constructor(player, options) {
  13159. super(player, options);
  13160. if (options) {
  13161. this.menuButton_ = options.menuButton;
  13162. }
  13163. this.focusedChild_ = -1;
  13164. this.on('keydown', e => this.handleKeyDown(e));
  13165. // All the menu item instances share the same blur handler provided by the menu container.
  13166. this.boundHandleBlur_ = e => this.handleBlur(e);
  13167. this.boundHandleTapClick_ = e => this.handleTapClick(e);
  13168. }
  13169. /**
  13170. * Add event listeners to the {@link MenuItem}.
  13171. *
  13172. * @param {Object} component
  13173. * The instance of the `MenuItem` to add listeners to.
  13174. *
  13175. */
  13176. addEventListenerForItem(component) {
  13177. if (!(component instanceof Component$1)) {
  13178. return;
  13179. }
  13180. this.on(component, 'blur', this.boundHandleBlur_);
  13181. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13182. }
  13183. /**
  13184. * Remove event listeners from the {@link MenuItem}.
  13185. *
  13186. * @param {Object} component
  13187. * The instance of the `MenuItem` to remove listeners.
  13188. *
  13189. */
  13190. removeEventListenerForItem(component) {
  13191. if (!(component instanceof Component$1)) {
  13192. return;
  13193. }
  13194. this.off(component, 'blur', this.boundHandleBlur_);
  13195. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13196. }
  13197. /**
  13198. * This method will be called indirectly when the component has been added
  13199. * before the component adds to the new menu instance by `addItem`.
  13200. * In this case, the original menu instance will remove the component
  13201. * by calling `removeChild`.
  13202. *
  13203. * @param {Object} component
  13204. * The instance of the `MenuItem`
  13205. */
  13206. removeChild(component) {
  13207. if (typeof component === 'string') {
  13208. component = this.getChild(component);
  13209. }
  13210. this.removeEventListenerForItem(component);
  13211. super.removeChild(component);
  13212. }
  13213. /**
  13214. * Add a {@link MenuItem} to the menu.
  13215. *
  13216. * @param {Object|string} component
  13217. * The name or instance of the `MenuItem` to add.
  13218. *
  13219. */
  13220. addItem(component) {
  13221. const childComponent = this.addChild(component);
  13222. if (childComponent) {
  13223. this.addEventListenerForItem(childComponent);
  13224. }
  13225. }
  13226. /**
  13227. * Create the `Menu`s DOM element.
  13228. *
  13229. * @return {Element}
  13230. * the element that was created
  13231. */
  13232. createEl() {
  13233. const contentElType = this.options_.contentElType || 'ul';
  13234. this.contentEl_ = createEl(contentElType, {
  13235. className: 'vjs-menu-content'
  13236. });
  13237. this.contentEl_.setAttribute('role', 'menu');
  13238. const el = super.createEl('div', {
  13239. append: this.contentEl_,
  13240. className: 'vjs-menu'
  13241. });
  13242. el.appendChild(this.contentEl_);
  13243. // Prevent clicks from bubbling up. Needed for Menu Buttons,
  13244. // where a click on the parent is significant
  13245. on(el, 'click', function (event) {
  13246. event.preventDefault();
  13247. event.stopImmediatePropagation();
  13248. });
  13249. return el;
  13250. }
  13251. dispose() {
  13252. this.contentEl_ = null;
  13253. this.boundHandleBlur_ = null;
  13254. this.boundHandleTapClick_ = null;
  13255. super.dispose();
  13256. }
  13257. /**
  13258. * Called when a `MenuItem` loses focus.
  13259. *
  13260. * @param {Event} event
  13261. * The `blur` event that caused this function to be called.
  13262. *
  13263. * @listens blur
  13264. */
  13265. handleBlur(event) {
  13266. const relatedTarget = event.relatedTarget || document__default["default"].activeElement;
  13267. // Close menu popup when a user clicks outside the menu
  13268. if (!this.children().some(element => {
  13269. return element.el() === relatedTarget;
  13270. })) {
  13271. const btn = this.menuButton_;
  13272. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  13273. btn.unpressButton();
  13274. }
  13275. }
  13276. }
  13277. /**
  13278. * Called when a `MenuItem` gets clicked or tapped.
  13279. *
  13280. * @param {Event} event
  13281. * The `click` or `tap` event that caused this function to be called.
  13282. *
  13283. * @listens click,tap
  13284. */
  13285. handleTapClick(event) {
  13286. // Unpress the associated MenuButton, and move focus back to it
  13287. if (this.menuButton_) {
  13288. this.menuButton_.unpressButton();
  13289. const childComponents = this.children();
  13290. if (!Array.isArray(childComponents)) {
  13291. return;
  13292. }
  13293. const foundComponent = childComponents.filter(component => component.el() === event.target)[0];
  13294. if (!foundComponent) {
  13295. return;
  13296. }
  13297. // don't focus menu button if item is a caption settings item
  13298. // because focus will move elsewhere
  13299. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  13300. this.menuButton_.focus();
  13301. }
  13302. }
  13303. }
  13304. /**
  13305. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  13306. *
  13307. * @param {Event} event
  13308. * A `keydown` event that happened on the menu.
  13309. *
  13310. * @listens keydown
  13311. */
  13312. handleKeyDown(event) {
  13313. // Left and Down Arrows
  13314. if (keycode__default["default"].isEventKey(event, 'Left') || keycode__default["default"].isEventKey(event, 'Down')) {
  13315. event.preventDefault();
  13316. event.stopPropagation();
  13317. this.stepForward();
  13318. // Up and Right Arrows
  13319. } else if (keycode__default["default"].isEventKey(event, 'Right') || keycode__default["default"].isEventKey(event, 'Up')) {
  13320. event.preventDefault();
  13321. event.stopPropagation();
  13322. this.stepBack();
  13323. }
  13324. }
  13325. /**
  13326. * Move to next (lower) menu item for keyboard users.
  13327. */
  13328. stepForward() {
  13329. let stepChild = 0;
  13330. if (this.focusedChild_ !== undefined) {
  13331. stepChild = this.focusedChild_ + 1;
  13332. }
  13333. this.focus(stepChild);
  13334. }
  13335. /**
  13336. * Move to previous (higher) menu item for keyboard users.
  13337. */
  13338. stepBack() {
  13339. let stepChild = 0;
  13340. if (this.focusedChild_ !== undefined) {
  13341. stepChild = this.focusedChild_ - 1;
  13342. }
  13343. this.focus(stepChild);
  13344. }
  13345. /**
  13346. * Set focus on a {@link MenuItem} in the `Menu`.
  13347. *
  13348. * @param {Object|string} [item=0]
  13349. * Index of child item set focus on.
  13350. */
  13351. focus(item = 0) {
  13352. const children = this.children().slice();
  13353. const haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  13354. if (haveTitle) {
  13355. children.shift();
  13356. }
  13357. if (children.length > 0) {
  13358. if (item < 0) {
  13359. item = 0;
  13360. } else if (item >= children.length) {
  13361. item = children.length - 1;
  13362. }
  13363. this.focusedChild_ = item;
  13364. children[item].el_.focus();
  13365. }
  13366. }
  13367. }
  13368. Component$1.registerComponent('Menu', Menu);
  13369. /**
  13370. * @file menu-button.js
  13371. */
  13372. /**
  13373. * A `MenuButton` class for any popup {@link Menu}.
  13374. *
  13375. * @extends Component
  13376. */
  13377. class MenuButton extends Component$1 {
  13378. /**
  13379. * Creates an instance of this class.
  13380. *
  13381. * @param { import('../player').default } player
  13382. * The `Player` that this class should be attached to.
  13383. *
  13384. * @param {Object} [options={}]
  13385. * The key/value store of player options.
  13386. */
  13387. constructor(player, options = {}) {
  13388. super(player, options);
  13389. this.menuButton_ = new Button(player, options);
  13390. this.menuButton_.controlText(this.controlText_);
  13391. this.menuButton_.el_.setAttribute('aria-haspopup', 'true');
  13392. // Add buildCSSClass values to the button, not the wrapper
  13393. const buttonClass = Button.prototype.buildCSSClass();
  13394. this.menuButton_.el_.className = this.buildCSSClass() + ' ' + buttonClass;
  13395. this.menuButton_.removeClass('vjs-control');
  13396. this.addChild(this.menuButton_);
  13397. this.update();
  13398. this.enabled_ = true;
  13399. const handleClick = e => this.handleClick(e);
  13400. this.handleMenuKeyUp_ = e => this.handleMenuKeyUp(e);
  13401. this.on(this.menuButton_, 'tap', handleClick);
  13402. this.on(this.menuButton_, 'click', handleClick);
  13403. this.on(this.menuButton_, 'keydown', e => this.handleKeyDown(e));
  13404. this.on(this.menuButton_, 'mouseenter', () => {
  13405. this.addClass('vjs-hover');
  13406. this.menu.show();
  13407. on(document__default["default"], 'keyup', this.handleMenuKeyUp_);
  13408. });
  13409. this.on('mouseleave', e => this.handleMouseLeave(e));
  13410. this.on('keydown', e => this.handleSubmenuKeyDown(e));
  13411. }
  13412. /**
  13413. * Update the menu based on the current state of its items.
  13414. */
  13415. update() {
  13416. const menu = this.createMenu();
  13417. if (this.menu) {
  13418. this.menu.dispose();
  13419. this.removeChild(this.menu);
  13420. }
  13421. this.menu = menu;
  13422. this.addChild(menu);
  13423. /**
  13424. * Track the state of the menu button
  13425. *
  13426. * @type {Boolean}
  13427. * @private
  13428. */
  13429. this.buttonPressed_ = false;
  13430. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13431. if (this.items && this.items.length <= this.hideThreshold_) {
  13432. this.hide();
  13433. this.menu.contentEl_.removeAttribute('role');
  13434. } else {
  13435. this.show();
  13436. this.menu.contentEl_.setAttribute('role', 'menu');
  13437. }
  13438. }
  13439. /**
  13440. * Create the menu and add all items to it.
  13441. *
  13442. * @return {Menu}
  13443. * The constructed menu
  13444. */
  13445. createMenu() {
  13446. const menu = new Menu(this.player_, {
  13447. menuButton: this
  13448. });
  13449. /**
  13450. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  13451. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  13452. * it here because every time we run `createMenu` we need to reset the value.
  13453. *
  13454. * @protected
  13455. * @type {Number}
  13456. */
  13457. this.hideThreshold_ = 0;
  13458. // Add a title list item to the top
  13459. if (this.options_.title) {
  13460. const titleEl = createEl('li', {
  13461. className: 'vjs-menu-title',
  13462. textContent: toTitleCase$1(this.options_.title),
  13463. tabIndex: -1
  13464. });
  13465. const titleComponent = new Component$1(this.player_, {
  13466. el: titleEl
  13467. });
  13468. menu.addItem(titleComponent);
  13469. }
  13470. this.items = this.createItems();
  13471. if (this.items) {
  13472. // Add menu items to the menu
  13473. for (let i = 0; i < this.items.length; i++) {
  13474. menu.addItem(this.items[i]);
  13475. }
  13476. }
  13477. return menu;
  13478. }
  13479. /**
  13480. * Create the list of menu items. Specific to each subclass.
  13481. *
  13482. * @abstract
  13483. */
  13484. createItems() {}
  13485. /**
  13486. * Create the `MenuButtons`s DOM element.
  13487. *
  13488. * @return {Element}
  13489. * The element that gets created.
  13490. */
  13491. createEl() {
  13492. return super.createEl('div', {
  13493. className: this.buildWrapperCSSClass()
  13494. }, {});
  13495. }
  13496. /**
  13497. * Allow sub components to stack CSS class names for the wrapper element
  13498. *
  13499. * @return {string}
  13500. * The constructed wrapper DOM `className`
  13501. */
  13502. buildWrapperCSSClass() {
  13503. let menuButtonClass = 'vjs-menu-button';
  13504. // If the inline option is passed, we want to use different styles altogether.
  13505. if (this.options_.inline === true) {
  13506. menuButtonClass += '-inline';
  13507. } else {
  13508. menuButtonClass += '-popup';
  13509. }
  13510. // TODO: Fix the CSS so that this isn't necessary
  13511. const buttonClass = Button.prototype.buildCSSClass();
  13512. return `vjs-menu-button ${menuButtonClass} ${buttonClass} ${super.buildCSSClass()}`;
  13513. }
  13514. /**
  13515. * Builds the default DOM `className`.
  13516. *
  13517. * @return {string}
  13518. * The DOM `className` for this object.
  13519. */
  13520. buildCSSClass() {
  13521. let menuButtonClass = 'vjs-menu-button';
  13522. // If the inline option is passed, we want to use different styles altogether.
  13523. if (this.options_.inline === true) {
  13524. menuButtonClass += '-inline';
  13525. } else {
  13526. menuButtonClass += '-popup';
  13527. }
  13528. return `vjs-menu-button ${menuButtonClass} ${super.buildCSSClass()}`;
  13529. }
  13530. /**
  13531. * Get or set the localized control text that will be used for accessibility.
  13532. *
  13533. * > NOTE: This will come from the internal `menuButton_` element.
  13534. *
  13535. * @param {string} [text]
  13536. * Control text for element.
  13537. *
  13538. * @param {Element} [el=this.menuButton_.el()]
  13539. * Element to set the title on.
  13540. *
  13541. * @return {string}
  13542. * - The control text when getting
  13543. */
  13544. controlText(text, el = this.menuButton_.el()) {
  13545. return this.menuButton_.controlText(text, el);
  13546. }
  13547. /**
  13548. * Dispose of the `menu-button` and all child components.
  13549. */
  13550. dispose() {
  13551. this.handleMouseLeave();
  13552. super.dispose();
  13553. }
  13554. /**
  13555. * Handle a click on a `MenuButton`.
  13556. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13557. *
  13558. * @param {Event} event
  13559. * The `keydown`, `tap`, or `click` event that caused this function to be
  13560. * called.
  13561. *
  13562. * @listens tap
  13563. * @listens click
  13564. */
  13565. handleClick(event) {
  13566. if (this.buttonPressed_) {
  13567. this.unpressButton();
  13568. } else {
  13569. this.pressButton();
  13570. }
  13571. }
  13572. /**
  13573. * Handle `mouseleave` for `MenuButton`.
  13574. *
  13575. * @param {Event} event
  13576. * The `mouseleave` event that caused this function to be called.
  13577. *
  13578. * @listens mouseleave
  13579. */
  13580. handleMouseLeave(event) {
  13581. this.removeClass('vjs-hover');
  13582. off(document__default["default"], 'keyup', this.handleMenuKeyUp_);
  13583. }
  13584. /**
  13585. * Set the focus to the actual button, not to this element
  13586. */
  13587. focus() {
  13588. this.menuButton_.focus();
  13589. }
  13590. /**
  13591. * Remove the focus from the actual button, not this element
  13592. */
  13593. blur() {
  13594. this.menuButton_.blur();
  13595. }
  13596. /**
  13597. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  13598. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13599. *
  13600. * @param {Event} event
  13601. * The `keydown` event that caused this function to be called.
  13602. *
  13603. * @listens keydown
  13604. */
  13605. handleKeyDown(event) {
  13606. // Escape or Tab unpress the 'button'
  13607. if (keycode__default["default"].isEventKey(event, 'Esc') || keycode__default["default"].isEventKey(event, 'Tab')) {
  13608. if (this.buttonPressed_) {
  13609. this.unpressButton();
  13610. }
  13611. // Don't preventDefault for Tab key - we still want to lose focus
  13612. if (!keycode__default["default"].isEventKey(event, 'Tab')) {
  13613. event.preventDefault();
  13614. // Set focus back to the menu button's button
  13615. this.menuButton_.focus();
  13616. }
  13617. // Up Arrow or Down Arrow also 'press' the button to open the menu
  13618. } else if (keycode__default["default"].isEventKey(event, 'Up') || keycode__default["default"].isEventKey(event, 'Down')) {
  13619. if (!this.buttonPressed_) {
  13620. event.preventDefault();
  13621. this.pressButton();
  13622. }
  13623. }
  13624. }
  13625. /**
  13626. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  13627. * the constructor.
  13628. *
  13629. * @param {Event} event
  13630. * Key press event
  13631. *
  13632. * @listens keyup
  13633. */
  13634. handleMenuKeyUp(event) {
  13635. // Escape hides popup menu
  13636. if (keycode__default["default"].isEventKey(event, 'Esc') || keycode__default["default"].isEventKey(event, 'Tab')) {
  13637. this.removeClass('vjs-hover');
  13638. }
  13639. }
  13640. /**
  13641. * This method name now delegates to `handleSubmenuKeyDown`. This means
  13642. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  13643. * stop working.
  13644. *
  13645. * @param {Event} event
  13646. * The event that caused this function to be called.
  13647. */
  13648. handleSubmenuKeyPress(event) {
  13649. this.handleSubmenuKeyDown(event);
  13650. }
  13651. /**
  13652. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  13653. * the constructor.
  13654. *
  13655. * @param {Event} event
  13656. * Key press event
  13657. *
  13658. * @listens keydown
  13659. */
  13660. handleSubmenuKeyDown(event) {
  13661. // Escape or Tab unpress the 'button'
  13662. if (keycode__default["default"].isEventKey(event, 'Esc') || keycode__default["default"].isEventKey(event, 'Tab')) {
  13663. if (this.buttonPressed_) {
  13664. this.unpressButton();
  13665. }
  13666. // Don't preventDefault for Tab key - we still want to lose focus
  13667. if (!keycode__default["default"].isEventKey(event, 'Tab')) {
  13668. event.preventDefault();
  13669. // Set focus back to the menu button's button
  13670. this.menuButton_.focus();
  13671. }
  13672. }
  13673. }
  13674. /**
  13675. * Put the current `MenuButton` into a pressed state.
  13676. */
  13677. pressButton() {
  13678. if (this.enabled_) {
  13679. this.buttonPressed_ = true;
  13680. this.menu.show();
  13681. this.menu.lockShowing();
  13682. this.menuButton_.el_.setAttribute('aria-expanded', 'true');
  13683. // set the focus into the submenu, except on iOS where it is resulting in
  13684. // undesired scrolling behavior when the player is in an iframe
  13685. if (IS_IOS && isInFrame()) {
  13686. // Return early so that the menu isn't focused
  13687. return;
  13688. }
  13689. this.menu.focus();
  13690. }
  13691. }
  13692. /**
  13693. * Take the current `MenuButton` out of a pressed state.
  13694. */
  13695. unpressButton() {
  13696. if (this.enabled_) {
  13697. this.buttonPressed_ = false;
  13698. this.menu.unlockShowing();
  13699. this.menu.hide();
  13700. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13701. }
  13702. }
  13703. /**
  13704. * Disable the `MenuButton`. Don't allow it to be clicked.
  13705. */
  13706. disable() {
  13707. this.unpressButton();
  13708. this.enabled_ = false;
  13709. this.addClass('vjs-disabled');
  13710. this.menuButton_.disable();
  13711. }
  13712. /**
  13713. * Enable the `MenuButton`. Allow it to be clicked.
  13714. */
  13715. enable() {
  13716. this.enabled_ = true;
  13717. this.removeClass('vjs-disabled');
  13718. this.menuButton_.enable();
  13719. }
  13720. }
  13721. Component$1.registerComponent('MenuButton', MenuButton);
  13722. /**
  13723. * @file track-button.js
  13724. */
  13725. /**
  13726. * The base class for buttons that toggle specific track types (e.g. subtitles).
  13727. *
  13728. * @extends MenuButton
  13729. */
  13730. class TrackButton extends MenuButton {
  13731. /**
  13732. * Creates an instance of this class.
  13733. *
  13734. * @param { import('./player').default } player
  13735. * The `Player` that this class should be attached to.
  13736. *
  13737. * @param {Object} [options]
  13738. * The key/value store of player options.
  13739. */
  13740. constructor(player, options) {
  13741. const tracks = options.tracks;
  13742. super(player, options);
  13743. if (this.items.length <= 1) {
  13744. this.hide();
  13745. }
  13746. if (!tracks) {
  13747. return;
  13748. }
  13749. const updateHandler = bind_(this, this.update);
  13750. tracks.addEventListener('removetrack', updateHandler);
  13751. tracks.addEventListener('addtrack', updateHandler);
  13752. tracks.addEventListener('labelchange', updateHandler);
  13753. this.player_.on('ready', updateHandler);
  13754. this.player_.on('dispose', function () {
  13755. tracks.removeEventListener('removetrack', updateHandler);
  13756. tracks.removeEventListener('addtrack', updateHandler);
  13757. tracks.removeEventListener('labelchange', updateHandler);
  13758. });
  13759. }
  13760. }
  13761. Component$1.registerComponent('TrackButton', TrackButton);
  13762. /**
  13763. * @file menu-keys.js
  13764. */
  13765. /**
  13766. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  13767. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  13768. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  13769. *
  13770. * @typedef MenuKeys
  13771. * @array
  13772. */
  13773. const MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  13774. /**
  13775. * @file menu-item.js
  13776. */
  13777. /**
  13778. * The component for a menu item. `<li>`
  13779. *
  13780. * @extends ClickableComponent
  13781. */
  13782. class MenuItem extends ClickableComponent {
  13783. /**
  13784. * Creates an instance of the this class.
  13785. *
  13786. * @param { import('../player').default } player
  13787. * The `Player` that this class should be attached to.
  13788. *
  13789. * @param {Object} [options={}]
  13790. * The key/value store of player options.
  13791. *
  13792. */
  13793. constructor(player, options) {
  13794. super(player, options);
  13795. this.selectable = options.selectable;
  13796. this.isSelected_ = options.selected || false;
  13797. this.multiSelectable = options.multiSelectable;
  13798. this.selected(this.isSelected_);
  13799. if (this.selectable) {
  13800. if (this.multiSelectable) {
  13801. this.el_.setAttribute('role', 'menuitemcheckbox');
  13802. } else {
  13803. this.el_.setAttribute('role', 'menuitemradio');
  13804. }
  13805. } else {
  13806. this.el_.setAttribute('role', 'menuitem');
  13807. }
  13808. }
  13809. /**
  13810. * Create the `MenuItem's DOM element
  13811. *
  13812. * @param {string} [type=li]
  13813. * Element's node type, not actually used, always set to `li`.
  13814. *
  13815. * @param {Object} [props={}]
  13816. * An object of properties that should be set on the element
  13817. *
  13818. * @param {Object} [attrs={}]
  13819. * An object of attributes that should be set on the element
  13820. *
  13821. * @return {Element}
  13822. * The element that gets created.
  13823. */
  13824. createEl(type, props, attrs) {
  13825. // The control is textual, not just an icon
  13826. this.nonIconControl = true;
  13827. const el = super.createEl('li', Object.assign({
  13828. className: 'vjs-menu-item',
  13829. tabIndex: -1
  13830. }, props), attrs);
  13831. // swap icon with menu item text.
  13832. el.replaceChild(createEl('span', {
  13833. className: 'vjs-menu-item-text',
  13834. textContent: this.localize(this.options_.label)
  13835. }), el.querySelector('.vjs-icon-placeholder'));
  13836. return el;
  13837. }
  13838. /**
  13839. * Ignore keys which are used by the menu, but pass any other ones up. See
  13840. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13841. *
  13842. * @param {Event} event
  13843. * The `keydown` event that caused this function to be called.
  13844. *
  13845. * @listens keydown
  13846. */
  13847. handleKeyDown(event) {
  13848. if (!MenuKeys.some(key => keycode__default["default"].isEventKey(event, key))) {
  13849. // Pass keydown handling up for unused keys
  13850. super.handleKeyDown(event);
  13851. }
  13852. }
  13853. /**
  13854. * Any click on a `MenuItem` puts it into the selected state.
  13855. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13856. *
  13857. * @param {Event} event
  13858. * The `keydown`, `tap`, or `click` event that caused this function to be
  13859. * called.
  13860. *
  13861. * @listens tap
  13862. * @listens click
  13863. */
  13864. handleClick(event) {
  13865. this.selected(true);
  13866. }
  13867. /**
  13868. * Set the state for this menu item as selected or not.
  13869. *
  13870. * @param {boolean} selected
  13871. * if the menu item is selected or not
  13872. */
  13873. selected(selected) {
  13874. if (this.selectable) {
  13875. if (selected) {
  13876. this.addClass('vjs-selected');
  13877. this.el_.setAttribute('aria-checked', 'true');
  13878. // aria-checked isn't fully supported by browsers/screen readers,
  13879. // so indicate selected state to screen reader in the control text.
  13880. this.controlText(', selected');
  13881. this.isSelected_ = true;
  13882. } else {
  13883. this.removeClass('vjs-selected');
  13884. this.el_.setAttribute('aria-checked', 'false');
  13885. // Indicate un-selected state to screen reader
  13886. this.controlText('');
  13887. this.isSelected_ = false;
  13888. }
  13889. }
  13890. }
  13891. }
  13892. Component$1.registerComponent('MenuItem', MenuItem);
  13893. /**
  13894. * @file text-track-menu-item.js
  13895. */
  13896. /**
  13897. * The specific menu item type for selecting a language within a text track kind
  13898. *
  13899. * @extends MenuItem
  13900. */
  13901. class TextTrackMenuItem extends MenuItem {
  13902. /**
  13903. * Creates an instance of this class.
  13904. *
  13905. * @param { import('../../player').default } player
  13906. * The `Player` that this class should be attached to.
  13907. *
  13908. * @param {Object} [options]
  13909. * The key/value store of player options.
  13910. */
  13911. constructor(player, options) {
  13912. const track = options.track;
  13913. const tracks = player.textTracks();
  13914. // Modify options for parent MenuItem class's init.
  13915. options.label = track.label || track.language || 'Unknown';
  13916. options.selected = track.mode === 'showing';
  13917. super(player, options);
  13918. this.track = track;
  13919. // Determine the relevant kind(s) of tracks for this component and filter
  13920. // out empty kinds.
  13921. this.kinds = (options.kinds || [options.kind || this.track.kind]).filter(Boolean);
  13922. const changeHandler = (...args) => {
  13923. this.handleTracksChange.apply(this, args);
  13924. };
  13925. const selectedLanguageChangeHandler = (...args) => {
  13926. this.handleSelectedLanguageChange.apply(this, args);
  13927. };
  13928. player.on(['loadstart', 'texttrackchange'], changeHandler);
  13929. tracks.addEventListener('change', changeHandler);
  13930. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13931. this.on('dispose', function () {
  13932. player.off(['loadstart', 'texttrackchange'], changeHandler);
  13933. tracks.removeEventListener('change', changeHandler);
  13934. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  13935. });
  13936. // iOS7 doesn't dispatch change events to TextTrackLists when an
  13937. // associated track's mode changes. Without something like
  13938. // Object.observe() (also not present on iOS7), it's not
  13939. // possible to detect changes to the mode attribute and polyfill
  13940. // the change event. As a poor substitute, we manually dispatch
  13941. // change events whenever the controls modify the mode.
  13942. if (tracks.onchange === undefined) {
  13943. let event;
  13944. this.on(['tap', 'click'], function () {
  13945. if (typeof window__default["default"].Event !== 'object') {
  13946. // Android 2.3 throws an Illegal Constructor error for window.Event
  13947. try {
  13948. event = new window__default["default"].Event('change');
  13949. } catch (err) {
  13950. // continue regardless of error
  13951. }
  13952. }
  13953. if (!event) {
  13954. event = document__default["default"].createEvent('Event');
  13955. event.initEvent('change', true, true);
  13956. }
  13957. tracks.dispatchEvent(event);
  13958. });
  13959. }
  13960. // set the default state based on current tracks
  13961. this.handleTracksChange();
  13962. }
  13963. /**
  13964. * This gets called when an `TextTrackMenuItem` is "clicked". See
  13965. * {@link ClickableComponent} for more detailed information on what a click can be.
  13966. *
  13967. * @param {Event} event
  13968. * The `keydown`, `tap`, or `click` event that caused this function to be
  13969. * called.
  13970. *
  13971. * @listens tap
  13972. * @listens click
  13973. */
  13974. handleClick(event) {
  13975. const referenceTrack = this.track;
  13976. const tracks = this.player_.textTracks();
  13977. super.handleClick(event);
  13978. if (!tracks) {
  13979. return;
  13980. }
  13981. for (let i = 0; i < tracks.length; i++) {
  13982. const track = tracks[i];
  13983. // If the track from the text tracks list is not of the right kind,
  13984. // skip it. We do not want to affect tracks of incompatible kind(s).
  13985. if (this.kinds.indexOf(track.kind) === -1) {
  13986. continue;
  13987. }
  13988. // If this text track is the component's track and it is not showing,
  13989. // set it to showing.
  13990. if (track === referenceTrack) {
  13991. if (track.mode !== 'showing') {
  13992. track.mode = 'showing';
  13993. }
  13994. // If this text track is not the component's track and it is not
  13995. // disabled, set it to disabled.
  13996. } else if (track.mode !== 'disabled') {
  13997. track.mode = 'disabled';
  13998. }
  13999. }
  14000. }
  14001. /**
  14002. * Handle text track list change
  14003. *
  14004. * @param {Event} event
  14005. * The `change` event that caused this function to be called.
  14006. *
  14007. * @listens TextTrackList#change
  14008. */
  14009. handleTracksChange(event) {
  14010. const shouldBeSelected = this.track.mode === 'showing';
  14011. // Prevent redundant selected() calls because they may cause
  14012. // screen readers to read the appended control text unnecessarily
  14013. if (shouldBeSelected !== this.isSelected_) {
  14014. this.selected(shouldBeSelected);
  14015. }
  14016. }
  14017. handleSelectedLanguageChange(event) {
  14018. if (this.track.mode === 'showing') {
  14019. const selectedLanguage = this.player_.cache_.selectedLanguage;
  14020. // Don't replace the kind of track across the same language
  14021. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14022. return;
  14023. }
  14024. this.player_.cache_.selectedLanguage = {
  14025. enabled: true,
  14026. language: this.track.language,
  14027. kind: this.track.kind
  14028. };
  14029. }
  14030. }
  14031. dispose() {
  14032. // remove reference to track object on dispose
  14033. this.track = null;
  14034. super.dispose();
  14035. }
  14036. }
  14037. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14038. /**
  14039. * @file off-text-track-menu-item.js
  14040. */
  14041. /**
  14042. * A special menu item for turning of a specific type of text track
  14043. *
  14044. * @extends TextTrackMenuItem
  14045. */
  14046. class OffTextTrackMenuItem extends TextTrackMenuItem {
  14047. /**
  14048. * Creates an instance of this class.
  14049. *
  14050. * @param { import('../../player').default } player
  14051. * The `Player` that this class should be attached to.
  14052. *
  14053. * @param {Object} [options]
  14054. * The key/value store of player options.
  14055. */
  14056. constructor(player, options) {
  14057. // Create pseudo track info
  14058. // Requires options['kind']
  14059. options.track = {
  14060. player,
  14061. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14062. // since they are now stored in the `kinds` property of all instances of
  14063. // TextTrackMenuItem, but this will remain for backwards compatibility
  14064. kind: options.kind,
  14065. kinds: options.kinds,
  14066. default: false,
  14067. mode: 'disabled'
  14068. };
  14069. if (!options.kinds) {
  14070. options.kinds = [options.kind];
  14071. }
  14072. if (options.label) {
  14073. options.track.label = options.label;
  14074. } else {
  14075. options.track.label = options.kinds.join(' and ') + ' off';
  14076. }
  14077. // MenuItem is selectable
  14078. options.selectable = true;
  14079. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14080. options.multiSelectable = false;
  14081. super(player, options);
  14082. }
  14083. /**
  14084. * Handle text track change
  14085. *
  14086. * @param {Event} event
  14087. * The event that caused this function to run
  14088. */
  14089. handleTracksChange(event) {
  14090. const tracks = this.player().textTracks();
  14091. let shouldBeSelected = true;
  14092. for (let i = 0, l = tracks.length; i < l; i++) {
  14093. const track = tracks[i];
  14094. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14095. shouldBeSelected = false;
  14096. break;
  14097. }
  14098. }
  14099. // Prevent redundant selected() calls because they may cause
  14100. // screen readers to read the appended control text unnecessarily
  14101. if (shouldBeSelected !== this.isSelected_) {
  14102. this.selected(shouldBeSelected);
  14103. }
  14104. }
  14105. handleSelectedLanguageChange(event) {
  14106. const tracks = this.player().textTracks();
  14107. let allHidden = true;
  14108. for (let i = 0, l = tracks.length; i < l; i++) {
  14109. const track = tracks[i];
  14110. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14111. allHidden = false;
  14112. break;
  14113. }
  14114. }
  14115. if (allHidden) {
  14116. this.player_.cache_.selectedLanguage = {
  14117. enabled: false
  14118. };
  14119. }
  14120. }
  14121. /**
  14122. * Update control text and label on languagechange
  14123. */
  14124. handleLanguagechange() {
  14125. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.label);
  14126. super.handleLanguagechange();
  14127. }
  14128. }
  14129. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14130. /**
  14131. * @file text-track-button.js
  14132. */
  14133. /**
  14134. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14135. *
  14136. * @extends MenuButton
  14137. */
  14138. class TextTrackButton extends TrackButton {
  14139. /**
  14140. * Creates an instance of this class.
  14141. *
  14142. * @param { import('../../player').default } player
  14143. * The `Player` that this class should be attached to.
  14144. *
  14145. * @param {Object} [options={}]
  14146. * The key/value store of player options.
  14147. */
  14148. constructor(player, options = {}) {
  14149. options.tracks = player.textTracks();
  14150. super(player, options);
  14151. }
  14152. /**
  14153. * Create a menu item for each text track
  14154. *
  14155. * @param {TextTrackMenuItem[]} [items=[]]
  14156. * Existing array of items to use during creation
  14157. *
  14158. * @return {TextTrackMenuItem[]}
  14159. * Array of menu items that were created
  14160. */
  14161. createItems(items = [], TrackMenuItem = TextTrackMenuItem) {
  14162. // Label is an override for the [track] off label
  14163. // USed to localise captions/subtitles
  14164. let label;
  14165. if (this.label_) {
  14166. label = `${this.label_} off`;
  14167. }
  14168. // Add an OFF menu item to turn all tracks off
  14169. items.push(new OffTextTrackMenuItem(this.player_, {
  14170. kinds: this.kinds_,
  14171. kind: this.kind_,
  14172. label
  14173. }));
  14174. this.hideThreshold_ += 1;
  14175. const tracks = this.player_.textTracks();
  14176. if (!Array.isArray(this.kinds_)) {
  14177. this.kinds_ = [this.kind_];
  14178. }
  14179. for (let i = 0; i < tracks.length; i++) {
  14180. const track = tracks[i];
  14181. // only add tracks that are of an appropriate kind and have a label
  14182. if (this.kinds_.indexOf(track.kind) > -1) {
  14183. const item = new TrackMenuItem(this.player_, {
  14184. track,
  14185. kinds: this.kinds_,
  14186. kind: this.kind_,
  14187. // MenuItem is selectable
  14188. selectable: true,
  14189. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14190. multiSelectable: false
  14191. });
  14192. item.addClass(`vjs-${track.kind}-menu-item`);
  14193. items.push(item);
  14194. }
  14195. }
  14196. return items;
  14197. }
  14198. }
  14199. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  14200. /**
  14201. * @file chapters-track-menu-item.js
  14202. */
  14203. /**
  14204. * The chapter track menu item
  14205. *
  14206. * @extends MenuItem
  14207. */
  14208. class ChaptersTrackMenuItem extends MenuItem {
  14209. /**
  14210. * Creates an instance of this class.
  14211. *
  14212. * @param { import('../../player').default } player
  14213. * The `Player` that this class should be attached to.
  14214. *
  14215. * @param {Object} [options]
  14216. * The key/value store of player options.
  14217. */
  14218. constructor(player, options) {
  14219. const track = options.track;
  14220. const cue = options.cue;
  14221. const currentTime = player.currentTime();
  14222. // Modify options for parent MenuItem class's init.
  14223. options.selectable = true;
  14224. options.multiSelectable = false;
  14225. options.label = cue.text;
  14226. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  14227. super(player, options);
  14228. this.track = track;
  14229. this.cue = cue;
  14230. }
  14231. /**
  14232. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  14233. * {@link ClickableComponent} for more detailed information on what a click can be.
  14234. *
  14235. * @param {Event} [event]
  14236. * The `keydown`, `tap`, or `click` event that caused this function to be
  14237. * called.
  14238. *
  14239. * @listens tap
  14240. * @listens click
  14241. */
  14242. handleClick(event) {
  14243. super.handleClick();
  14244. this.player_.currentTime(this.cue.startTime);
  14245. }
  14246. }
  14247. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  14248. /**
  14249. * @file chapters-button.js
  14250. */
  14251. /**
  14252. * The button component for toggling and selecting chapters
  14253. * Chapters act much differently than other text tracks
  14254. * Cues are navigation vs. other tracks of alternative languages
  14255. *
  14256. * @extends TextTrackButton
  14257. */
  14258. class ChaptersButton extends TextTrackButton {
  14259. /**
  14260. * Creates an instance of this class.
  14261. *
  14262. * @param { import('../../player').default } player
  14263. * The `Player` that this class should be attached to.
  14264. *
  14265. * @param {Object} [options]
  14266. * The key/value store of player options.
  14267. *
  14268. * @param {Function} [ready]
  14269. * The function to call when this function is ready.
  14270. */
  14271. constructor(player, options, ready) {
  14272. super(player, options, ready);
  14273. this.selectCurrentItem_ = () => {
  14274. this.items.forEach(item => {
  14275. item.selected(this.track_.activeCues[0] === item.cue);
  14276. });
  14277. };
  14278. }
  14279. /**
  14280. * Builds the default DOM `className`.
  14281. *
  14282. * @return {string}
  14283. * The DOM `className` for this object.
  14284. */
  14285. buildCSSClass() {
  14286. return `vjs-chapters-button ${super.buildCSSClass()}`;
  14287. }
  14288. buildWrapperCSSClass() {
  14289. return `vjs-chapters-button ${super.buildWrapperCSSClass()}`;
  14290. }
  14291. /**
  14292. * Update the menu based on the current state of its items.
  14293. *
  14294. * @param {Event} [event]
  14295. * An event that triggered this function to run.
  14296. *
  14297. * @listens TextTrackList#addtrack
  14298. * @listens TextTrackList#removetrack
  14299. * @listens TextTrackList#change
  14300. */
  14301. update(event) {
  14302. if (event && event.track && event.track.kind !== 'chapters') {
  14303. return;
  14304. }
  14305. const track = this.findChaptersTrack();
  14306. if (track !== this.track_) {
  14307. this.setTrack(track);
  14308. super.update();
  14309. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  14310. // Update the menu initially or if the number of cues has changed since set
  14311. super.update();
  14312. }
  14313. }
  14314. /**
  14315. * Set the currently selected track for the chapters button.
  14316. *
  14317. * @param {TextTrack} track
  14318. * The new track to select. Nothing will change if this is the currently selected
  14319. * track.
  14320. */
  14321. setTrack(track) {
  14322. if (this.track_ === track) {
  14323. return;
  14324. }
  14325. if (!this.updateHandler_) {
  14326. this.updateHandler_ = this.update.bind(this);
  14327. }
  14328. // here this.track_ refers to the old track instance
  14329. if (this.track_) {
  14330. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14331. if (remoteTextTrackEl) {
  14332. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  14333. }
  14334. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  14335. this.track_ = null;
  14336. }
  14337. this.track_ = track;
  14338. // here this.track_ refers to the new track instance
  14339. if (this.track_) {
  14340. this.track_.mode = 'hidden';
  14341. const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14342. if (remoteTextTrackEl) {
  14343. remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  14344. }
  14345. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  14346. }
  14347. }
  14348. /**
  14349. * Find the track object that is currently in use by this ChaptersButton
  14350. *
  14351. * @return {TextTrack|undefined}
  14352. * The current track or undefined if none was found.
  14353. */
  14354. findChaptersTrack() {
  14355. const tracks = this.player_.textTracks() || [];
  14356. for (let i = tracks.length - 1; i >= 0; i--) {
  14357. // We will always choose the last track as our chaptersTrack
  14358. const track = tracks[i];
  14359. if (track.kind === this.kind_) {
  14360. return track;
  14361. }
  14362. }
  14363. }
  14364. /**
  14365. * Get the caption for the ChaptersButton based on the track label. This will also
  14366. * use the current tracks localized kind as a fallback if a label does not exist.
  14367. *
  14368. * @return {string}
  14369. * The tracks current label or the localized track kind.
  14370. */
  14371. getMenuCaption() {
  14372. if (this.track_ && this.track_.label) {
  14373. return this.track_.label;
  14374. }
  14375. return this.localize(toTitleCase$1(this.kind_));
  14376. }
  14377. /**
  14378. * Create menu from chapter track
  14379. *
  14380. * @return { import('../../menu/menu').default }
  14381. * New menu for the chapter buttons
  14382. */
  14383. createMenu() {
  14384. this.options_.title = this.getMenuCaption();
  14385. return super.createMenu();
  14386. }
  14387. /**
  14388. * Create a menu item for each text track
  14389. *
  14390. * @return { import('./text-track-menu-item').default[] }
  14391. * Array of menu items
  14392. */
  14393. createItems() {
  14394. const items = [];
  14395. if (!this.track_) {
  14396. return items;
  14397. }
  14398. const cues = this.track_.cues;
  14399. if (!cues) {
  14400. return items;
  14401. }
  14402. for (let i = 0, l = cues.length; i < l; i++) {
  14403. const cue = cues[i];
  14404. const mi = new ChaptersTrackMenuItem(this.player_, {
  14405. track: this.track_,
  14406. cue
  14407. });
  14408. items.push(mi);
  14409. }
  14410. return items;
  14411. }
  14412. }
  14413. /**
  14414. * `kind` of TextTrack to look for to associate it with this menu.
  14415. *
  14416. * @type {string}
  14417. * @private
  14418. */
  14419. ChaptersButton.prototype.kind_ = 'chapters';
  14420. /**
  14421. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  14422. *
  14423. * @type {string}
  14424. * @protected
  14425. */
  14426. ChaptersButton.prototype.controlText_ = 'Chapters';
  14427. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  14428. /**
  14429. * @file descriptions-button.js
  14430. */
  14431. /**
  14432. * The button component for toggling and selecting descriptions
  14433. *
  14434. * @extends TextTrackButton
  14435. */
  14436. class DescriptionsButton extends TextTrackButton {
  14437. /**
  14438. * Creates an instance of this class.
  14439. *
  14440. * @param { import('../../player').default } player
  14441. * The `Player` that this class should be attached to.
  14442. *
  14443. * @param {Object} [options]
  14444. * The key/value store of player options.
  14445. *
  14446. * @param {Function} [ready]
  14447. * The function to call when this component is ready.
  14448. */
  14449. constructor(player, options, ready) {
  14450. super(player, options, ready);
  14451. const tracks = player.textTracks();
  14452. const changeHandler = bind_(this, this.handleTracksChange);
  14453. tracks.addEventListener('change', changeHandler);
  14454. this.on('dispose', function () {
  14455. tracks.removeEventListener('change', changeHandler);
  14456. });
  14457. }
  14458. /**
  14459. * Handle text track change
  14460. *
  14461. * @param {Event} event
  14462. * The event that caused this function to run
  14463. *
  14464. * @listens TextTrackList#change
  14465. */
  14466. handleTracksChange(event) {
  14467. const tracks = this.player().textTracks();
  14468. let disabled = false;
  14469. // Check whether a track of a different kind is showing
  14470. for (let i = 0, l = tracks.length; i < l; i++) {
  14471. const track = tracks[i];
  14472. if (track.kind !== this.kind_ && track.mode === 'showing') {
  14473. disabled = true;
  14474. break;
  14475. }
  14476. }
  14477. // If another track is showing, disable this menu button
  14478. if (disabled) {
  14479. this.disable();
  14480. } else {
  14481. this.enable();
  14482. }
  14483. }
  14484. /**
  14485. * Builds the default DOM `className`.
  14486. *
  14487. * @return {string}
  14488. * The DOM `className` for this object.
  14489. */
  14490. buildCSSClass() {
  14491. return `vjs-descriptions-button ${super.buildCSSClass()}`;
  14492. }
  14493. buildWrapperCSSClass() {
  14494. return `vjs-descriptions-button ${super.buildWrapperCSSClass()}`;
  14495. }
  14496. }
  14497. /**
  14498. * `kind` of TextTrack to look for to associate it with this menu.
  14499. *
  14500. * @type {string}
  14501. * @private
  14502. */
  14503. DescriptionsButton.prototype.kind_ = 'descriptions';
  14504. /**
  14505. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  14506. *
  14507. * @type {string}
  14508. * @protected
  14509. */
  14510. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  14511. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  14512. /**
  14513. * @file subtitles-button.js
  14514. */
  14515. /**
  14516. * The button component for toggling and selecting subtitles
  14517. *
  14518. * @extends TextTrackButton
  14519. */
  14520. class SubtitlesButton extends TextTrackButton {
  14521. /**
  14522. * Creates an instance of this class.
  14523. *
  14524. * @param { import('../../player').default } player
  14525. * The `Player` that this class should be attached to.
  14526. *
  14527. * @param {Object} [options]
  14528. * The key/value store of player options.
  14529. *
  14530. * @param {Function} [ready]
  14531. * The function to call when this component is ready.
  14532. */
  14533. constructor(player, options, ready) {
  14534. super(player, options, ready);
  14535. }
  14536. /**
  14537. * Builds the default DOM `className`.
  14538. *
  14539. * @return {string}
  14540. * The DOM `className` for this object.
  14541. */
  14542. buildCSSClass() {
  14543. return `vjs-subtitles-button ${super.buildCSSClass()}`;
  14544. }
  14545. buildWrapperCSSClass() {
  14546. return `vjs-subtitles-button ${super.buildWrapperCSSClass()}`;
  14547. }
  14548. }
  14549. /**
  14550. * `kind` of TextTrack to look for to associate it with this menu.
  14551. *
  14552. * @type {string}
  14553. * @private
  14554. */
  14555. SubtitlesButton.prototype.kind_ = 'subtitles';
  14556. /**
  14557. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  14558. *
  14559. * @type {string}
  14560. * @protected
  14561. */
  14562. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  14563. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  14564. /**
  14565. * @file caption-settings-menu-item.js
  14566. */
  14567. /**
  14568. * The menu item for caption track settings menu
  14569. *
  14570. * @extends TextTrackMenuItem
  14571. */
  14572. class CaptionSettingsMenuItem extends TextTrackMenuItem {
  14573. /**
  14574. * Creates an instance of this class.
  14575. *
  14576. * @param { import('../../player').default } player
  14577. * The `Player` that this class should be attached to.
  14578. *
  14579. * @param {Object} [options]
  14580. * The key/value store of player options.
  14581. */
  14582. constructor(player, options) {
  14583. options.track = {
  14584. player,
  14585. kind: options.kind,
  14586. label: options.kind + ' settings',
  14587. selectable: false,
  14588. default: false,
  14589. mode: 'disabled'
  14590. };
  14591. // CaptionSettingsMenuItem has no concept of 'selected'
  14592. options.selectable = false;
  14593. options.name = 'CaptionSettingsMenuItem';
  14594. super(player, options);
  14595. this.addClass('vjs-texttrack-settings');
  14596. this.controlText(', opens ' + options.kind + ' settings dialog');
  14597. }
  14598. /**
  14599. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  14600. * {@link ClickableComponent} for more detailed information on what a click can be.
  14601. *
  14602. * @param {Event} [event]
  14603. * The `keydown`, `tap`, or `click` event that caused this function to be
  14604. * called.
  14605. *
  14606. * @listens tap
  14607. * @listens click
  14608. */
  14609. handleClick(event) {
  14610. this.player().getChild('textTrackSettings').open();
  14611. }
  14612. /**
  14613. * Update control text and label on languagechange
  14614. */
  14615. handleLanguagechange() {
  14616. this.$('.vjs-menu-item-text').textContent = this.player_.localize(this.options_.kind + ' settings');
  14617. super.handleLanguagechange();
  14618. }
  14619. }
  14620. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  14621. /**
  14622. * @file captions-button.js
  14623. */
  14624. /**
  14625. * The button component for toggling and selecting captions
  14626. *
  14627. * @extends TextTrackButton
  14628. */
  14629. class CaptionsButton extends TextTrackButton {
  14630. /**
  14631. * Creates an instance of this class.
  14632. *
  14633. * @param { import('../../player').default } player
  14634. * The `Player` that this class should be attached to.
  14635. *
  14636. * @param {Object} [options]
  14637. * The key/value store of player options.
  14638. *
  14639. * @param {Function} [ready]
  14640. * The function to call when this component is ready.
  14641. */
  14642. constructor(player, options, ready) {
  14643. super(player, options, ready);
  14644. }
  14645. /**
  14646. * Builds the default DOM `className`.
  14647. *
  14648. * @return {string}
  14649. * The DOM `className` for this object.
  14650. */
  14651. buildCSSClass() {
  14652. return `vjs-captions-button ${super.buildCSSClass()}`;
  14653. }
  14654. buildWrapperCSSClass() {
  14655. return `vjs-captions-button ${super.buildWrapperCSSClass()}`;
  14656. }
  14657. /**
  14658. * Create caption menu items
  14659. *
  14660. * @return {CaptionSettingsMenuItem[]}
  14661. * The array of current menu items.
  14662. */
  14663. createItems() {
  14664. const items = [];
  14665. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14666. items.push(new CaptionSettingsMenuItem(this.player_, {
  14667. kind: this.kind_
  14668. }));
  14669. this.hideThreshold_ += 1;
  14670. }
  14671. return super.createItems(items);
  14672. }
  14673. }
  14674. /**
  14675. * `kind` of TextTrack to look for to associate it with this menu.
  14676. *
  14677. * @type {string}
  14678. * @private
  14679. */
  14680. CaptionsButton.prototype.kind_ = 'captions';
  14681. /**
  14682. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  14683. *
  14684. * @type {string}
  14685. * @protected
  14686. */
  14687. CaptionsButton.prototype.controlText_ = 'Captions';
  14688. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  14689. /**
  14690. * @file subs-caps-menu-item.js
  14691. */
  14692. /**
  14693. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  14694. * in the SubsCapsMenu.
  14695. *
  14696. * @extends TextTrackMenuItem
  14697. */
  14698. class SubsCapsMenuItem extends TextTrackMenuItem {
  14699. createEl(type, props, attrs) {
  14700. const el = super.createEl(type, props, attrs);
  14701. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14702. if (this.options_.track.kind === 'captions') {
  14703. parentSpan.appendChild(createEl('span', {
  14704. className: 'vjs-icon-placeholder'
  14705. }, {
  14706. 'aria-hidden': true
  14707. }));
  14708. parentSpan.appendChild(createEl('span', {
  14709. className: 'vjs-control-text',
  14710. // space added as the text will visually flow with the
  14711. // label
  14712. textContent: ` ${this.localize('Captions')}`
  14713. }));
  14714. }
  14715. return el;
  14716. }
  14717. }
  14718. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  14719. /**
  14720. * @file sub-caps-button.js
  14721. */
  14722. /**
  14723. * The button component for toggling and selecting captions and/or subtitles
  14724. *
  14725. * @extends TextTrackButton
  14726. */
  14727. class SubsCapsButton extends TextTrackButton {
  14728. /**
  14729. * Creates an instance of this class.
  14730. *
  14731. * @param { import('../../player').default } player
  14732. * The `Player` that this class should be attached to.
  14733. *
  14734. * @param {Object} [options]
  14735. * The key/value store of player options.
  14736. *
  14737. * @param {Function} [ready]
  14738. * The function to call when this component is ready.
  14739. */
  14740. constructor(player, options = {}) {
  14741. super(player, options);
  14742. // Although North America uses "captions" in most cases for
  14743. // "captions and subtitles" other locales use "subtitles"
  14744. this.label_ = 'subtitles';
  14745. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(this.player_.language_) > -1) {
  14746. this.label_ = 'captions';
  14747. }
  14748. this.menuButton_.controlText(toTitleCase$1(this.label_));
  14749. }
  14750. /**
  14751. * Builds the default DOM `className`.
  14752. *
  14753. * @return {string}
  14754. * The DOM `className` for this object.
  14755. */
  14756. buildCSSClass() {
  14757. return `vjs-subs-caps-button ${super.buildCSSClass()}`;
  14758. }
  14759. buildWrapperCSSClass() {
  14760. return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
  14761. }
  14762. /**
  14763. * Create caption/subtitles menu items
  14764. *
  14765. * @return {CaptionSettingsMenuItem[]}
  14766. * The array of current menu items.
  14767. */
  14768. createItems() {
  14769. let items = [];
  14770. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14771. items.push(new CaptionSettingsMenuItem(this.player_, {
  14772. kind: this.label_
  14773. }));
  14774. this.hideThreshold_ += 1;
  14775. }
  14776. items = super.createItems(items, SubsCapsMenuItem);
  14777. return items;
  14778. }
  14779. }
  14780. /**
  14781. * `kind`s of TextTrack to look for to associate it with this menu.
  14782. *
  14783. * @type {array}
  14784. * @private
  14785. */
  14786. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  14787. /**
  14788. * The text that should display over the `SubsCapsButton`s controls.
  14789. *
  14790. *
  14791. * @type {string}
  14792. * @protected
  14793. */
  14794. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  14795. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  14796. /**
  14797. * @file audio-track-menu-item.js
  14798. */
  14799. /**
  14800. * An {@link AudioTrack} {@link MenuItem}
  14801. *
  14802. * @extends MenuItem
  14803. */
  14804. class AudioTrackMenuItem extends MenuItem {
  14805. /**
  14806. * Creates an instance of this class.
  14807. *
  14808. * @param { import('../../player').default } player
  14809. * The `Player` that this class should be attached to.
  14810. *
  14811. * @param {Object} [options]
  14812. * The key/value store of player options.
  14813. */
  14814. constructor(player, options) {
  14815. const track = options.track;
  14816. const tracks = player.audioTracks();
  14817. // Modify options for parent MenuItem class's init.
  14818. options.label = track.label || track.language || 'Unknown';
  14819. options.selected = track.enabled;
  14820. super(player, options);
  14821. this.track = track;
  14822. this.addClass(`vjs-${track.kind}-menu-item`);
  14823. const changeHandler = (...args) => {
  14824. this.handleTracksChange.apply(this, args);
  14825. };
  14826. tracks.addEventListener('change', changeHandler);
  14827. this.on('dispose', () => {
  14828. tracks.removeEventListener('change', changeHandler);
  14829. });
  14830. }
  14831. createEl(type, props, attrs) {
  14832. const el = super.createEl(type, props, attrs);
  14833. const parentSpan = el.querySelector('.vjs-menu-item-text');
  14834. if (this.options_.track.kind === 'main-desc') {
  14835. parentSpan.appendChild(createEl('span', {
  14836. className: 'vjs-icon-placeholder'
  14837. }, {
  14838. 'aria-hidden': true
  14839. }));
  14840. parentSpan.appendChild(createEl('span', {
  14841. className: 'vjs-control-text',
  14842. textContent: ' ' + this.localize('Descriptions')
  14843. }));
  14844. }
  14845. return el;
  14846. }
  14847. /**
  14848. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  14849. * for more detailed information on what a click can be.
  14850. *
  14851. * @param {Event} [event]
  14852. * The `keydown`, `tap`, or `click` event that caused this function to be
  14853. * called.
  14854. *
  14855. * @listens tap
  14856. * @listens click
  14857. */
  14858. handleClick(event) {
  14859. super.handleClick(event);
  14860. // the audio track list will automatically toggle other tracks
  14861. // off for us.
  14862. this.track.enabled = true;
  14863. // when native audio tracks are used, we want to make sure that other tracks are turned off
  14864. if (this.player_.tech_.featuresNativeAudioTracks) {
  14865. const tracks = this.player_.audioTracks();
  14866. for (let i = 0; i < tracks.length; i++) {
  14867. const track = tracks[i];
  14868. // skip the current track since we enabled it above
  14869. if (track === this.track) {
  14870. continue;
  14871. }
  14872. track.enabled = track === this.track;
  14873. }
  14874. }
  14875. }
  14876. /**
  14877. * Handle any {@link AudioTrack} change.
  14878. *
  14879. * @param {Event} [event]
  14880. * The {@link AudioTrackList#change} event that caused this to run.
  14881. *
  14882. * @listens AudioTrackList#change
  14883. */
  14884. handleTracksChange(event) {
  14885. this.selected(this.track.enabled);
  14886. }
  14887. }
  14888. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  14889. /**
  14890. * @file audio-track-button.js
  14891. */
  14892. /**
  14893. * The base class for buttons that toggle specific {@link AudioTrack} types.
  14894. *
  14895. * @extends TrackButton
  14896. */
  14897. class AudioTrackButton extends TrackButton {
  14898. /**
  14899. * Creates an instance of this class.
  14900. *
  14901. * @param {Player} player
  14902. * The `Player` that this class should be attached to.
  14903. *
  14904. * @param {Object} [options={}]
  14905. * The key/value store of player options.
  14906. */
  14907. constructor(player, options = {}) {
  14908. options.tracks = player.audioTracks();
  14909. super(player, options);
  14910. }
  14911. /**
  14912. * Builds the default DOM `className`.
  14913. *
  14914. * @return {string}
  14915. * The DOM `className` for this object.
  14916. */
  14917. buildCSSClass() {
  14918. return `vjs-audio-button ${super.buildCSSClass()}`;
  14919. }
  14920. buildWrapperCSSClass() {
  14921. return `vjs-audio-button ${super.buildWrapperCSSClass()}`;
  14922. }
  14923. /**
  14924. * Create a menu item for each audio track
  14925. *
  14926. * @param {AudioTrackMenuItem[]} [items=[]]
  14927. * An array of existing menu items to use.
  14928. *
  14929. * @return {AudioTrackMenuItem[]}
  14930. * An array of menu items
  14931. */
  14932. createItems(items = []) {
  14933. // if there's only one audio track, there no point in showing it
  14934. this.hideThreshold_ = 1;
  14935. const tracks = this.player_.audioTracks();
  14936. for (let i = 0; i < tracks.length; i++) {
  14937. const track = tracks[i];
  14938. items.push(new AudioTrackMenuItem(this.player_, {
  14939. track,
  14940. // MenuItem is selectable
  14941. selectable: true,
  14942. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14943. multiSelectable: false
  14944. }));
  14945. }
  14946. return items;
  14947. }
  14948. }
  14949. /**
  14950. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  14951. *
  14952. * @type {string}
  14953. * @protected
  14954. */
  14955. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  14956. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  14957. /**
  14958. * @file playback-rate-menu-item.js
  14959. */
  14960. /**
  14961. * The specific menu item type for selecting a playback rate.
  14962. *
  14963. * @extends MenuItem
  14964. */
  14965. class PlaybackRateMenuItem extends MenuItem {
  14966. /**
  14967. * Creates an instance of this class.
  14968. *
  14969. * @param { import('../../player').default } player
  14970. * The `Player` that this class should be attached to.
  14971. *
  14972. * @param {Object} [options]
  14973. * The key/value store of player options.
  14974. */
  14975. constructor(player, options) {
  14976. const label = options.rate;
  14977. const rate = parseFloat(label, 10);
  14978. // Modify options for parent MenuItem class's init.
  14979. options.label = label;
  14980. options.selected = rate === player.playbackRate();
  14981. options.selectable = true;
  14982. options.multiSelectable = false;
  14983. super(player, options);
  14984. this.label = label;
  14985. this.rate = rate;
  14986. this.on(player, 'ratechange', e => this.update(e));
  14987. }
  14988. /**
  14989. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  14990. * {@link ClickableComponent} for more detailed information on what a click can be.
  14991. *
  14992. * @param {Event} [event]
  14993. * The `keydown`, `tap`, or `click` event that caused this function to be
  14994. * called.
  14995. *
  14996. * @listens tap
  14997. * @listens click
  14998. */
  14999. handleClick(event) {
  15000. super.handleClick();
  15001. this.player().playbackRate(this.rate);
  15002. }
  15003. /**
  15004. * Update the PlaybackRateMenuItem when the playbackrate changes.
  15005. *
  15006. * @param {Event} [event]
  15007. * The `ratechange` event that caused this function to run.
  15008. *
  15009. * @listens Player#ratechange
  15010. */
  15011. update(event) {
  15012. this.selected(this.player().playbackRate() === this.rate);
  15013. }
  15014. }
  15015. /**
  15016. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  15017. *
  15018. * @type {string}
  15019. * @private
  15020. */
  15021. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15022. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15023. /**
  15024. * @file playback-rate-menu-button.js
  15025. */
  15026. /**
  15027. * The component for controlling the playback rate.
  15028. *
  15029. * @extends MenuButton
  15030. */
  15031. class PlaybackRateMenuButton extends MenuButton {
  15032. /**
  15033. * Creates an instance of this class.
  15034. *
  15035. * @param { import('../../player').default } player
  15036. * The `Player` that this class should be attached to.
  15037. *
  15038. * @param {Object} [options]
  15039. * The key/value store of player options.
  15040. */
  15041. constructor(player, options) {
  15042. super(player, options);
  15043. this.menuButton_.el_.setAttribute('aria-describedby', this.labelElId_);
  15044. this.updateVisibility();
  15045. this.updateLabel();
  15046. this.on(player, 'loadstart', e => this.updateVisibility(e));
  15047. this.on(player, 'ratechange', e => this.updateLabel(e));
  15048. this.on(player, 'playbackrateschange', e => this.handlePlaybackRateschange(e));
  15049. }
  15050. /**
  15051. * Create the `Component`'s DOM element
  15052. *
  15053. * @return {Element}
  15054. * The element that was created.
  15055. */
  15056. createEl() {
  15057. const el = super.createEl();
  15058. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15059. this.labelEl_ = createEl('div', {
  15060. className: 'vjs-playback-rate-value',
  15061. id: this.labelElId_,
  15062. textContent: '1x'
  15063. });
  15064. el.appendChild(this.labelEl_);
  15065. return el;
  15066. }
  15067. dispose() {
  15068. this.labelEl_ = null;
  15069. super.dispose();
  15070. }
  15071. /**
  15072. * Builds the default DOM `className`.
  15073. *
  15074. * @return {string}
  15075. * The DOM `className` for this object.
  15076. */
  15077. buildCSSClass() {
  15078. return `vjs-playback-rate ${super.buildCSSClass()}`;
  15079. }
  15080. buildWrapperCSSClass() {
  15081. return `vjs-playback-rate ${super.buildWrapperCSSClass()}`;
  15082. }
  15083. /**
  15084. * Create the list of menu items. Specific to each subclass.
  15085. *
  15086. */
  15087. createItems() {
  15088. const rates = this.playbackRates();
  15089. const items = [];
  15090. for (let i = rates.length - 1; i >= 0; i--) {
  15091. items.push(new PlaybackRateMenuItem(this.player(), {
  15092. rate: rates[i] + 'x'
  15093. }));
  15094. }
  15095. return items;
  15096. }
  15097. /**
  15098. * On playbackrateschange, update the menu to account for the new items.
  15099. *
  15100. * @listens Player#playbackrateschange
  15101. */
  15102. handlePlaybackRateschange(event) {
  15103. this.update();
  15104. }
  15105. /**
  15106. * Get possible playback rates
  15107. *
  15108. * @return {Array}
  15109. * All possible playback rates
  15110. */
  15111. playbackRates() {
  15112. const player = this.player();
  15113. return player.playbackRates && player.playbackRates() || [];
  15114. }
  15115. /**
  15116. * Get whether playback rates is supported by the tech
  15117. * and an array of playback rates exists
  15118. *
  15119. * @return {boolean}
  15120. * Whether changing playback rate is supported
  15121. */
  15122. playbackRateSupported() {
  15123. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15124. }
  15125. /**
  15126. * Hide playback rate controls when they're no playback rate options to select
  15127. *
  15128. * @param {Event} [event]
  15129. * The event that caused this function to run.
  15130. *
  15131. * @listens Player#loadstart
  15132. */
  15133. updateVisibility(event) {
  15134. if (this.playbackRateSupported()) {
  15135. this.removeClass('vjs-hidden');
  15136. } else {
  15137. this.addClass('vjs-hidden');
  15138. }
  15139. }
  15140. /**
  15141. * Update button label when rate changed
  15142. *
  15143. * @param {Event} [event]
  15144. * The event that caused this function to run.
  15145. *
  15146. * @listens Player#ratechange
  15147. */
  15148. updateLabel(event) {
  15149. if (this.playbackRateSupported()) {
  15150. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  15151. }
  15152. }
  15153. }
  15154. /**
  15155. * The text that should display over the `PlaybackRateMenuButton`s controls.
  15156. *
  15157. * Added for localization.
  15158. *
  15159. * @type {string}
  15160. * @protected
  15161. */
  15162. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  15163. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  15164. /**
  15165. * @file spacer.js
  15166. */
  15167. /**
  15168. * Just an empty spacer element that can be used as an append point for plugins, etc.
  15169. * Also can be used to create space between elements when necessary.
  15170. *
  15171. * @extends Component
  15172. */
  15173. class Spacer extends Component$1 {
  15174. /**
  15175. * Builds the default DOM `className`.
  15176. *
  15177. * @return {string}
  15178. * The DOM `className` for this object.
  15179. */
  15180. buildCSSClass() {
  15181. return `vjs-spacer ${super.buildCSSClass()}`;
  15182. }
  15183. /**
  15184. * Create the `Component`'s DOM element
  15185. *
  15186. * @return {Element}
  15187. * The element that was created.
  15188. */
  15189. createEl(tag = 'div', props = {}, attributes = {}) {
  15190. if (!props.className) {
  15191. props.className = this.buildCSSClass();
  15192. }
  15193. return super.createEl(tag, props, attributes);
  15194. }
  15195. }
  15196. Component$1.registerComponent('Spacer', Spacer);
  15197. /**
  15198. * @file custom-control-spacer.js
  15199. */
  15200. /**
  15201. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  15202. *
  15203. * @extends Spacer
  15204. */
  15205. class CustomControlSpacer extends Spacer {
  15206. /**
  15207. * Builds the default DOM `className`.
  15208. *
  15209. * @return {string}
  15210. * The DOM `className` for this object.
  15211. */
  15212. buildCSSClass() {
  15213. return `vjs-custom-control-spacer ${super.buildCSSClass()}`;
  15214. }
  15215. /**
  15216. * Create the `Component`'s DOM element
  15217. *
  15218. * @return {Element}
  15219. * The element that was created.
  15220. */
  15221. createEl() {
  15222. return super.createEl('div', {
  15223. className: this.buildCSSClass(),
  15224. // No-flex/table-cell mode requires there be some content
  15225. // in the cell to fill the remaining space of the table.
  15226. textContent: '\u00a0'
  15227. });
  15228. }
  15229. }
  15230. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  15231. /**
  15232. * @file control-bar.js
  15233. */
  15234. /**
  15235. * Container of main controls.
  15236. *
  15237. * @extends Component
  15238. */
  15239. class ControlBar extends Component$1 {
  15240. /**
  15241. * Create the `Component`'s DOM element
  15242. *
  15243. * @return {Element}
  15244. * The element that was created.
  15245. */
  15246. createEl() {
  15247. return super.createEl('div', {
  15248. className: 'vjs-control-bar',
  15249. dir: 'ltr'
  15250. });
  15251. }
  15252. }
  15253. /**
  15254. * Default options for `ControlBar`
  15255. *
  15256. * @type {Object}
  15257. * @private
  15258. */
  15259. ControlBar.prototype.options_ = {
  15260. children: ['playToggle', 'skipBackward', 'skipForward', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  15261. };
  15262. if ('exitPictureInPicture' in document__default["default"]) {
  15263. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  15264. }
  15265. Component$1.registerComponent('ControlBar', ControlBar);
  15266. /**
  15267. * @file error-display.js
  15268. */
  15269. /**
  15270. * A display that indicates an error has occurred. This means that the video
  15271. * is unplayable.
  15272. *
  15273. * @extends ModalDialog
  15274. */
  15275. class ErrorDisplay extends ModalDialog {
  15276. /**
  15277. * Creates an instance of this class.
  15278. *
  15279. * @param { import('./player').default } player
  15280. * The `Player` that this class should be attached to.
  15281. *
  15282. * @param {Object} [options]
  15283. * The key/value store of player options.
  15284. */
  15285. constructor(player, options) {
  15286. super(player, options);
  15287. this.on(player, 'error', e => this.open(e));
  15288. }
  15289. /**
  15290. * Builds the default DOM `className`.
  15291. *
  15292. * @return {string}
  15293. * The DOM `className` for this object.
  15294. *
  15295. * @deprecated Since version 5.
  15296. */
  15297. buildCSSClass() {
  15298. return `vjs-error-display ${super.buildCSSClass()}`;
  15299. }
  15300. /**
  15301. * Gets the localized error message based on the `Player`s error.
  15302. *
  15303. * @return {string}
  15304. * The `Player`s error message localized or an empty string.
  15305. */
  15306. content() {
  15307. const error = this.player().error();
  15308. return error ? this.localize(error.message) : '';
  15309. }
  15310. }
  15311. /**
  15312. * The default options for an `ErrorDisplay`.
  15313. *
  15314. * @private
  15315. */
  15316. ErrorDisplay.prototype.options_ = Object.assign({}, ModalDialog.prototype.options_, {
  15317. pauseOnOpen: false,
  15318. fillAlways: true,
  15319. temporary: false,
  15320. uncloseable: true
  15321. });
  15322. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  15323. /**
  15324. * @file text-track-settings.js
  15325. */
  15326. const LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  15327. const COLOR_BLACK = ['#000', 'Black'];
  15328. const COLOR_BLUE = ['#00F', 'Blue'];
  15329. const COLOR_CYAN = ['#0FF', 'Cyan'];
  15330. const COLOR_GREEN = ['#0F0', 'Green'];
  15331. const COLOR_MAGENTA = ['#F0F', 'Magenta'];
  15332. const COLOR_RED = ['#F00', 'Red'];
  15333. const COLOR_WHITE = ['#FFF', 'White'];
  15334. const COLOR_YELLOW = ['#FF0', 'Yellow'];
  15335. const OPACITY_OPAQUE = ['1', 'Opaque'];
  15336. const OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  15337. const OPACITY_TRANS = ['0', 'Transparent'];
  15338. // Configuration for the various <select> elements in the DOM of this component.
  15339. //
  15340. // Possible keys include:
  15341. //
  15342. // `default`:
  15343. // The default option index. Only needs to be provided if not zero.
  15344. // `parser`:
  15345. // A function which is used to parse the value from the selected option in
  15346. // a customized way.
  15347. // `selector`:
  15348. // The selector used to find the associated <select> element.
  15349. const selectConfigs = {
  15350. backgroundColor: {
  15351. selector: '.vjs-bg-color > select',
  15352. id: 'captions-background-color-%s',
  15353. label: 'Color',
  15354. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15355. },
  15356. backgroundOpacity: {
  15357. selector: '.vjs-bg-opacity > select',
  15358. id: 'captions-background-opacity-%s',
  15359. label: 'Opacity',
  15360. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  15361. },
  15362. color: {
  15363. selector: '.vjs-text-color > select',
  15364. id: 'captions-foreground-color-%s',
  15365. label: 'Color',
  15366. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15367. },
  15368. edgeStyle: {
  15369. selector: '.vjs-edge-style > select',
  15370. id: '%s',
  15371. label: 'Text Edge Style',
  15372. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  15373. },
  15374. fontFamily: {
  15375. selector: '.vjs-font-family > select',
  15376. id: 'captions-font-family-%s',
  15377. label: 'Font Family',
  15378. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  15379. },
  15380. fontPercent: {
  15381. selector: '.vjs-font-percent > select',
  15382. id: 'captions-font-size-%s',
  15383. label: 'Font Size',
  15384. options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
  15385. default: 2,
  15386. parser: v => v === '1.00' ? null : Number(v)
  15387. },
  15388. textOpacity: {
  15389. selector: '.vjs-text-opacity > select',
  15390. id: 'captions-foreground-opacity-%s',
  15391. label: 'Opacity',
  15392. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  15393. },
  15394. // Options for this object are defined below.
  15395. windowColor: {
  15396. selector: '.vjs-window-color > select',
  15397. id: 'captions-window-color-%s',
  15398. label: 'Color'
  15399. },
  15400. // Options for this object are defined below.
  15401. windowOpacity: {
  15402. selector: '.vjs-window-opacity > select',
  15403. id: 'captions-window-opacity-%s',
  15404. label: 'Opacity',
  15405. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  15406. }
  15407. };
  15408. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  15409. /**
  15410. * Get the actual value of an option.
  15411. *
  15412. * @param {string} value
  15413. * The value to get
  15414. *
  15415. * @param {Function} [parser]
  15416. * Optional function to adjust the value.
  15417. *
  15418. * @return {*}
  15419. * - Will be `undefined` if no value exists
  15420. * - Will be `undefined` if the given value is "none".
  15421. * - Will be the actual value otherwise.
  15422. *
  15423. * @private
  15424. */
  15425. function parseOptionValue(value, parser) {
  15426. if (parser) {
  15427. value = parser(value);
  15428. }
  15429. if (value && value !== 'none') {
  15430. return value;
  15431. }
  15432. }
  15433. /**
  15434. * Gets the value of the selected <option> element within a <select> element.
  15435. *
  15436. * @param {Element} el
  15437. * the element to look in
  15438. *
  15439. * @param {Function} [parser]
  15440. * Optional function to adjust the value.
  15441. *
  15442. * @return {*}
  15443. * - Will be `undefined` if no value exists
  15444. * - Will be `undefined` if the given value is "none".
  15445. * - Will be the actual value otherwise.
  15446. *
  15447. * @private
  15448. */
  15449. function getSelectedOptionValue(el, parser) {
  15450. const value = el.options[el.options.selectedIndex].value;
  15451. return parseOptionValue(value, parser);
  15452. }
  15453. /**
  15454. * Sets the selected <option> element within a <select> element based on a
  15455. * given value.
  15456. *
  15457. * @param {Element} el
  15458. * The element to look in.
  15459. *
  15460. * @param {string} value
  15461. * the property to look on.
  15462. *
  15463. * @param {Function} [parser]
  15464. * Optional function to adjust the value before comparing.
  15465. *
  15466. * @private
  15467. */
  15468. function setSelectedOption(el, value, parser) {
  15469. if (!value) {
  15470. return;
  15471. }
  15472. for (let i = 0; i < el.options.length; i++) {
  15473. if (parseOptionValue(el.options[i].value, parser) === value) {
  15474. el.selectedIndex = i;
  15475. break;
  15476. }
  15477. }
  15478. }
  15479. /**
  15480. * Manipulate Text Tracks settings.
  15481. *
  15482. * @extends ModalDialog
  15483. */
  15484. class TextTrackSettings extends ModalDialog {
  15485. /**
  15486. * Creates an instance of this class.
  15487. *
  15488. * @param { import('../player').default } player
  15489. * The `Player` that this class should be attached to.
  15490. *
  15491. * @param {Object} [options]
  15492. * The key/value store of player options.
  15493. */
  15494. constructor(player, options) {
  15495. options.temporary = false;
  15496. super(player, options);
  15497. this.updateDisplay = this.updateDisplay.bind(this);
  15498. // fill the modal and pretend we have opened it
  15499. this.fill();
  15500. this.hasBeenOpened_ = this.hasBeenFilled_ = true;
  15501. this.endDialog = createEl('p', {
  15502. className: 'vjs-control-text',
  15503. textContent: this.localize('End of dialog window.')
  15504. });
  15505. this.el().appendChild(this.endDialog);
  15506. this.setDefaults();
  15507. // Grab `persistTextTrackSettings` from the player options if not passed in child options
  15508. if (options.persistTextTrackSettings === undefined) {
  15509. this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
  15510. }
  15511. this.on(this.$('.vjs-done-button'), 'click', () => {
  15512. this.saveSettings();
  15513. this.close();
  15514. });
  15515. this.on(this.$('.vjs-default-button'), 'click', () => {
  15516. this.setDefaults();
  15517. this.updateDisplay();
  15518. });
  15519. each(selectConfigs, config => {
  15520. this.on(this.$(config.selector), 'change', this.updateDisplay);
  15521. });
  15522. if (this.options_.persistTextTrackSettings) {
  15523. this.restoreSettings();
  15524. }
  15525. }
  15526. dispose() {
  15527. this.endDialog = null;
  15528. super.dispose();
  15529. }
  15530. /**
  15531. * Create a <select> element with configured options.
  15532. *
  15533. * @param {string} key
  15534. * Configuration key to use during creation.
  15535. *
  15536. * @return {string}
  15537. * An HTML string.
  15538. *
  15539. * @private
  15540. */
  15541. createElSelect_(key, legendId = '', type = 'label') {
  15542. const config = selectConfigs[key];
  15543. const id = config.id.replace('%s', this.id_);
  15544. const selectLabelledbyIds = [legendId, id].join(' ').trim();
  15545. return [`<${type} id="${id}" class="${type === 'label' ? 'vjs-label' : ''}">`, this.localize(config.label), `</${type}>`, `<select aria-labelledby="${selectLabelledbyIds}">`].concat(config.options.map(o => {
  15546. const optionId = id + '-' + o[1].replace(/\W+/g, '');
  15547. return [`<option id="${optionId}" value="${o[0]}" `, `aria-labelledby="${selectLabelledbyIds} ${optionId}">`, this.localize(o[1]), '</option>'].join('');
  15548. })).concat('</select>').join('');
  15549. }
  15550. /**
  15551. * Create foreground color element for the component
  15552. *
  15553. * @return {string}
  15554. * An HTML string.
  15555. *
  15556. * @private
  15557. */
  15558. createElFgColor_() {
  15559. const legendId = `captions-text-legend-${this.id_}`;
  15560. return ['<fieldset class="vjs-fg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text'), '</legend>', '<span class="vjs-text-color">', this.createElSelect_('color', legendId), '</span>', '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
  15561. }
  15562. /**
  15563. * Create background color element for the component
  15564. *
  15565. * @return {string}
  15566. * An HTML string.
  15567. *
  15568. * @private
  15569. */
  15570. createElBgColor_() {
  15571. const legendId = `captions-background-${this.id_}`;
  15572. return ['<fieldset class="vjs-bg vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Text Background'), '</legend>', '<span class="vjs-bg-color">', this.createElSelect_('backgroundColor', legendId), '</span>', '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
  15573. }
  15574. /**
  15575. * Create window color element for the component
  15576. *
  15577. * @return {string}
  15578. * An HTML string.
  15579. *
  15580. * @private
  15581. */
  15582. createElWinColor_() {
  15583. const legendId = `captions-window-${this.id_}`;
  15584. return ['<fieldset class="vjs-window vjs-track-setting">', `<legend id="${legendId}">`, this.localize('Caption Area Background'), '</legend>', '<span class="vjs-window-color">', this.createElSelect_('windowColor', legendId), '</span>', '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
  15585. }
  15586. /**
  15587. * Create color elements for the component
  15588. *
  15589. * @return {Element}
  15590. * The element that was created
  15591. *
  15592. * @private
  15593. */
  15594. createElColors_() {
  15595. return createEl('div', {
  15596. className: 'vjs-track-settings-colors',
  15597. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  15598. });
  15599. }
  15600. /**
  15601. * Create font elements for the component
  15602. *
  15603. * @return {Element}
  15604. * The element that was created.
  15605. *
  15606. * @private
  15607. */
  15608. createElFont_() {
  15609. return createEl('div', {
  15610. className: 'vjs-track-settings-font',
  15611. innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_('fontPercent', '', 'legend'), '</fieldset>', '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_('edgeStyle', '', 'legend'), '</fieldset>', '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_('fontFamily', '', 'legend'), '</fieldset>'].join('')
  15612. });
  15613. }
  15614. /**
  15615. * Create controls for the component
  15616. *
  15617. * @return {Element}
  15618. * The element that was created.
  15619. *
  15620. * @private
  15621. */
  15622. createElControls_() {
  15623. const defaultsDescription = this.localize('restore all settings to the default values');
  15624. return createEl('div', {
  15625. className: 'vjs-track-settings-controls',
  15626. innerHTML: [`<button type="button" class="vjs-default-button" title="${defaultsDescription}">`, this.localize('Reset'), `<span class="vjs-control-text"> ${defaultsDescription}</span>`, '</button>', `<button type="button" class="vjs-done-button">${this.localize('Done')}</button>`].join('')
  15627. });
  15628. }
  15629. content() {
  15630. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  15631. }
  15632. label() {
  15633. return this.localize('Caption Settings Dialog');
  15634. }
  15635. description() {
  15636. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  15637. }
  15638. buildCSSClass() {
  15639. return super.buildCSSClass() + ' vjs-text-track-settings';
  15640. }
  15641. /**
  15642. * Gets an object of text track settings (or null).
  15643. *
  15644. * @return {Object}
  15645. * An object with config values parsed from the DOM or localStorage.
  15646. */
  15647. getValues() {
  15648. return reduce(selectConfigs, (accum, config, key) => {
  15649. const value = getSelectedOptionValue(this.$(config.selector), config.parser);
  15650. if (value !== undefined) {
  15651. accum[key] = value;
  15652. }
  15653. return accum;
  15654. }, {});
  15655. }
  15656. /**
  15657. * Sets text track settings from an object of values.
  15658. *
  15659. * @param {Object} values
  15660. * An object with config values parsed from the DOM or localStorage.
  15661. */
  15662. setValues(values) {
  15663. each(selectConfigs, (config, key) => {
  15664. setSelectedOption(this.$(config.selector), values[key], config.parser);
  15665. });
  15666. }
  15667. /**
  15668. * Sets all `<select>` elements to their default values.
  15669. */
  15670. setDefaults() {
  15671. each(selectConfigs, config => {
  15672. const index = config.hasOwnProperty('default') ? config.default : 0;
  15673. this.$(config.selector).selectedIndex = index;
  15674. });
  15675. }
  15676. /**
  15677. * Restore texttrack settings from localStorage
  15678. */
  15679. restoreSettings() {
  15680. let values;
  15681. try {
  15682. values = JSON.parse(window__default["default"].localStorage.getItem(LOCAL_STORAGE_KEY$1));
  15683. } catch (err) {
  15684. log$1.warn(err);
  15685. }
  15686. if (values) {
  15687. this.setValues(values);
  15688. }
  15689. }
  15690. /**
  15691. * Save text track settings to localStorage
  15692. */
  15693. saveSettings() {
  15694. if (!this.options_.persistTextTrackSettings) {
  15695. return;
  15696. }
  15697. const values = this.getValues();
  15698. try {
  15699. if (Object.keys(values).length) {
  15700. window__default["default"].localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  15701. } else {
  15702. window__default["default"].localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  15703. }
  15704. } catch (err) {
  15705. log$1.warn(err);
  15706. }
  15707. }
  15708. /**
  15709. * Update display of text track settings
  15710. */
  15711. updateDisplay() {
  15712. const ttDisplay = this.player_.getChild('textTrackDisplay');
  15713. if (ttDisplay) {
  15714. ttDisplay.updateDisplay();
  15715. }
  15716. }
  15717. /**
  15718. * conditionally blur the element and refocus the captions button
  15719. *
  15720. * @private
  15721. */
  15722. conditionalBlur_() {
  15723. this.previouslyActiveEl_ = null;
  15724. const cb = this.player_.controlBar;
  15725. const subsCapsBtn = cb && cb.subsCapsButton;
  15726. const ccBtn = cb && cb.captionsButton;
  15727. if (subsCapsBtn) {
  15728. subsCapsBtn.focus();
  15729. } else if (ccBtn) {
  15730. ccBtn.focus();
  15731. }
  15732. }
  15733. /**
  15734. * Repopulate dialog with new localizations on languagechange
  15735. */
  15736. handleLanguagechange() {
  15737. this.fill();
  15738. }
  15739. }
  15740. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  15741. /**
  15742. * @file resize-manager.js
  15743. */
  15744. /**
  15745. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  15746. *
  15747. * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
  15748. *
  15749. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  15750. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  15751. *
  15752. * @example <caption>How to disable the resize manager</caption>
  15753. * const player = videojs('#vid', {
  15754. * resizeManager: false
  15755. * });
  15756. *
  15757. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  15758. *
  15759. * @extends Component
  15760. */
  15761. class ResizeManager extends Component$1 {
  15762. /**
  15763. * Create the ResizeManager.
  15764. *
  15765. * @param {Object} player
  15766. * The `Player` that this class should be attached to.
  15767. *
  15768. * @param {Object} [options]
  15769. * The key/value store of ResizeManager options.
  15770. *
  15771. * @param {Object} [options.ResizeObserver]
  15772. * A polyfill for ResizeObserver can be passed in here.
  15773. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  15774. */
  15775. constructor(player, options) {
  15776. let RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window__default["default"].ResizeObserver;
  15777. // if `null` was passed, we want to disable the ResizeObserver
  15778. if (options.ResizeObserver === null) {
  15779. RESIZE_OBSERVER_AVAILABLE = false;
  15780. }
  15781. // Only create an element when ResizeObserver isn't available
  15782. const options_ = merge$1({
  15783. createEl: !RESIZE_OBSERVER_AVAILABLE,
  15784. reportTouchActivity: false
  15785. }, options);
  15786. super(player, options_);
  15787. this.ResizeObserver = options.ResizeObserver || window__default["default"].ResizeObserver;
  15788. this.loadListener_ = null;
  15789. this.resizeObserver_ = null;
  15790. this.debouncedHandler_ = debounce(() => {
  15791. this.resizeHandler();
  15792. }, 100, false, this);
  15793. if (RESIZE_OBSERVER_AVAILABLE) {
  15794. this.resizeObserver_ = new this.ResizeObserver(this.debouncedHandler_);
  15795. this.resizeObserver_.observe(player.el());
  15796. } else {
  15797. this.loadListener_ = () => {
  15798. if (!this.el_ || !this.el_.contentWindow) {
  15799. return;
  15800. }
  15801. const debouncedHandler_ = this.debouncedHandler_;
  15802. let unloadListener_ = this.unloadListener_ = function () {
  15803. off(this, 'resize', debouncedHandler_);
  15804. off(this, 'unload', unloadListener_);
  15805. unloadListener_ = null;
  15806. };
  15807. // safari and edge can unload the iframe before resizemanager dispose
  15808. // we have to dispose of event handlers correctly before that happens
  15809. on(this.el_.contentWindow, 'unload', unloadListener_);
  15810. on(this.el_.contentWindow, 'resize', debouncedHandler_);
  15811. };
  15812. this.one('load', this.loadListener_);
  15813. }
  15814. }
  15815. createEl() {
  15816. return super.createEl('iframe', {
  15817. className: 'vjs-resize-manager',
  15818. tabIndex: -1,
  15819. title: this.localize('No content')
  15820. }, {
  15821. 'aria-hidden': 'true'
  15822. });
  15823. }
  15824. /**
  15825. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  15826. *
  15827. * @fires Player#playerresize
  15828. */
  15829. resizeHandler() {
  15830. /**
  15831. * Called when the player size has changed
  15832. *
  15833. * @event Player#playerresize
  15834. * @type {Event}
  15835. */
  15836. // make sure player is still around to trigger
  15837. // prevents this from causing an error after dispose
  15838. if (!this.player_ || !this.player_.trigger) {
  15839. return;
  15840. }
  15841. this.player_.trigger('playerresize');
  15842. }
  15843. dispose() {
  15844. if (this.debouncedHandler_) {
  15845. this.debouncedHandler_.cancel();
  15846. }
  15847. if (this.resizeObserver_) {
  15848. if (this.player_.el()) {
  15849. this.resizeObserver_.unobserve(this.player_.el());
  15850. }
  15851. this.resizeObserver_.disconnect();
  15852. }
  15853. if (this.loadListener_) {
  15854. this.off('load', this.loadListener_);
  15855. }
  15856. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  15857. this.unloadListener_.call(this.el_.contentWindow);
  15858. }
  15859. this.ResizeObserver = null;
  15860. this.resizeObserver = null;
  15861. this.debouncedHandler_ = null;
  15862. this.loadListener_ = null;
  15863. super.dispose();
  15864. }
  15865. }
  15866. Component$1.registerComponent('ResizeManager', ResizeManager);
  15867. const defaults = {
  15868. trackingThreshold: 20,
  15869. liveTolerance: 15
  15870. };
  15871. /*
  15872. track when we are at the live edge, and other helpers for live playback */
  15873. /**
  15874. * A class for checking live current time and determining when the player
  15875. * is at or behind the live edge.
  15876. */
  15877. class LiveTracker extends Component$1 {
  15878. /**
  15879. * Creates an instance of this class.
  15880. *
  15881. * @param { import('./player').default } player
  15882. * The `Player` that this class should be attached to.
  15883. *
  15884. * @param {Object} [options]
  15885. * The key/value store of player options.
  15886. *
  15887. * @param {number} [options.trackingThreshold=20]
  15888. * Number of seconds of live window (seekableEnd - seekableStart) that
  15889. * media needs to have before the liveui will be shown.
  15890. *
  15891. * @param {number} [options.liveTolerance=15]
  15892. * Number of seconds behind live that we have to be
  15893. * before we will be considered non-live. Note that this will only
  15894. * be used when playing at the live edge. This allows large seekable end
  15895. * changes to not effect whether we are live or not.
  15896. */
  15897. constructor(player, options) {
  15898. // LiveTracker does not need an element
  15899. const options_ = merge$1(defaults, options, {
  15900. createEl: false
  15901. });
  15902. super(player, options_);
  15903. this.trackLiveHandler_ = () => this.trackLive_();
  15904. this.handlePlay_ = e => this.handlePlay(e);
  15905. this.handleFirstTimeupdate_ = e => this.handleFirstTimeupdate(e);
  15906. this.handleSeeked_ = e => this.handleSeeked(e);
  15907. this.seekToLiveEdge_ = e => this.seekToLiveEdge(e);
  15908. this.reset_();
  15909. this.on(this.player_, 'durationchange', e => this.handleDurationchange(e));
  15910. // we should try to toggle tracking on canplay as native playback engines, like Safari
  15911. // may not have the proper values for things like seekableEnd until then
  15912. this.on(this.player_, 'canplay', () => this.toggleTracking());
  15913. }
  15914. /**
  15915. * all the functionality for tracking when seek end changes
  15916. * and for tracking how far past seek end we should be
  15917. */
  15918. trackLive_() {
  15919. const seekable = this.player_.seekable();
  15920. // skip undefined seekable
  15921. if (!seekable || !seekable.length) {
  15922. return;
  15923. }
  15924. const newTime = Number(window__default["default"].performance.now().toFixed(4));
  15925. const deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  15926. this.lastTime_ = newTime;
  15927. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  15928. const liveCurrentTime = this.liveCurrentTime();
  15929. const currentTime = this.player_.currentTime();
  15930. // we are behind live if any are true
  15931. // 1. the player is paused
  15932. // 2. the user seeked to a location 2 seconds away from live
  15933. // 3. the difference between live and current time is greater
  15934. // liveTolerance which defaults to 15s
  15935. let isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance;
  15936. // we cannot be behind if
  15937. // 1. until we have not seen a timeupdate yet
  15938. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  15939. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  15940. isBehind = false;
  15941. }
  15942. if (isBehind !== this.behindLiveEdge_) {
  15943. this.behindLiveEdge_ = isBehind;
  15944. this.trigger('liveedgechange');
  15945. }
  15946. }
  15947. /**
  15948. * handle a durationchange event on the player
  15949. * and start/stop tracking accordingly.
  15950. */
  15951. handleDurationchange() {
  15952. this.toggleTracking();
  15953. }
  15954. /**
  15955. * start/stop tracking
  15956. */
  15957. toggleTracking() {
  15958. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  15959. if (this.player_.options_.liveui) {
  15960. this.player_.addClass('vjs-liveui');
  15961. }
  15962. this.startTracking();
  15963. } else {
  15964. this.player_.removeClass('vjs-liveui');
  15965. this.stopTracking();
  15966. }
  15967. }
  15968. /**
  15969. * start tracking live playback
  15970. */
  15971. startTracking() {
  15972. if (this.isTracking()) {
  15973. return;
  15974. }
  15975. // If we haven't seen a timeupdate, we need to check whether playback
  15976. // began before this component started tracking. This can happen commonly
  15977. // when using autoplay.
  15978. if (!this.timeupdateSeen_) {
  15979. this.timeupdateSeen_ = this.player_.hasStarted();
  15980. }
  15981. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  15982. this.trackLive_();
  15983. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  15984. if (!this.timeupdateSeen_) {
  15985. this.one(this.player_, 'play', this.handlePlay_);
  15986. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  15987. } else {
  15988. this.on(this.player_, 'seeked', this.handleSeeked_);
  15989. }
  15990. }
  15991. /**
  15992. * handle the first timeupdate on the player if it wasn't already playing
  15993. * when live tracker started tracking.
  15994. */
  15995. handleFirstTimeupdate() {
  15996. this.timeupdateSeen_ = true;
  15997. this.on(this.player_, 'seeked', this.handleSeeked_);
  15998. }
  15999. /**
  16000. * Keep track of what time a seek starts, and listen for seeked
  16001. * to find where a seek ends.
  16002. */
  16003. handleSeeked() {
  16004. const timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  16005. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  16006. this.nextSeekedFromUser_ = false;
  16007. this.trackLive_();
  16008. }
  16009. /**
  16010. * handle the first play on the player, and make sure that we seek
  16011. * right to the live edge.
  16012. */
  16013. handlePlay() {
  16014. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16015. }
  16016. /**
  16017. * Stop tracking, and set all internal variables to
  16018. * their initial value.
  16019. */
  16020. reset_() {
  16021. this.lastTime_ = -1;
  16022. this.pastSeekEnd_ = 0;
  16023. this.lastSeekEnd_ = -1;
  16024. this.behindLiveEdge_ = true;
  16025. this.timeupdateSeen_ = false;
  16026. this.seekedBehindLive_ = false;
  16027. this.nextSeekedFromUser_ = false;
  16028. this.clearInterval(this.trackingInterval_);
  16029. this.trackingInterval_ = null;
  16030. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16031. this.off(this.player_, 'seeked', this.handleSeeked_);
  16032. this.off(this.player_, 'play', this.handlePlay_);
  16033. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16034. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16035. }
  16036. /**
  16037. * The next seeked event is from the user. Meaning that any seek
  16038. * > 2s behind live will be considered behind live for real and
  16039. * liveTolerance will be ignored.
  16040. */
  16041. nextSeekedFromUser() {
  16042. this.nextSeekedFromUser_ = true;
  16043. }
  16044. /**
  16045. * stop tracking live playback
  16046. */
  16047. stopTracking() {
  16048. if (!this.isTracking()) {
  16049. return;
  16050. }
  16051. this.reset_();
  16052. this.trigger('liveedgechange');
  16053. }
  16054. /**
  16055. * A helper to get the player seekable end
  16056. * so that we don't have to null check everywhere
  16057. *
  16058. * @return {number}
  16059. * The furthest seekable end or Infinity.
  16060. */
  16061. seekableEnd() {
  16062. const seekable = this.player_.seekable();
  16063. const seekableEnds = [];
  16064. let i = seekable ? seekable.length : 0;
  16065. while (i--) {
  16066. seekableEnds.push(seekable.end(i));
  16067. }
  16068. // grab the furthest seekable end after sorting, or if there are none
  16069. // default to Infinity
  16070. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  16071. }
  16072. /**
  16073. * A helper to get the player seekable start
  16074. * so that we don't have to null check everywhere
  16075. *
  16076. * @return {number}
  16077. * The earliest seekable start or 0.
  16078. */
  16079. seekableStart() {
  16080. const seekable = this.player_.seekable();
  16081. const seekableStarts = [];
  16082. let i = seekable ? seekable.length : 0;
  16083. while (i--) {
  16084. seekableStarts.push(seekable.start(i));
  16085. }
  16086. // grab the first seekable start after sorting, or if there are none
  16087. // default to 0
  16088. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  16089. }
  16090. /**
  16091. * Get the live time window aka
  16092. * the amount of time between seekable start and
  16093. * live current time.
  16094. *
  16095. * @return {number}
  16096. * The amount of seconds that are seekable in
  16097. * the live video.
  16098. */
  16099. liveWindow() {
  16100. const liveCurrentTime = this.liveCurrentTime();
  16101. // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  16102. if (liveCurrentTime === Infinity) {
  16103. return 0;
  16104. }
  16105. return liveCurrentTime - this.seekableStart();
  16106. }
  16107. /**
  16108. * Determines if the player is live, only checks if this component
  16109. * is tracking live playback or not
  16110. *
  16111. * @return {boolean}
  16112. * Whether liveTracker is tracking
  16113. */
  16114. isLive() {
  16115. return this.isTracking();
  16116. }
  16117. /**
  16118. * Determines if currentTime is at the live edge and won't fall behind
  16119. * on each seekableendchange
  16120. *
  16121. * @return {boolean}
  16122. * Whether playback is at the live edge
  16123. */
  16124. atLiveEdge() {
  16125. return !this.behindLiveEdge();
  16126. }
  16127. /**
  16128. * get what we expect the live current time to be
  16129. *
  16130. * @return {number}
  16131. * The expected live current time
  16132. */
  16133. liveCurrentTime() {
  16134. return this.pastSeekEnd() + this.seekableEnd();
  16135. }
  16136. /**
  16137. * The number of seconds that have occurred after seekable end
  16138. * changed. This will be reset to 0 once seekable end changes.
  16139. *
  16140. * @return {number}
  16141. * Seconds past the current seekable end
  16142. */
  16143. pastSeekEnd() {
  16144. const seekableEnd = this.seekableEnd();
  16145. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  16146. this.pastSeekEnd_ = 0;
  16147. }
  16148. this.lastSeekEnd_ = seekableEnd;
  16149. return this.pastSeekEnd_;
  16150. }
  16151. /**
  16152. * If we are currently behind the live edge, aka currentTime will be
  16153. * behind on a seekableendchange
  16154. *
  16155. * @return {boolean}
  16156. * If we are behind the live edge
  16157. */
  16158. behindLiveEdge() {
  16159. return this.behindLiveEdge_;
  16160. }
  16161. /**
  16162. * Whether live tracker is currently tracking or not.
  16163. */
  16164. isTracking() {
  16165. return typeof this.trackingInterval_ === 'number';
  16166. }
  16167. /**
  16168. * Seek to the live edge if we are behind the live edge
  16169. */
  16170. seekToLiveEdge() {
  16171. this.seekedBehindLive_ = false;
  16172. if (this.atLiveEdge()) {
  16173. return;
  16174. }
  16175. this.nextSeekedFromUser_ = false;
  16176. this.player_.currentTime(this.liveCurrentTime());
  16177. }
  16178. /**
  16179. * Dispose of liveTracker
  16180. */
  16181. dispose() {
  16182. this.stopTracking();
  16183. super.dispose();
  16184. }
  16185. }
  16186. Component$1.registerComponent('LiveTracker', LiveTracker);
  16187. /**
  16188. * Displays an element over the player which contains an optional title and
  16189. * description for the current content.
  16190. *
  16191. * Much of the code for this component originated in the now obsolete
  16192. * videojs-dock plugin: https://github.com/brightcove/videojs-dock/
  16193. *
  16194. * @extends Component
  16195. */
  16196. class TitleBar extends Component$1 {
  16197. constructor(player, options) {
  16198. super(player, options);
  16199. this.on('statechanged', e => this.updateDom_());
  16200. this.updateDom_();
  16201. }
  16202. /**
  16203. * Create the `TitleBar`'s DOM element
  16204. *
  16205. * @return {Element}
  16206. * The element that was created.
  16207. */
  16208. createEl() {
  16209. this.els = {
  16210. title: createEl('div', {
  16211. className: 'vjs-title-bar-title',
  16212. id: `vjs-title-bar-title-${newGUID()}`
  16213. }),
  16214. description: createEl('div', {
  16215. className: 'vjs-title-bar-description',
  16216. id: `vjs-title-bar-description-${newGUID()}`
  16217. })
  16218. };
  16219. return createEl('div', {
  16220. className: 'vjs-title-bar'
  16221. }, {}, Object.values(this.els));
  16222. }
  16223. /**
  16224. * Updates the DOM based on the component's state object.
  16225. */
  16226. updateDom_() {
  16227. const tech = this.player_.tech_;
  16228. const techEl = tech && tech.el_;
  16229. const techAriaAttrs = {
  16230. title: 'aria-labelledby',
  16231. description: 'aria-describedby'
  16232. };
  16233. ['title', 'description'].forEach(k => {
  16234. const value = this.state[k];
  16235. const el = this.els[k];
  16236. const techAriaAttr = techAriaAttrs[k];
  16237. emptyEl(el);
  16238. if (value) {
  16239. textContent(el, value);
  16240. }
  16241. // If there is a tech element available, update its ARIA attributes
  16242. // according to whether a title and/or description have been provided.
  16243. if (techEl) {
  16244. techEl.removeAttribute(techAriaAttr);
  16245. if (value) {
  16246. techEl.setAttribute(techAriaAttr, el.id);
  16247. }
  16248. }
  16249. });
  16250. if (this.state.title || this.state.description) {
  16251. this.show();
  16252. } else {
  16253. this.hide();
  16254. }
  16255. }
  16256. /**
  16257. * Update the contents of the title bar component with new title and
  16258. * description text.
  16259. *
  16260. * If both title and description are missing, the title bar will be hidden.
  16261. *
  16262. * If either title or description are present, the title bar will be visible.
  16263. *
  16264. * NOTE: Any previously set value will be preserved. To unset a previously
  16265. * set value, you must pass an empty string or null.
  16266. *
  16267. * For example:
  16268. *
  16269. * ```
  16270. * update({title: 'foo', description: 'bar'}) // title: 'foo', description: 'bar'
  16271. * update({description: 'bar2'}) // title: 'foo', description: 'bar2'
  16272. * update({title: ''}) // title: '', description: 'bar2'
  16273. * update({title: 'foo', description: null}) // title: 'foo', description: null
  16274. * ```
  16275. *
  16276. * @param {Object} [options={}]
  16277. * An options object. When empty, the title bar will be hidden.
  16278. *
  16279. * @param {string} [options.title]
  16280. * A title to display in the title bar.
  16281. *
  16282. * @param {string} [options.description]
  16283. * A description to display in the title bar.
  16284. */
  16285. update(options) {
  16286. this.setState(options);
  16287. }
  16288. /**
  16289. * Dispose the component.
  16290. */
  16291. dispose() {
  16292. const tech = this.player_.tech_;
  16293. const techEl = tech && tech.el_;
  16294. if (techEl) {
  16295. techEl.removeAttribute('aria-labelledby');
  16296. techEl.removeAttribute('aria-describedby');
  16297. }
  16298. super.dispose();
  16299. this.els = null;
  16300. }
  16301. }
  16302. Component$1.registerComponent('TitleBar', TitleBar);
  16303. /**
  16304. * This function is used to fire a sourceset when there is something
  16305. * similar to `mediaEl.load()` being called. It will try to find the source via
  16306. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  16307. * with the source that was found or empty string if we cannot know. If it cannot
  16308. * find a source then `sourceset` will not be fired.
  16309. *
  16310. * @param { import('./html5').default } tech
  16311. * The tech object that sourceset was setup on
  16312. *
  16313. * @return {boolean}
  16314. * returns false if the sourceset was not fired and true otherwise.
  16315. */
  16316. const sourcesetLoad = tech => {
  16317. const el = tech.el();
  16318. // if `el.src` is set, that source will be loaded.
  16319. if (el.hasAttribute('src')) {
  16320. tech.triggerSourceset(el.src);
  16321. return true;
  16322. }
  16323. /**
  16324. * Since there isn't a src property on the media element, source elements will be used for
  16325. * implementing the source selection algorithm. This happens asynchronously and
  16326. * for most cases were there is more than one source we cannot tell what source will
  16327. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  16328. * going to do that. There are three special cases that we do handle here though:
  16329. *
  16330. * 1. If there are no sources, do not fire `sourceset`.
  16331. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  16332. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  16333. * That will be our src.
  16334. */
  16335. const sources = tech.$$('source');
  16336. const srcUrls = [];
  16337. let src = '';
  16338. // if there are no sources, do not fire sourceset
  16339. if (!sources.length) {
  16340. return false;
  16341. }
  16342. // only count valid/non-duplicate source elements
  16343. for (let i = 0; i < sources.length; i++) {
  16344. const url = sources[i].src;
  16345. if (url && srcUrls.indexOf(url) === -1) {
  16346. srcUrls.push(url);
  16347. }
  16348. }
  16349. // there were no valid sources
  16350. if (!srcUrls.length) {
  16351. return false;
  16352. }
  16353. // there is only one valid source element url
  16354. // use that
  16355. if (srcUrls.length === 1) {
  16356. src = srcUrls[0];
  16357. }
  16358. tech.triggerSourceset(src);
  16359. return true;
  16360. };
  16361. /**
  16362. * our implementation of an `innerHTML` descriptor for browsers
  16363. * that do not have one.
  16364. */
  16365. const innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  16366. get() {
  16367. return this.cloneNode(true).innerHTML;
  16368. },
  16369. set(v) {
  16370. // make a dummy node to use innerHTML on
  16371. const dummy = document__default["default"].createElement(this.nodeName.toLowerCase());
  16372. // set innerHTML to the value provided
  16373. dummy.innerHTML = v;
  16374. // make a document fragment to hold the nodes from dummy
  16375. const docFrag = document__default["default"].createDocumentFragment();
  16376. // copy all of the nodes created by the innerHTML on dummy
  16377. // to the document fragment
  16378. while (dummy.childNodes.length) {
  16379. docFrag.appendChild(dummy.childNodes[0]);
  16380. }
  16381. // remove content
  16382. this.innerText = '';
  16383. // now we add all of that html in one by appending the
  16384. // document fragment. This is how innerHTML does it.
  16385. window__default["default"].Element.prototype.appendChild.call(this, docFrag);
  16386. // then return the result that innerHTML's setter would
  16387. return this.innerHTML;
  16388. }
  16389. });
  16390. /**
  16391. * Get a property descriptor given a list of priorities and the
  16392. * property to get.
  16393. */
  16394. const getDescriptor = (priority, prop) => {
  16395. let descriptor = {};
  16396. for (let i = 0; i < priority.length; i++) {
  16397. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  16398. if (descriptor && descriptor.set && descriptor.get) {
  16399. break;
  16400. }
  16401. }
  16402. descriptor.enumerable = true;
  16403. descriptor.configurable = true;
  16404. return descriptor;
  16405. };
  16406. const getInnerHTMLDescriptor = tech => getDescriptor([tech.el(), window__default["default"].HTMLMediaElement.prototype, window__default["default"].Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  16407. /**
  16408. * Patches browser internal functions so that we can tell synchronously
  16409. * if a `<source>` was appended to the media element. For some reason this
  16410. * causes a `sourceset` if the the media element is ready and has no source.
  16411. * This happens when:
  16412. * - The page has just loaded and the media element does not have a source.
  16413. * - The media element was emptied of all sources, then `load()` was called.
  16414. *
  16415. * It does this by patching the following functions/properties when they are supported:
  16416. *
  16417. * - `append()` - can be used to add a `<source>` element to the media element
  16418. * - `appendChild()` - can be used to add a `<source>` element to the media element
  16419. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  16420. * - `innerHTML` - can be used to add a `<source>` element to the media element
  16421. *
  16422. * @param {Html5} tech
  16423. * The tech object that sourceset is being setup on.
  16424. */
  16425. const firstSourceWatch = function (tech) {
  16426. const el = tech.el();
  16427. // make sure firstSourceWatch isn't setup twice.
  16428. if (el.resetSourceWatch_) {
  16429. return;
  16430. }
  16431. const old = {};
  16432. const innerDescriptor = getInnerHTMLDescriptor(tech);
  16433. const appendWrapper = appendFn => (...args) => {
  16434. const retval = appendFn.apply(el, args);
  16435. sourcesetLoad(tech);
  16436. return retval;
  16437. };
  16438. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(k => {
  16439. if (!el[k]) {
  16440. return;
  16441. }
  16442. // store the old function
  16443. old[k] = el[k];
  16444. // call the old function with a sourceset if a source
  16445. // was loaded
  16446. el[k] = appendWrapper(old[k]);
  16447. });
  16448. Object.defineProperty(el, 'innerHTML', merge$1(innerDescriptor, {
  16449. set: appendWrapper(innerDescriptor.set)
  16450. }));
  16451. el.resetSourceWatch_ = () => {
  16452. el.resetSourceWatch_ = null;
  16453. Object.keys(old).forEach(k => {
  16454. el[k] = old[k];
  16455. });
  16456. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  16457. };
  16458. // on the first sourceset, we need to revert our changes
  16459. tech.one('sourceset', el.resetSourceWatch_);
  16460. };
  16461. /**
  16462. * our implementation of a `src` descriptor for browsers
  16463. * that do not have one
  16464. */
  16465. const srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  16466. get() {
  16467. if (this.hasAttribute('src')) {
  16468. return getAbsoluteURL(window__default["default"].Element.prototype.getAttribute.call(this, 'src'));
  16469. }
  16470. return '';
  16471. },
  16472. set(v) {
  16473. window__default["default"].Element.prototype.setAttribute.call(this, 'src', v);
  16474. return v;
  16475. }
  16476. });
  16477. const getSrcDescriptor = tech => getDescriptor([tech.el(), window__default["default"].HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  16478. /**
  16479. * setup `sourceset` handling on the `Html5` tech. This function
  16480. * patches the following element properties/functions:
  16481. *
  16482. * - `src` - to determine when `src` is set
  16483. * - `setAttribute()` - to determine when `src` is set
  16484. * - `load()` - this re-triggers the source selection algorithm, and can
  16485. * cause a sourceset.
  16486. *
  16487. * If there is no source when we are adding `sourceset` support or during a `load()`
  16488. * we also patch the functions listed in `firstSourceWatch`.
  16489. *
  16490. * @param {Html5} tech
  16491. * The tech to patch
  16492. */
  16493. const setupSourceset = function (tech) {
  16494. if (!tech.featuresSourceset) {
  16495. return;
  16496. }
  16497. const el = tech.el();
  16498. // make sure sourceset isn't setup twice.
  16499. if (el.resetSourceset_) {
  16500. return;
  16501. }
  16502. const srcDescriptor = getSrcDescriptor(tech);
  16503. const oldSetAttribute = el.setAttribute;
  16504. const oldLoad = el.load;
  16505. Object.defineProperty(el, 'src', merge$1(srcDescriptor, {
  16506. set: v => {
  16507. const retval = srcDescriptor.set.call(el, v);
  16508. // we use the getter here to get the actual value set on src
  16509. tech.triggerSourceset(el.src);
  16510. return retval;
  16511. }
  16512. }));
  16513. el.setAttribute = (n, v) => {
  16514. const retval = oldSetAttribute.call(el, n, v);
  16515. if (/src/i.test(n)) {
  16516. tech.triggerSourceset(el.src);
  16517. }
  16518. return retval;
  16519. };
  16520. el.load = () => {
  16521. const retval = oldLoad.call(el);
  16522. // if load was called, but there was no source to fire
  16523. // sourceset on. We have to watch for a source append
  16524. // as that can trigger a `sourceset` when the media element
  16525. // has no source
  16526. if (!sourcesetLoad(tech)) {
  16527. tech.triggerSourceset('');
  16528. firstSourceWatch(tech);
  16529. }
  16530. return retval;
  16531. };
  16532. if (el.currentSrc) {
  16533. tech.triggerSourceset(el.currentSrc);
  16534. } else if (!sourcesetLoad(tech)) {
  16535. firstSourceWatch(tech);
  16536. }
  16537. el.resetSourceset_ = () => {
  16538. el.resetSourceset_ = null;
  16539. el.load = oldLoad;
  16540. el.setAttribute = oldSetAttribute;
  16541. Object.defineProperty(el, 'src', srcDescriptor);
  16542. if (el.resetSourceWatch_) {
  16543. el.resetSourceWatch_();
  16544. }
  16545. };
  16546. };
  16547. /**
  16548. * @file html5.js
  16549. */
  16550. /**
  16551. * HTML5 Media Controller - Wrapper for HTML5 Media API
  16552. *
  16553. * @mixes Tech~SourceHandlerAdditions
  16554. * @extends Tech
  16555. */
  16556. class Html5 extends Tech {
  16557. /**
  16558. * Create an instance of this Tech.
  16559. *
  16560. * @param {Object} [options]
  16561. * The key/value store of player options.
  16562. *
  16563. * @param {Function} [ready]
  16564. * Callback function to call when the `HTML5` Tech is ready.
  16565. */
  16566. constructor(options, ready) {
  16567. super(options, ready);
  16568. const source = options.source;
  16569. let crossoriginTracks = false;
  16570. this.featuresVideoFrameCallback = this.featuresVideoFrameCallback && this.el_.tagName === 'VIDEO';
  16571. // Set the source if one is provided
  16572. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  16573. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  16574. // anyway so the error gets fired.
  16575. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  16576. this.setSource(source);
  16577. } else {
  16578. this.handleLateInit_(this.el_);
  16579. }
  16580. // setup sourceset after late sourceset/init
  16581. if (options.enableSourceset) {
  16582. this.setupSourcesetHandling_();
  16583. }
  16584. this.isScrubbing_ = false;
  16585. if (this.el_.hasChildNodes()) {
  16586. const nodes = this.el_.childNodes;
  16587. let nodesLength = nodes.length;
  16588. const removeNodes = [];
  16589. while (nodesLength--) {
  16590. const node = nodes[nodesLength];
  16591. const nodeName = node.nodeName.toLowerCase();
  16592. if (nodeName === 'track') {
  16593. if (!this.featuresNativeTextTracks) {
  16594. // Empty video tag tracks so the built-in player doesn't use them also.
  16595. // This may not be fast enough to stop HTML5 browsers from reading the tags
  16596. // so we'll need to turn off any default tracks if we're manually doing
  16597. // captions and subtitles. videoElement.textTracks
  16598. removeNodes.push(node);
  16599. } else {
  16600. // store HTMLTrackElement and TextTrack to remote list
  16601. this.remoteTextTrackEls().addTrackElement_(node);
  16602. this.remoteTextTracks().addTrack(node.track);
  16603. this.textTracks().addTrack(node.track);
  16604. if (!crossoriginTracks && !this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  16605. crossoriginTracks = true;
  16606. }
  16607. }
  16608. }
  16609. }
  16610. for (let i = 0; i < removeNodes.length; i++) {
  16611. this.el_.removeChild(removeNodes[i]);
  16612. }
  16613. }
  16614. this.proxyNativeTracks_();
  16615. if (this.featuresNativeTextTracks && crossoriginTracks) {
  16616. log$1.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'This may prevent text tracks from loading.');
  16617. }
  16618. // prevent iOS Safari from disabling metadata text tracks during native playback
  16619. this.restoreMetadataTracksInIOSNativePlayer_();
  16620. // Determine if native controls should be used
  16621. // Our goal should be to get the custom controls on mobile solid everywhere
  16622. // so we can remove this all together. Right now this will block custom
  16623. // controls on touch enabled laptops like the Chrome Pixel
  16624. if ((TOUCH_ENABLED || IS_IPHONE) && options.nativeControlsForTouch === true) {
  16625. this.setControls(true);
  16626. }
  16627. // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  16628. // into a `fullscreenchange` event
  16629. this.proxyWebkitFullscreen_();
  16630. this.triggerReady();
  16631. }
  16632. /**
  16633. * Dispose of `HTML5` media element and remove all tracks.
  16634. */
  16635. dispose() {
  16636. if (this.el_ && this.el_.resetSourceset_) {
  16637. this.el_.resetSourceset_();
  16638. }
  16639. Html5.disposeMediaElement(this.el_);
  16640. this.options_ = null;
  16641. // tech will handle clearing of the emulated track list
  16642. super.dispose();
  16643. }
  16644. /**
  16645. * Modify the media element so that we can detect when
  16646. * the source is changed. Fires `sourceset` just after the source has changed
  16647. */
  16648. setupSourcesetHandling_() {
  16649. setupSourceset(this);
  16650. }
  16651. /**
  16652. * When a captions track is enabled in the iOS Safari native player, all other
  16653. * tracks are disabled (including metadata tracks), which nulls all of their
  16654. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  16655. * state in those cases so that cue points are not needlessly lost.
  16656. *
  16657. * @private
  16658. */
  16659. restoreMetadataTracksInIOSNativePlayer_() {
  16660. const textTracks = this.textTracks();
  16661. let metadataTracksPreFullscreenState;
  16662. // captures a snapshot of every metadata track's current state
  16663. const takeMetadataTrackSnapshot = () => {
  16664. metadataTracksPreFullscreenState = [];
  16665. for (let i = 0; i < textTracks.length; i++) {
  16666. const track = textTracks[i];
  16667. if (track.kind === 'metadata') {
  16668. metadataTracksPreFullscreenState.push({
  16669. track,
  16670. storedMode: track.mode
  16671. });
  16672. }
  16673. }
  16674. };
  16675. // snapshot each metadata track's initial state, and update the snapshot
  16676. // each time there is a track 'change' event
  16677. takeMetadataTrackSnapshot();
  16678. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16679. this.on('dispose', () => textTracks.removeEventListener('change', takeMetadataTrackSnapshot));
  16680. const restoreTrackMode = () => {
  16681. for (let i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  16682. const storedTrack = metadataTracksPreFullscreenState[i];
  16683. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  16684. storedTrack.track.mode = storedTrack.storedMode;
  16685. }
  16686. }
  16687. // we only want this handler to be executed on the first 'change' event
  16688. textTracks.removeEventListener('change', restoreTrackMode);
  16689. };
  16690. // when we enter fullscreen playback, stop updating the snapshot and
  16691. // restore all track modes to their pre-fullscreen state
  16692. this.on('webkitbeginfullscreen', () => {
  16693. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16694. // remove the listener before adding it just in case it wasn't previously removed
  16695. textTracks.removeEventListener('change', restoreTrackMode);
  16696. textTracks.addEventListener('change', restoreTrackMode);
  16697. });
  16698. // start updating the snapshot again after leaving fullscreen
  16699. this.on('webkitendfullscreen', () => {
  16700. // remove the listener before adding it just in case it wasn't previously removed
  16701. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  16702. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  16703. // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  16704. textTracks.removeEventListener('change', restoreTrackMode);
  16705. });
  16706. }
  16707. /**
  16708. * Attempt to force override of tracks for the given type
  16709. *
  16710. * @param {string} type - Track type to override, possible values include 'Audio',
  16711. * 'Video', and 'Text'.
  16712. * @param {boolean} override - If set to true native audio/video will be overridden,
  16713. * otherwise native audio/video will potentially be used.
  16714. * @private
  16715. */
  16716. overrideNative_(type, override) {
  16717. // If there is no behavioral change don't add/remove listeners
  16718. if (override !== this[`featuresNative${type}Tracks`]) {
  16719. return;
  16720. }
  16721. const lowerCaseType = type.toLowerCase();
  16722. if (this[`${lowerCaseType}TracksListeners_`]) {
  16723. Object.keys(this[`${lowerCaseType}TracksListeners_`]).forEach(eventName => {
  16724. const elTracks = this.el()[`${lowerCaseType}Tracks`];
  16725. elTracks.removeEventListener(eventName, this[`${lowerCaseType}TracksListeners_`][eventName]);
  16726. });
  16727. }
  16728. this[`featuresNative${type}Tracks`] = !override;
  16729. this[`${lowerCaseType}TracksListeners_`] = null;
  16730. this.proxyNativeTracksForType_(lowerCaseType);
  16731. }
  16732. /**
  16733. * Attempt to force override of native audio tracks.
  16734. *
  16735. * @param {boolean} override - If set to true native audio will be overridden,
  16736. * otherwise native audio will potentially be used.
  16737. */
  16738. overrideNativeAudioTracks(override) {
  16739. this.overrideNative_('Audio', override);
  16740. }
  16741. /**
  16742. * Attempt to force override of native video tracks.
  16743. *
  16744. * @param {boolean} override - If set to true native video will be overridden,
  16745. * otherwise native video will potentially be used.
  16746. */
  16747. overrideNativeVideoTracks(override) {
  16748. this.overrideNative_('Video', override);
  16749. }
  16750. /**
  16751. * Proxy native track list events for the given type to our track
  16752. * lists if the browser we are playing in supports that type of track list.
  16753. *
  16754. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  16755. * @private
  16756. */
  16757. proxyNativeTracksForType_(name) {
  16758. const props = NORMAL[name];
  16759. const elTracks = this.el()[props.getterName];
  16760. const techTracks = this[props.getterName]();
  16761. if (!this[`featuresNative${props.capitalName}Tracks`] || !elTracks || !elTracks.addEventListener) {
  16762. return;
  16763. }
  16764. const listeners = {
  16765. change: e => {
  16766. const event = {
  16767. type: 'change',
  16768. target: techTracks,
  16769. currentTarget: techTracks,
  16770. srcElement: techTracks
  16771. };
  16772. techTracks.trigger(event);
  16773. // if we are a text track change event, we should also notify the
  16774. // remote text track list. This can potentially cause a false positive
  16775. // if we were to get a change event on a non-remote track and
  16776. // we triggered the event on the remote text track list which doesn't
  16777. // contain that track. However, best practices mean looping through the
  16778. // list of tracks and searching for the appropriate mode value, so,
  16779. // this shouldn't pose an issue
  16780. if (name === 'text') {
  16781. this[REMOTE.remoteText.getterName]().trigger(event);
  16782. }
  16783. },
  16784. addtrack(e) {
  16785. techTracks.addTrack(e.track);
  16786. },
  16787. removetrack(e) {
  16788. techTracks.removeTrack(e.track);
  16789. }
  16790. };
  16791. const removeOldTracks = function () {
  16792. const removeTracks = [];
  16793. for (let i = 0; i < techTracks.length; i++) {
  16794. let found = false;
  16795. for (let j = 0; j < elTracks.length; j++) {
  16796. if (elTracks[j] === techTracks[i]) {
  16797. found = true;
  16798. break;
  16799. }
  16800. }
  16801. if (!found) {
  16802. removeTracks.push(techTracks[i]);
  16803. }
  16804. }
  16805. while (removeTracks.length) {
  16806. techTracks.removeTrack(removeTracks.shift());
  16807. }
  16808. };
  16809. this[props.getterName + 'Listeners_'] = listeners;
  16810. Object.keys(listeners).forEach(eventName => {
  16811. const listener = listeners[eventName];
  16812. elTracks.addEventListener(eventName, listener);
  16813. this.on('dispose', e => elTracks.removeEventListener(eventName, listener));
  16814. });
  16815. // Remove (native) tracks that are not used anymore
  16816. this.on('loadstart', removeOldTracks);
  16817. this.on('dispose', e => this.off('loadstart', removeOldTracks));
  16818. }
  16819. /**
  16820. * Proxy all native track list events to our track lists if the browser we are playing
  16821. * in supports that type of track list.
  16822. *
  16823. * @private
  16824. */
  16825. proxyNativeTracks_() {
  16826. NORMAL.names.forEach(name => {
  16827. this.proxyNativeTracksForType_(name);
  16828. });
  16829. }
  16830. /**
  16831. * Create the `Html5` Tech's DOM element.
  16832. *
  16833. * @return {Element}
  16834. * The element that gets created.
  16835. */
  16836. createEl() {
  16837. let el = this.options_.tag;
  16838. // Check if this browser supports moving the element into the box.
  16839. // On the iPhone video will break if you move the element,
  16840. // So we have to create a brand new element.
  16841. // If we ingested the player div, we do not need to move the media element.
  16842. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  16843. // If the original tag is still there, clone and remove it.
  16844. if (el) {
  16845. const clone = el.cloneNode(true);
  16846. if (el.parentNode) {
  16847. el.parentNode.insertBefore(clone, el);
  16848. }
  16849. Html5.disposeMediaElement(el);
  16850. el = clone;
  16851. } else {
  16852. el = document__default["default"].createElement('video');
  16853. // determine if native controls should be used
  16854. const tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  16855. const attributes = merge$1({}, tagAttributes);
  16856. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  16857. delete attributes.controls;
  16858. }
  16859. setAttributes(el, Object.assign(attributes, {
  16860. id: this.options_.techId,
  16861. class: 'vjs-tech'
  16862. }));
  16863. }
  16864. el.playerId = this.options_.playerId;
  16865. }
  16866. if (typeof this.options_.preload !== 'undefined') {
  16867. setAttribute(el, 'preload', this.options_.preload);
  16868. }
  16869. if (this.options_.disablePictureInPicture !== undefined) {
  16870. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  16871. }
  16872. // Update specific tag settings, in case they were overridden
  16873. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  16874. // when iOS/Safari or other browsers attempt to autoplay.
  16875. const settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  16876. for (let i = 0; i < settingsAttrs.length; i++) {
  16877. const attr = settingsAttrs[i];
  16878. const value = this.options_[attr];
  16879. if (typeof value !== 'undefined') {
  16880. if (value) {
  16881. setAttribute(el, attr, attr);
  16882. } else {
  16883. removeAttribute(el, attr);
  16884. }
  16885. el[attr] = value;
  16886. }
  16887. }
  16888. return el;
  16889. }
  16890. /**
  16891. * This will be triggered if the loadstart event has already fired, before videojs was
  16892. * ready. Two known examples of when this can happen are:
  16893. * 1. If we're loading the playback object after it has started loading
  16894. * 2. The media is already playing the (often with autoplay on) then
  16895. *
  16896. * This function will fire another loadstart so that videojs can catchup.
  16897. *
  16898. * @fires Tech#loadstart
  16899. *
  16900. * @return {undefined}
  16901. * returns nothing.
  16902. */
  16903. handleLateInit_(el) {
  16904. if (el.networkState === 0 || el.networkState === 3) {
  16905. // The video element hasn't started loading the source yet
  16906. // or didn't find a source
  16907. return;
  16908. }
  16909. if (el.readyState === 0) {
  16910. // NetworkState is set synchronously BUT loadstart is fired at the
  16911. // end of the current stack, usually before setInterval(fn, 0).
  16912. // So at this point we know loadstart may have already fired or is
  16913. // about to fire, and either way the player hasn't seen it yet.
  16914. // We don't want to fire loadstart prematurely here and cause a
  16915. // double loadstart so we'll wait and see if it happens between now
  16916. // and the next loop, and fire it if not.
  16917. // HOWEVER, we also want to make sure it fires before loadedmetadata
  16918. // which could also happen between now and the next loop, so we'll
  16919. // watch for that also.
  16920. let loadstartFired = false;
  16921. const setLoadstartFired = function () {
  16922. loadstartFired = true;
  16923. };
  16924. this.on('loadstart', setLoadstartFired);
  16925. const triggerLoadstart = function () {
  16926. // We did miss the original loadstart. Make sure the player
  16927. // sees loadstart before loadedmetadata
  16928. if (!loadstartFired) {
  16929. this.trigger('loadstart');
  16930. }
  16931. };
  16932. this.on('loadedmetadata', triggerLoadstart);
  16933. this.ready(function () {
  16934. this.off('loadstart', setLoadstartFired);
  16935. this.off('loadedmetadata', triggerLoadstart);
  16936. if (!loadstartFired) {
  16937. // We did miss the original native loadstart. Fire it now.
  16938. this.trigger('loadstart');
  16939. }
  16940. });
  16941. return;
  16942. }
  16943. // From here on we know that loadstart already fired and we missed it.
  16944. // The other readyState events aren't as much of a problem if we double
  16945. // them, so not going to go to as much trouble as loadstart to prevent
  16946. // that unless we find reason to.
  16947. const eventsToTrigger = ['loadstart'];
  16948. // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  16949. eventsToTrigger.push('loadedmetadata');
  16950. // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  16951. if (el.readyState >= 2) {
  16952. eventsToTrigger.push('loadeddata');
  16953. }
  16954. // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  16955. if (el.readyState >= 3) {
  16956. eventsToTrigger.push('canplay');
  16957. }
  16958. // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  16959. if (el.readyState >= 4) {
  16960. eventsToTrigger.push('canplaythrough');
  16961. }
  16962. // We still need to give the player time to add event listeners
  16963. this.ready(function () {
  16964. eventsToTrigger.forEach(function (type) {
  16965. this.trigger(type);
  16966. }, this);
  16967. });
  16968. }
  16969. /**
  16970. * Set whether we are scrubbing or not.
  16971. * This is used to decide whether we should use `fastSeek` or not.
  16972. * `fastSeek` is used to provide trick play on Safari browsers.
  16973. *
  16974. * @param {boolean} isScrubbing
  16975. * - true for we are currently scrubbing
  16976. * - false for we are no longer scrubbing
  16977. */
  16978. setScrubbing(isScrubbing) {
  16979. this.isScrubbing_ = isScrubbing;
  16980. }
  16981. /**
  16982. * Get whether we are scrubbing or not.
  16983. *
  16984. * @return {boolean} isScrubbing
  16985. * - true for we are currently scrubbing
  16986. * - false for we are no longer scrubbing
  16987. */
  16988. scrubbing() {
  16989. return this.isScrubbing_;
  16990. }
  16991. /**
  16992. * Set current time for the `HTML5` tech.
  16993. *
  16994. * @param {number} seconds
  16995. * Set the current time of the media to this.
  16996. */
  16997. setCurrentTime(seconds) {
  16998. try {
  16999. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  17000. this.el_.fastSeek(seconds);
  17001. } else {
  17002. this.el_.currentTime = seconds;
  17003. }
  17004. } catch (e) {
  17005. log$1(e, 'Video is not ready. (Video.js)');
  17006. // this.warning(VideoJS.warnings.videoNotReady);
  17007. }
  17008. }
  17009. /**
  17010. * Get the current duration of the HTML5 media element.
  17011. *
  17012. * @return {number}
  17013. * The duration of the media or 0 if there is no duration.
  17014. */
  17015. duration() {
  17016. // Android Chrome will report duration as Infinity for VOD HLS until after
  17017. // playback has started, which triggers the live display erroneously.
  17018. // Return NaN if playback has not started and trigger a durationupdate once
  17019. // the duration can be reliably known.
  17020. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  17021. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17022. // several with 0
  17023. const checkProgress = () => {
  17024. if (this.el_.currentTime > 0) {
  17025. // Trigger durationchange for genuinely live video
  17026. if (this.el_.duration === Infinity) {
  17027. this.trigger('durationchange');
  17028. }
  17029. this.off('timeupdate', checkProgress);
  17030. }
  17031. };
  17032. this.on('timeupdate', checkProgress);
  17033. return NaN;
  17034. }
  17035. return this.el_.duration || NaN;
  17036. }
  17037. /**
  17038. * Get the current width of the HTML5 media element.
  17039. *
  17040. * @return {number}
  17041. * The width of the HTML5 media element.
  17042. */
  17043. width() {
  17044. return this.el_.offsetWidth;
  17045. }
  17046. /**
  17047. * Get the current height of the HTML5 media element.
  17048. *
  17049. * @return {number}
  17050. * The height of the HTML5 media element.
  17051. */
  17052. height() {
  17053. return this.el_.offsetHeight;
  17054. }
  17055. /**
  17056. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17057. * `fullscreenchange` event.
  17058. *
  17059. * @private
  17060. * @fires fullscreenchange
  17061. * @listens webkitendfullscreen
  17062. * @listens webkitbeginfullscreen
  17063. * @listens webkitbeginfullscreen
  17064. */
  17065. proxyWebkitFullscreen_() {
  17066. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17067. return;
  17068. }
  17069. const endFn = function () {
  17070. this.trigger('fullscreenchange', {
  17071. isFullscreen: false
  17072. });
  17073. // Safari will sometimes set controls on the videoelement when existing fullscreen.
  17074. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17075. this.el_.controls = false;
  17076. }
  17077. };
  17078. const beginFn = function () {
  17079. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17080. this.one('webkitendfullscreen', endFn);
  17081. this.trigger('fullscreenchange', {
  17082. isFullscreen: true,
  17083. // set a flag in case another tech triggers fullscreenchange
  17084. nativeIOSFullscreen: true
  17085. });
  17086. }
  17087. };
  17088. this.on('webkitbeginfullscreen', beginFn);
  17089. this.on('dispose', () => {
  17090. this.off('webkitbeginfullscreen', beginFn);
  17091. this.off('webkitendfullscreen', endFn);
  17092. });
  17093. }
  17094. /**
  17095. * Check if fullscreen is supported on the video el.
  17096. *
  17097. * @return {boolean}
  17098. * - True if fullscreen is supported.
  17099. * - False if fullscreen is not supported.
  17100. */
  17101. supportsFullScreen() {
  17102. return typeof this.el_.webkitEnterFullScreen === 'function';
  17103. }
  17104. /**
  17105. * Request that the `HTML5` Tech enter fullscreen.
  17106. */
  17107. enterFullScreen() {
  17108. const video = this.el_;
  17109. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17110. // attempt to prime the video element for programmatic access
  17111. // this isn't necessary on the desktop but shouldn't hurt
  17112. silencePromise(this.el_.play());
  17113. // playing and pausing synchronously during the transition to fullscreen
  17114. // can get iOS ~6.1 devices into a play/pause loop
  17115. this.setTimeout(function () {
  17116. video.pause();
  17117. try {
  17118. video.webkitEnterFullScreen();
  17119. } catch (e) {
  17120. this.trigger('fullscreenerror', e);
  17121. }
  17122. }, 0);
  17123. } else {
  17124. try {
  17125. video.webkitEnterFullScreen();
  17126. } catch (e) {
  17127. this.trigger('fullscreenerror', e);
  17128. }
  17129. }
  17130. }
  17131. /**
  17132. * Request that the `HTML5` Tech exit fullscreen.
  17133. */
  17134. exitFullScreen() {
  17135. if (!this.el_.webkitDisplayingFullscreen) {
  17136. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  17137. return;
  17138. }
  17139. this.el_.webkitExitFullScreen();
  17140. }
  17141. /**
  17142. * Create a floating video window always on top of other windows so that users may
  17143. * continue consuming media while they interact with other content sites, or
  17144. * applications on their device.
  17145. *
  17146. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  17147. *
  17148. * @return {Promise}
  17149. * A promise with a Picture-in-Picture window.
  17150. */
  17151. requestPictureInPicture() {
  17152. return this.el_.requestPictureInPicture();
  17153. }
  17154. /**
  17155. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  17156. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  17157. * Needs to be checked later than the constructor
  17158. * This will be a false positive for clear sources loaded after a Fairplay source
  17159. *
  17160. * @param {function} cb function to call
  17161. * @return {number} id of request
  17162. */
  17163. requestVideoFrameCallback(cb) {
  17164. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17165. return this.el_.requestVideoFrameCallback(cb);
  17166. }
  17167. return super.requestVideoFrameCallback(cb);
  17168. }
  17169. /**
  17170. * Native or fallback requestVideoFrameCallback
  17171. *
  17172. * @param {number} id request id to cancel
  17173. */
  17174. cancelVideoFrameCallback(id) {
  17175. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17176. this.el_.cancelVideoFrameCallback(id);
  17177. } else {
  17178. super.cancelVideoFrameCallback(id);
  17179. }
  17180. }
  17181. /**
  17182. * A getter/setter for the `Html5` Tech's source object.
  17183. * > Note: Please use {@link Html5#setSource}
  17184. *
  17185. * @param {Tech~SourceObject} [src]
  17186. * The source object you want to set on the `HTML5` techs element.
  17187. *
  17188. * @return {Tech~SourceObject|undefined}
  17189. * - The current source object when a source is not passed in.
  17190. * - undefined when setting
  17191. *
  17192. * @deprecated Since version 5.
  17193. */
  17194. src(src) {
  17195. if (src === undefined) {
  17196. return this.el_.src;
  17197. }
  17198. // Setting src through `src` instead of `setSrc` will be deprecated
  17199. this.setSrc(src);
  17200. }
  17201. /**
  17202. * Reset the tech by removing all sources and then calling
  17203. * {@link Html5.resetMediaElement}.
  17204. */
  17205. reset() {
  17206. Html5.resetMediaElement(this.el_);
  17207. }
  17208. /**
  17209. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  17210. * the HTML5 media element.
  17211. *
  17212. * @return {Tech~SourceObject}
  17213. * The current source object from the HTML5 tech. With a fallback to the
  17214. * elements source.
  17215. */
  17216. currentSrc() {
  17217. if (this.currentSource_) {
  17218. return this.currentSource_.src;
  17219. }
  17220. return this.el_.currentSrc;
  17221. }
  17222. /**
  17223. * Set controls attribute for the HTML5 media Element.
  17224. *
  17225. * @param {string} val
  17226. * Value to set the controls attribute to
  17227. */
  17228. setControls(val) {
  17229. this.el_.controls = !!val;
  17230. }
  17231. /**
  17232. * Create and returns a remote {@link TextTrack} object.
  17233. *
  17234. * @param {string} kind
  17235. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  17236. *
  17237. * @param {string} [label]
  17238. * Label to identify the text track
  17239. *
  17240. * @param {string} [language]
  17241. * Two letter language abbreviation
  17242. *
  17243. * @return {TextTrack}
  17244. * The TextTrack that gets created.
  17245. */
  17246. addTextTrack(kind, label, language) {
  17247. if (!this.featuresNativeTextTracks) {
  17248. return super.addTextTrack(kind, label, language);
  17249. }
  17250. return this.el_.addTextTrack(kind, label, language);
  17251. }
  17252. /**
  17253. * Creates either native TextTrack or an emulated TextTrack depending
  17254. * on the value of `featuresNativeTextTracks`
  17255. *
  17256. * @param {Object} options
  17257. * The object should contain the options to initialize the TextTrack with.
  17258. *
  17259. * @param {string} [options.kind]
  17260. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  17261. *
  17262. * @param {string} [options.label]
  17263. * Label to identify the text track
  17264. *
  17265. * @param {string} [options.language]
  17266. * Two letter language abbreviation.
  17267. *
  17268. * @param {boolean} [options.default]
  17269. * Default this track to on.
  17270. *
  17271. * @param {string} [options.id]
  17272. * The internal id to assign this track.
  17273. *
  17274. * @param {string} [options.src]
  17275. * A source url for the track.
  17276. *
  17277. * @return {HTMLTrackElement}
  17278. * The track element that gets created.
  17279. */
  17280. createRemoteTextTrack(options) {
  17281. if (!this.featuresNativeTextTracks) {
  17282. return super.createRemoteTextTrack(options);
  17283. }
  17284. const htmlTrackElement = document__default["default"].createElement('track');
  17285. if (options.kind) {
  17286. htmlTrackElement.kind = options.kind;
  17287. }
  17288. if (options.label) {
  17289. htmlTrackElement.label = options.label;
  17290. }
  17291. if (options.language || options.srclang) {
  17292. htmlTrackElement.srclang = options.language || options.srclang;
  17293. }
  17294. if (options.default) {
  17295. htmlTrackElement.default = options.default;
  17296. }
  17297. if (options.id) {
  17298. htmlTrackElement.id = options.id;
  17299. }
  17300. if (options.src) {
  17301. htmlTrackElement.src = options.src;
  17302. }
  17303. return htmlTrackElement;
  17304. }
  17305. /**
  17306. * Creates a remote text track object and returns an html track element.
  17307. *
  17308. * @param {Object} options The object should contain values for
  17309. * kind, language, label, and src (location of the WebVTT file)
  17310. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack
  17311. * will not be removed from the TextTrackList and HtmlTrackElementList
  17312. * after a source change
  17313. * @return {HTMLTrackElement} An Html Track Element.
  17314. * This can be an emulated {@link HTMLTrackElement} or a native one.
  17315. *
  17316. */
  17317. addRemoteTextTrack(options, manualCleanup) {
  17318. const htmlTrackElement = super.addRemoteTextTrack(options, manualCleanup);
  17319. if (this.featuresNativeTextTracks) {
  17320. this.el().appendChild(htmlTrackElement);
  17321. }
  17322. return htmlTrackElement;
  17323. }
  17324. /**
  17325. * Remove remote `TextTrack` from `TextTrackList` object
  17326. *
  17327. * @param {TextTrack} track
  17328. * `TextTrack` object to remove
  17329. */
  17330. removeRemoteTextTrack(track) {
  17331. super.removeRemoteTextTrack(track);
  17332. if (this.featuresNativeTextTracks) {
  17333. const tracks = this.$$('track');
  17334. let i = tracks.length;
  17335. while (i--) {
  17336. if (track === tracks[i] || track === tracks[i].track) {
  17337. this.el().removeChild(tracks[i]);
  17338. }
  17339. }
  17340. }
  17341. }
  17342. /**
  17343. * Gets available media playback quality metrics as specified by the W3C's Media
  17344. * Playback Quality API.
  17345. *
  17346. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  17347. *
  17348. * @return {Object}
  17349. * An object with supported media playback quality metrics
  17350. */
  17351. getVideoPlaybackQuality() {
  17352. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  17353. return this.el().getVideoPlaybackQuality();
  17354. }
  17355. const videoPlaybackQuality = {};
  17356. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  17357. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  17358. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  17359. }
  17360. if (window__default["default"].performance) {
  17361. videoPlaybackQuality.creationTime = window__default["default"].performance.now();
  17362. }
  17363. return videoPlaybackQuality;
  17364. }
  17365. }
  17366. /* HTML5 Support Testing ---------------------------------------------------- */
  17367. /**
  17368. * Element for testing browser HTML5 media capabilities
  17369. *
  17370. * @type {Element}
  17371. * @constant
  17372. * @private
  17373. */
  17374. defineLazyProperty(Html5, 'TEST_VID', function () {
  17375. if (!isReal()) {
  17376. return;
  17377. }
  17378. const video = document__default["default"].createElement('video');
  17379. const track = document__default["default"].createElement('track');
  17380. track.kind = 'captions';
  17381. track.srclang = 'en';
  17382. track.label = 'English';
  17383. video.appendChild(track);
  17384. return video;
  17385. });
  17386. /**
  17387. * Check if HTML5 media is supported by this browser/device.
  17388. *
  17389. * @return {boolean}
  17390. * - True if HTML5 media is supported.
  17391. * - False if HTML5 media is not supported.
  17392. */
  17393. Html5.isSupported = function () {
  17394. // IE with no Media Player is a LIAR! (#984)
  17395. try {
  17396. Html5.TEST_VID.volume = 0.5;
  17397. } catch (e) {
  17398. return false;
  17399. }
  17400. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  17401. };
  17402. /**
  17403. * Check if the tech can support the given type
  17404. *
  17405. * @param {string} type
  17406. * The mimetype to check
  17407. * @return {string} 'probably', 'maybe', or '' (empty string)
  17408. */
  17409. Html5.canPlayType = function (type) {
  17410. return Html5.TEST_VID.canPlayType(type);
  17411. };
  17412. /**
  17413. * Check if the tech can support the given source
  17414. *
  17415. * @param {Object} srcObj
  17416. * The source object
  17417. * @param {Object} options
  17418. * The options passed to the tech
  17419. * @return {string} 'probably', 'maybe', or '' (empty string)
  17420. */
  17421. Html5.canPlaySource = function (srcObj, options) {
  17422. return Html5.canPlayType(srcObj.type);
  17423. };
  17424. /**
  17425. * Check if the volume can be changed in this browser/device.
  17426. * Volume cannot be changed in a lot of mobile devices.
  17427. * Specifically, it can't be changed from 1 on iOS.
  17428. *
  17429. * @return {boolean}
  17430. * - True if volume can be controlled
  17431. * - False otherwise
  17432. */
  17433. Html5.canControlVolume = function () {
  17434. // IE will error if Windows Media Player not installed #3315
  17435. try {
  17436. const volume = Html5.TEST_VID.volume;
  17437. Html5.TEST_VID.volume = volume / 2 + 0.1;
  17438. const canControl = volume !== Html5.TEST_VID.volume;
  17439. // With the introduction of iOS 15, there are cases where the volume is read as
  17440. // changed but reverts back to its original state at the start of the next tick.
  17441. // To determine whether volume can be controlled on iOS,
  17442. // a timeout is set and the volume is checked asynchronously.
  17443. // Since `features` doesn't currently work asynchronously, the value is manually set.
  17444. if (canControl && IS_IOS) {
  17445. window__default["default"].setTimeout(() => {
  17446. if (Html5 && Html5.prototype) {
  17447. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  17448. }
  17449. });
  17450. // default iOS to false, which will be updated in the timeout above.
  17451. return false;
  17452. }
  17453. return canControl;
  17454. } catch (e) {
  17455. return false;
  17456. }
  17457. };
  17458. /**
  17459. * Check if the volume can be muted in this browser/device.
  17460. * Some devices, e.g. iOS, don't allow changing volume
  17461. * but permits muting/unmuting.
  17462. *
  17463. * @return {boolean}
  17464. * - True if volume can be muted
  17465. * - False otherwise
  17466. */
  17467. Html5.canMuteVolume = function () {
  17468. try {
  17469. const muted = Html5.TEST_VID.muted;
  17470. // in some versions of iOS muted property doesn't always
  17471. // work, so we want to set both property and attribute
  17472. Html5.TEST_VID.muted = !muted;
  17473. if (Html5.TEST_VID.muted) {
  17474. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  17475. } else {
  17476. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  17477. }
  17478. return muted !== Html5.TEST_VID.muted;
  17479. } catch (e) {
  17480. return false;
  17481. }
  17482. };
  17483. /**
  17484. * Check if the playback rate can be changed in this browser/device.
  17485. *
  17486. * @return {boolean}
  17487. * - True if playback rate can be controlled
  17488. * - False otherwise
  17489. */
  17490. Html5.canControlPlaybackRate = function () {
  17491. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  17492. // https://github.com/videojs/video.js/issues/3180
  17493. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  17494. return false;
  17495. }
  17496. // IE will error if Windows Media Player not installed #3315
  17497. try {
  17498. const playbackRate = Html5.TEST_VID.playbackRate;
  17499. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  17500. return playbackRate !== Html5.TEST_VID.playbackRate;
  17501. } catch (e) {
  17502. return false;
  17503. }
  17504. };
  17505. /**
  17506. * Check if we can override a video/audio elements attributes, with
  17507. * Object.defineProperty.
  17508. *
  17509. * @return {boolean}
  17510. * - True if builtin attributes can be overridden
  17511. * - False otherwise
  17512. */
  17513. Html5.canOverrideAttributes = function () {
  17514. // if we cannot overwrite the src/innerHTML property, there is no support
  17515. // iOS 7 safari for instance cannot do this.
  17516. try {
  17517. const noop = () => {};
  17518. Object.defineProperty(document__default["default"].createElement('video'), 'src', {
  17519. get: noop,
  17520. set: noop
  17521. });
  17522. Object.defineProperty(document__default["default"].createElement('audio'), 'src', {
  17523. get: noop,
  17524. set: noop
  17525. });
  17526. Object.defineProperty(document__default["default"].createElement('video'), 'innerHTML', {
  17527. get: noop,
  17528. set: noop
  17529. });
  17530. Object.defineProperty(document__default["default"].createElement('audio'), 'innerHTML', {
  17531. get: noop,
  17532. set: noop
  17533. });
  17534. } catch (e) {
  17535. return false;
  17536. }
  17537. return true;
  17538. };
  17539. /**
  17540. * Check to see if native `TextTrack`s are supported by this browser/device.
  17541. *
  17542. * @return {boolean}
  17543. * - True if native `TextTrack`s are supported.
  17544. * - False otherwise
  17545. */
  17546. Html5.supportsNativeTextTracks = function () {
  17547. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  17548. };
  17549. /**
  17550. * Check to see if native `VideoTrack`s are supported by this browser/device
  17551. *
  17552. * @return {boolean}
  17553. * - True if native `VideoTrack`s are supported.
  17554. * - False otherwise
  17555. */
  17556. Html5.supportsNativeVideoTracks = function () {
  17557. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  17558. };
  17559. /**
  17560. * Check to see if native `AudioTrack`s are supported by this browser/device
  17561. *
  17562. * @return {boolean}
  17563. * - True if native `AudioTrack`s are supported.
  17564. * - False otherwise
  17565. */
  17566. Html5.supportsNativeAudioTracks = function () {
  17567. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  17568. };
  17569. /**
  17570. * An array of events available on the Html5 tech.
  17571. *
  17572. * @private
  17573. * @type {Array}
  17574. */
  17575. Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
  17576. /**
  17577. * Boolean indicating whether the `Tech` supports volume control.
  17578. *
  17579. * @type {boolean}
  17580. * @default {@link Html5.canControlVolume}
  17581. */
  17582. /**
  17583. * Boolean indicating whether the `Tech` supports muting volume.
  17584. *
  17585. * @type {boolean}
  17586. * @default {@link Html5.canMuteVolume}
  17587. */
  17588. /**
  17589. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  17590. * plays. Examples:
  17591. * - Set player to play 2x (twice) as fast
  17592. * - Set player to play 0.5x (half) as fast
  17593. *
  17594. * @type {boolean}
  17595. * @default {@link Html5.canControlPlaybackRate}
  17596. */
  17597. /**
  17598. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  17599. *
  17600. * @type {boolean}
  17601. * @default
  17602. */
  17603. /**
  17604. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  17605. *
  17606. * @type {boolean}
  17607. * @default {@link Html5.supportsNativeTextTracks}
  17608. */
  17609. /**
  17610. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  17611. *
  17612. * @type {boolean}
  17613. * @default {@link Html5.supportsNativeVideoTracks}
  17614. */
  17615. /**
  17616. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  17617. *
  17618. * @type {boolean}
  17619. * @default {@link Html5.supportsNativeAudioTracks}
  17620. */
  17621. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function ([key, fn]) {
  17622. defineLazyProperty(Html5.prototype, key, () => Html5[fn](), true);
  17623. });
  17624. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  17625. /**
  17626. * Boolean indicating whether the `HTML5` tech currently supports the media element
  17627. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  17628. * false there. Everywhere else this should be true.
  17629. *
  17630. * @type {boolean}
  17631. * @default
  17632. */
  17633. Html5.prototype.movingMediaElementInDOM = !IS_IOS;
  17634. // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  17635. // Is this true?
  17636. /**
  17637. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  17638. * when going into fullscreen.
  17639. *
  17640. * @type {boolean}
  17641. * @default
  17642. */
  17643. Html5.prototype.featuresFullscreenResize = true;
  17644. /**
  17645. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  17646. * If this is false, manual `progress` events will be triggered instead.
  17647. *
  17648. * @type {boolean}
  17649. * @default
  17650. */
  17651. Html5.prototype.featuresProgressEvents = true;
  17652. /**
  17653. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  17654. * If this is false, manual `timeupdate` events will be triggered instead.
  17655. *
  17656. * @default
  17657. */
  17658. Html5.prototype.featuresTimeupdateEvents = true;
  17659. /**
  17660. * Whether the HTML5 el supports `requestVideoFrameCallback`
  17661. *
  17662. * @type {boolean}
  17663. */
  17664. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback);
  17665. Html5.disposeMediaElement = function (el) {
  17666. if (!el) {
  17667. return;
  17668. }
  17669. if (el.parentNode) {
  17670. el.parentNode.removeChild(el);
  17671. }
  17672. // remove any child track or source nodes to prevent their loading
  17673. while (el.hasChildNodes()) {
  17674. el.removeChild(el.firstChild);
  17675. }
  17676. // remove any src reference. not setting `src=''` because that causes a warning
  17677. // in firefox
  17678. el.removeAttribute('src');
  17679. // force the media element to update its loading state by calling load()
  17680. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  17681. if (typeof el.load === 'function') {
  17682. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17683. (function () {
  17684. try {
  17685. el.load();
  17686. } catch (e) {
  17687. // not supported
  17688. }
  17689. })();
  17690. }
  17691. };
  17692. Html5.resetMediaElement = function (el) {
  17693. if (!el) {
  17694. return;
  17695. }
  17696. const sources = el.querySelectorAll('source');
  17697. let i = sources.length;
  17698. while (i--) {
  17699. el.removeChild(sources[i]);
  17700. }
  17701. // remove any src reference.
  17702. // not setting `src=''` because that throws an error
  17703. el.removeAttribute('src');
  17704. if (typeof el.load === 'function') {
  17705. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  17706. (function () {
  17707. try {
  17708. el.load();
  17709. } catch (e) {
  17710. // satisfy linter
  17711. }
  17712. })();
  17713. }
  17714. };
  17715. /* Native HTML5 element property wrapping ----------------------------------- */
  17716. // Wrap native boolean attributes with getters that check both property and attribute
  17717. // The list is as followed:
  17718. // muted, defaultMuted, autoplay, controls, loop, playsinline
  17719. [
  17720. /**
  17721. * Get the value of `muted` from the media element. `muted` indicates
  17722. * that the volume for the media should be set to silent. This does not actually change
  17723. * the `volume` attribute.
  17724. *
  17725. * @method Html5#muted
  17726. * @return {boolean}
  17727. * - True if the value of `volume` should be ignored and the audio set to silent.
  17728. * - False if the value of `volume` should be used.
  17729. *
  17730. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17731. */
  17732. 'muted',
  17733. /**
  17734. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  17735. * whether the media should start muted or not. Only changes the default state of the
  17736. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  17737. * current state.
  17738. *
  17739. * @method Html5#defaultMuted
  17740. * @return {boolean}
  17741. * - The value of `defaultMuted` from the media element.
  17742. * - True indicates that the media should start muted.
  17743. * - False indicates that the media should not start muted
  17744. *
  17745. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17746. */
  17747. 'defaultMuted',
  17748. /**
  17749. * Get the value of `autoplay` from the media element. `autoplay` indicates
  17750. * that the media should start to play as soon as the page is ready.
  17751. *
  17752. * @method Html5#autoplay
  17753. * @return {boolean}
  17754. * - The value of `autoplay` from the media element.
  17755. * - True indicates that the media should start as soon as the page loads.
  17756. * - False indicates that the media should not start as soon as the page loads.
  17757. *
  17758. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17759. */
  17760. 'autoplay',
  17761. /**
  17762. * Get the value of `controls` from the media element. `controls` indicates
  17763. * whether the native media controls should be shown or hidden.
  17764. *
  17765. * @method Html5#controls
  17766. * @return {boolean}
  17767. * - The value of `controls` from the media element.
  17768. * - True indicates that native controls should be showing.
  17769. * - False indicates that native controls should be hidden.
  17770. *
  17771. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  17772. */
  17773. 'controls',
  17774. /**
  17775. * Get the value of `loop` from the media element. `loop` indicates
  17776. * that the media should return to the start of the media and continue playing once
  17777. * it reaches the end.
  17778. *
  17779. * @method Html5#loop
  17780. * @return {boolean}
  17781. * - The value of `loop` from the media element.
  17782. * - True indicates that playback should seek back to start once
  17783. * the end of a media is reached.
  17784. * - False indicates that playback should not loop back to the start when the
  17785. * end of the media is reached.
  17786. *
  17787. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17788. */
  17789. 'loop',
  17790. /**
  17791. * Get the value of `playsinline` from the media element. `playsinline` indicates
  17792. * to the browser that non-fullscreen playback is preferred when fullscreen
  17793. * playback is the native default, such as in iOS Safari.
  17794. *
  17795. * @method Html5#playsinline
  17796. * @return {boolean}
  17797. * - The value of `playsinline` from the media element.
  17798. * - True indicates that the media should play inline.
  17799. * - False indicates that the media should not play inline.
  17800. *
  17801. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17802. */
  17803. 'playsinline'].forEach(function (prop) {
  17804. Html5.prototype[prop] = function () {
  17805. return this.el_[prop] || this.el_.hasAttribute(prop);
  17806. };
  17807. });
  17808. // Wrap native boolean attributes with setters that set both property and attribute
  17809. // The list is as followed:
  17810. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  17811. // setControls is special-cased above
  17812. [
  17813. /**
  17814. * Set the value of `muted` on the media element. `muted` indicates that the current
  17815. * audio level should be silent.
  17816. *
  17817. * @method Html5#setMuted
  17818. * @param {boolean} muted
  17819. * - True if the audio should be set to silent
  17820. * - False otherwise
  17821. *
  17822. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  17823. */
  17824. 'muted',
  17825. /**
  17826. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  17827. * audio level should be silent, but will only effect the muted level on initial playback..
  17828. *
  17829. * @method Html5.prototype.setDefaultMuted
  17830. * @param {boolean} defaultMuted
  17831. * - True if the audio should be set to silent
  17832. * - False otherwise
  17833. *
  17834. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  17835. */
  17836. 'defaultMuted',
  17837. /**
  17838. * Set the value of `autoplay` on the media element. `autoplay` indicates
  17839. * that the media should start to play as soon as the page is ready.
  17840. *
  17841. * @method Html5#setAutoplay
  17842. * @param {boolean} autoplay
  17843. * - True indicates that the media should start as soon as the page loads.
  17844. * - False indicates that the media should not start as soon as the page loads.
  17845. *
  17846. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  17847. */
  17848. 'autoplay',
  17849. /**
  17850. * Set the value of `loop` on the media element. `loop` indicates
  17851. * that the media should return to the start of the media and continue playing once
  17852. * it reaches the end.
  17853. *
  17854. * @method Html5#setLoop
  17855. * @param {boolean} loop
  17856. * - True indicates that playback should seek back to start once
  17857. * the end of a media is reached.
  17858. * - False indicates that playback should not loop back to the start when the
  17859. * end of the media is reached.
  17860. *
  17861. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  17862. */
  17863. 'loop',
  17864. /**
  17865. * Set the value of `playsinline` from the media element. `playsinline` indicates
  17866. * to the browser that non-fullscreen playback is preferred when fullscreen
  17867. * playback is the native default, such as in iOS Safari.
  17868. *
  17869. * @method Html5#setPlaysinline
  17870. * @param {boolean} playsinline
  17871. * - True indicates that the media should play inline.
  17872. * - False indicates that the media should not play inline.
  17873. *
  17874. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  17875. */
  17876. 'playsinline'].forEach(function (prop) {
  17877. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  17878. this.el_[prop] = v;
  17879. if (v) {
  17880. this.el_.setAttribute(prop, prop);
  17881. } else {
  17882. this.el_.removeAttribute(prop);
  17883. }
  17884. };
  17885. });
  17886. // Wrap native properties with a getter
  17887. // The list is as followed
  17888. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  17889. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  17890. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  17891. [
  17892. /**
  17893. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  17894. * is currently paused or not.
  17895. *
  17896. * @method Html5#paused
  17897. * @return {boolean}
  17898. * The value of `paused` from the media element.
  17899. *
  17900. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  17901. */
  17902. 'paused',
  17903. /**
  17904. * Get the value of `currentTime` from the media element. `currentTime` indicates
  17905. * the current second that the media is at in playback.
  17906. *
  17907. * @method Html5#currentTime
  17908. * @return {number}
  17909. * The value of `currentTime` from the media element.
  17910. *
  17911. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  17912. */
  17913. 'currentTime',
  17914. /**
  17915. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  17916. * object that represents the parts of the media that are already downloaded and
  17917. * available for playback.
  17918. *
  17919. * @method Html5#buffered
  17920. * @return {TimeRange}
  17921. * The value of `buffered` from the media element.
  17922. *
  17923. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  17924. */
  17925. 'buffered',
  17926. /**
  17927. * Get the value of `volume` from the media element. `volume` indicates
  17928. * the current playback volume of audio for a media. `volume` will be a value from 0
  17929. * (silent) to 1 (loudest and default).
  17930. *
  17931. * @method Html5#volume
  17932. * @return {number}
  17933. * The value of `volume` from the media element. Value will be between 0-1.
  17934. *
  17935. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  17936. */
  17937. 'volume',
  17938. /**
  17939. * Get the value of `poster` from the media element. `poster` indicates
  17940. * that the url of an image file that can/will be shown when no media data is available.
  17941. *
  17942. * @method Html5#poster
  17943. * @return {string}
  17944. * The value of `poster` from the media element. Value will be a url to an
  17945. * image.
  17946. *
  17947. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  17948. */
  17949. 'poster',
  17950. /**
  17951. * Get the value of `preload` from the media element. `preload` indicates
  17952. * what should download before the media is interacted with. It can have the following
  17953. * values:
  17954. * - none: nothing should be downloaded
  17955. * - metadata: poster and the first few frames of the media may be downloaded to get
  17956. * media dimensions and other metadata
  17957. * - auto: allow the media and metadata for the media to be downloaded before
  17958. * interaction
  17959. *
  17960. * @method Html5#preload
  17961. * @return {string}
  17962. * The value of `preload` from the media element. Will be 'none', 'metadata',
  17963. * or 'auto'.
  17964. *
  17965. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  17966. */
  17967. 'preload',
  17968. /**
  17969. * Get the value of the `error` from the media element. `error` indicates any
  17970. * MediaError that may have occurred during playback. If error returns null there is no
  17971. * current error.
  17972. *
  17973. * @method Html5#error
  17974. * @return {MediaError|null}
  17975. * The value of `error` from the media element. Will be `MediaError` if there
  17976. * is a current error and null otherwise.
  17977. *
  17978. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  17979. */
  17980. 'error',
  17981. /**
  17982. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  17983. * media is currently seeking to a new position or not.
  17984. *
  17985. * @method Html5#seeking
  17986. * @return {boolean}
  17987. * - The value of `seeking` from the media element.
  17988. * - True indicates that the media is currently seeking to a new position.
  17989. * - False indicates that the media is not seeking to a new position at this time.
  17990. *
  17991. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  17992. */
  17993. 'seeking',
  17994. /**
  17995. * Get the value of `seekable` from the media element. `seekable` returns a
  17996. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  17997. *
  17998. * @method Html5#seekable
  17999. * @return {TimeRange}
  18000. * The value of `seekable` from the media element. A `TimeRange` object
  18001. * indicating the current ranges of time that can be seeked to.
  18002. *
  18003. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  18004. */
  18005. 'seekable',
  18006. /**
  18007. * Get the value of `ended` from the media element. `ended` indicates whether
  18008. * the media has reached the end or not.
  18009. *
  18010. * @method Html5#ended
  18011. * @return {boolean}
  18012. * - The value of `ended` from the media element.
  18013. * - True indicates that the media has ended.
  18014. * - False indicates that the media has not ended.
  18015. *
  18016. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  18017. */
  18018. 'ended',
  18019. /**
  18020. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  18021. * the rate at which the media is currently playing back. Examples:
  18022. * - if playbackRate is set to 2, media will play twice as fast.
  18023. * - if playbackRate is set to 0.5, media will play half as fast.
  18024. *
  18025. * @method Html5#playbackRate
  18026. * @return {number}
  18027. * The value of `playbackRate` from the media element. A number indicating
  18028. * the current playback speed of the media, where 1 is normal speed.
  18029. *
  18030. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18031. */
  18032. 'playbackRate',
  18033. /**
  18034. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18035. * the rate at which the media is currently playing back. This value will not indicate the current
  18036. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18037. *
  18038. * Examples:
  18039. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18040. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18041. *
  18042. * @method Html5.prototype.defaultPlaybackRate
  18043. * @return {number}
  18044. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18045. * the current playback speed of the media, where 1 is normal speed.
  18046. *
  18047. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18048. */
  18049. 'defaultPlaybackRate',
  18050. /**
  18051. * Get the value of 'disablePictureInPicture' from the video element.
  18052. *
  18053. * @method Html5#disablePictureInPicture
  18054. * @return {boolean} value
  18055. * - The value of `disablePictureInPicture` from the video element.
  18056. * - True indicates that the video can't be played in Picture-In-Picture mode
  18057. * - False indicates that the video can be played in Picture-In-Picture mode
  18058. *
  18059. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18060. */
  18061. 'disablePictureInPicture',
  18062. /**
  18063. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18064. * object representing points in the media timeline that have been played.
  18065. *
  18066. * @method Html5#played
  18067. * @return {TimeRange}
  18068. * The value of `played` from the media element. A `TimeRange` object indicating
  18069. * the ranges of time that have been played.
  18070. *
  18071. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18072. */
  18073. 'played',
  18074. /**
  18075. * Get the value of `networkState` from the media element. `networkState` indicates
  18076. * the current network state. It returns an enumeration from the following list:
  18077. * - 0: NETWORK_EMPTY
  18078. * - 1: NETWORK_IDLE
  18079. * - 2: NETWORK_LOADING
  18080. * - 3: NETWORK_NO_SOURCE
  18081. *
  18082. * @method Html5#networkState
  18083. * @return {number}
  18084. * The value of `networkState` from the media element. This will be a number
  18085. * from the list in the description.
  18086. *
  18087. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18088. */
  18089. 'networkState',
  18090. /**
  18091. * Get the value of `readyState` from the media element. `readyState` indicates
  18092. * the current state of the media element. It returns an enumeration from the
  18093. * following list:
  18094. * - 0: HAVE_NOTHING
  18095. * - 1: HAVE_METADATA
  18096. * - 2: HAVE_CURRENT_DATA
  18097. * - 3: HAVE_FUTURE_DATA
  18098. * - 4: HAVE_ENOUGH_DATA
  18099. *
  18100. * @method Html5#readyState
  18101. * @return {number}
  18102. * The value of `readyState` from the media element. This will be a number
  18103. * from the list in the description.
  18104. *
  18105. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  18106. */
  18107. 'readyState',
  18108. /**
  18109. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  18110. * the current width of the video in css pixels.
  18111. *
  18112. * @method Html5#videoWidth
  18113. * @return {number}
  18114. * The value of `videoWidth` from the video element. This will be a number
  18115. * in css pixels.
  18116. *
  18117. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18118. */
  18119. 'videoWidth',
  18120. /**
  18121. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  18122. * the current height of the video in css pixels.
  18123. *
  18124. * @method Html5#videoHeight
  18125. * @return {number}
  18126. * The value of `videoHeight` from the video element. This will be a number
  18127. * in css pixels.
  18128. *
  18129. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18130. */
  18131. 'videoHeight',
  18132. /**
  18133. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18134. * to the browser that should sent the cookies along with the requests for the
  18135. * different assets/playlists
  18136. *
  18137. * @method Html5#crossOrigin
  18138. * @return {string}
  18139. * - anonymous indicates that the media should not sent cookies.
  18140. * - use-credentials indicates that the media should sent cookies along the requests.
  18141. *
  18142. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18143. */
  18144. 'crossOrigin'].forEach(function (prop) {
  18145. Html5.prototype[prop] = function () {
  18146. return this.el_[prop];
  18147. };
  18148. });
  18149. // Wrap native properties with a setter in this format:
  18150. // set + toTitleCase(name)
  18151. // The list is as follows:
  18152. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  18153. // setDisablePictureInPicture, setCrossOrigin
  18154. [
  18155. /**
  18156. * Set the value of `volume` on the media element. `volume` indicates the current
  18157. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  18158. * so on.
  18159. *
  18160. * @method Html5#setVolume
  18161. * @param {number} percentAsDecimal
  18162. * The volume percent as a decimal. Valid range is from 0-1.
  18163. *
  18164. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18165. */
  18166. 'volume',
  18167. /**
  18168. * Set the value of `src` on the media element. `src` indicates the current
  18169. * {@link Tech~SourceObject} for the media.
  18170. *
  18171. * @method Html5#setSrc
  18172. * @param {Tech~SourceObject} src
  18173. * The source object to set as the current source.
  18174. *
  18175. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  18176. */
  18177. 'src',
  18178. /**
  18179. * Set the value of `poster` on the media element. `poster` is the url to
  18180. * an image file that can/will be shown when no media data is available.
  18181. *
  18182. * @method Html5#setPoster
  18183. * @param {string} poster
  18184. * The url to an image that should be used as the `poster` for the media
  18185. * element.
  18186. *
  18187. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  18188. */
  18189. 'poster',
  18190. /**
  18191. * Set the value of `preload` on the media element. `preload` indicates
  18192. * what should download before the media is interacted with. It can have the following
  18193. * values:
  18194. * - none: nothing should be downloaded
  18195. * - metadata: poster and the first few frames of the media may be downloaded to get
  18196. * media dimensions and other metadata
  18197. * - auto: allow the media and metadata for the media to be downloaded before
  18198. * interaction
  18199. *
  18200. * @method Html5#setPreload
  18201. * @param {string} preload
  18202. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  18203. * or 'auto'.
  18204. *
  18205. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18206. */
  18207. 'preload',
  18208. /**
  18209. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  18210. * the rate at which the media should play back. Examples:
  18211. * - if playbackRate is set to 2, media will play twice as fast.
  18212. * - if playbackRate is set to 0.5, media will play half as fast.
  18213. *
  18214. * @method Html5#setPlaybackRate
  18215. * @return {number}
  18216. * The value of `playbackRate` from the media element. A number indicating
  18217. * the current playback speed of the media, where 1 is normal speed.
  18218. *
  18219. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18220. */
  18221. 'playbackRate',
  18222. /**
  18223. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  18224. * the rate at which the media should play back upon initial startup. Changing this value
  18225. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  18226. *
  18227. * Example Values:
  18228. * - if playbackRate is set to 2, media will play twice as fast.
  18229. * - if playbackRate is set to 0.5, media will play half as fast.
  18230. *
  18231. * @method Html5.prototype.setDefaultPlaybackRate
  18232. * @return {number}
  18233. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18234. * the current playback speed of the media, where 1 is normal speed.
  18235. *
  18236. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  18237. */
  18238. 'defaultPlaybackRate',
  18239. /**
  18240. * Prevents the browser from suggesting a Picture-in-Picture context menu
  18241. * or to request Picture-in-Picture automatically in some cases.
  18242. *
  18243. * @method Html5#setDisablePictureInPicture
  18244. * @param {boolean} value
  18245. * The true value will disable Picture-in-Picture mode.
  18246. *
  18247. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18248. */
  18249. 'disablePictureInPicture',
  18250. /**
  18251. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18252. * to the browser that should sent the cookies along with the requests for the
  18253. * different assets/playlists
  18254. *
  18255. * @method Html5#setCrossOrigin
  18256. * @param {string} crossOrigin
  18257. * - anonymous indicates that the media should not sent cookies.
  18258. * - use-credentials indicates that the media should sent cookies along the requests.
  18259. *
  18260. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18261. */
  18262. 'crossOrigin'].forEach(function (prop) {
  18263. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18264. this.el_[prop] = v;
  18265. };
  18266. });
  18267. // wrap native functions with a function
  18268. // The list is as follows:
  18269. // pause, load, play
  18270. [
  18271. /**
  18272. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  18273. * media elements `pause` function.
  18274. *
  18275. * @method Html5#pause
  18276. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  18277. */
  18278. 'pause',
  18279. /**
  18280. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  18281. * media element `load` function.
  18282. *
  18283. * @method Html5#load
  18284. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  18285. */
  18286. 'load',
  18287. /**
  18288. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  18289. * media element `play` function.
  18290. *
  18291. * @method Html5#play
  18292. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  18293. */
  18294. 'play'].forEach(function (prop) {
  18295. Html5.prototype[prop] = function () {
  18296. return this.el_[prop]();
  18297. };
  18298. });
  18299. Tech.withSourceHandlers(Html5);
  18300. /**
  18301. * Native source handler for Html5, simply passes the source to the media element.
  18302. *
  18303. * @property {Tech~SourceObject} source
  18304. * The source object
  18305. *
  18306. * @property {Html5} tech
  18307. * The instance of the HTML5 tech.
  18308. */
  18309. Html5.nativeSourceHandler = {};
  18310. /**
  18311. * Check if the media element can play the given mime type.
  18312. *
  18313. * @param {string} type
  18314. * The mimetype to check
  18315. *
  18316. * @return {string}
  18317. * 'probably', 'maybe', or '' (empty string)
  18318. */
  18319. Html5.nativeSourceHandler.canPlayType = function (type) {
  18320. // IE without MediaPlayer throws an error (#519)
  18321. try {
  18322. return Html5.TEST_VID.canPlayType(type);
  18323. } catch (e) {
  18324. return '';
  18325. }
  18326. };
  18327. /**
  18328. * Check if the media element can handle a source natively.
  18329. *
  18330. * @param {Tech~SourceObject} source
  18331. * The source object
  18332. *
  18333. * @param {Object} [options]
  18334. * Options to be passed to the tech.
  18335. *
  18336. * @return {string}
  18337. * 'probably', 'maybe', or '' (empty string).
  18338. */
  18339. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  18340. // If a type was provided we should rely on that
  18341. if (source.type) {
  18342. return Html5.nativeSourceHandler.canPlayType(source.type);
  18343. // If no type, fall back to checking 'video/[EXTENSION]'
  18344. } else if (source.src) {
  18345. const ext = getFileExtension(source.src);
  18346. return Html5.nativeSourceHandler.canPlayType(`video/${ext}`);
  18347. }
  18348. return '';
  18349. };
  18350. /**
  18351. * Pass the source to the native media element.
  18352. *
  18353. * @param {Tech~SourceObject} source
  18354. * The source object
  18355. *
  18356. * @param {Html5} tech
  18357. * The instance of the Html5 tech
  18358. *
  18359. * @param {Object} [options]
  18360. * The options to pass to the source
  18361. */
  18362. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  18363. tech.setSrc(source.src);
  18364. };
  18365. /**
  18366. * A noop for the native dispose function, as cleanup is not needed.
  18367. */
  18368. Html5.nativeSourceHandler.dispose = function () {};
  18369. // Register the native source handler
  18370. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  18371. Tech.registerTech('Html5', Html5);
  18372. /**
  18373. * @file player.js
  18374. */
  18375. // The following tech events are simply re-triggered
  18376. // on the player when they happen
  18377. const TECH_EVENTS_RETRIGGER = [
  18378. /**
  18379. * Fired while the user agent is downloading media data.
  18380. *
  18381. * @event Player#progress
  18382. * @type {Event}
  18383. */
  18384. /**
  18385. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  18386. *
  18387. * @private
  18388. * @method Player#handleTechProgress_
  18389. * @fires Player#progress
  18390. * @listens Tech#progress
  18391. */
  18392. 'progress',
  18393. /**
  18394. * Fires when the loading of an audio/video is aborted.
  18395. *
  18396. * @event Player#abort
  18397. * @type {Event}
  18398. */
  18399. /**
  18400. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  18401. *
  18402. * @private
  18403. * @method Player#handleTechAbort_
  18404. * @fires Player#abort
  18405. * @listens Tech#abort
  18406. */
  18407. 'abort',
  18408. /**
  18409. * Fires when the browser is intentionally not getting media data.
  18410. *
  18411. * @event Player#suspend
  18412. * @type {Event}
  18413. */
  18414. /**
  18415. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  18416. *
  18417. * @private
  18418. * @method Player#handleTechSuspend_
  18419. * @fires Player#suspend
  18420. * @listens Tech#suspend
  18421. */
  18422. 'suspend',
  18423. /**
  18424. * Fires when the current playlist is empty.
  18425. *
  18426. * @event Player#emptied
  18427. * @type {Event}
  18428. */
  18429. /**
  18430. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  18431. *
  18432. * @private
  18433. * @method Player#handleTechEmptied_
  18434. * @fires Player#emptied
  18435. * @listens Tech#emptied
  18436. */
  18437. 'emptied',
  18438. /**
  18439. * Fires when the browser is trying to get media data, but data is not available.
  18440. *
  18441. * @event Player#stalled
  18442. * @type {Event}
  18443. */
  18444. /**
  18445. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  18446. *
  18447. * @private
  18448. * @method Player#handleTechStalled_
  18449. * @fires Player#stalled
  18450. * @listens Tech#stalled
  18451. */
  18452. 'stalled',
  18453. /**
  18454. * Fires when the browser has loaded meta data for the audio/video.
  18455. *
  18456. * @event Player#loadedmetadata
  18457. * @type {Event}
  18458. */
  18459. /**
  18460. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  18461. *
  18462. * @private
  18463. * @method Player#handleTechLoadedmetadata_
  18464. * @fires Player#loadedmetadata
  18465. * @listens Tech#loadedmetadata
  18466. */
  18467. 'loadedmetadata',
  18468. /**
  18469. * Fires when the browser has loaded the current frame of the audio/video.
  18470. *
  18471. * @event Player#loadeddata
  18472. * @type {event}
  18473. */
  18474. /**
  18475. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  18476. *
  18477. * @private
  18478. * @method Player#handleTechLoaddeddata_
  18479. * @fires Player#loadeddata
  18480. * @listens Tech#loadeddata
  18481. */
  18482. 'loadeddata',
  18483. /**
  18484. * Fires when the current playback position has changed.
  18485. *
  18486. * @event Player#timeupdate
  18487. * @type {event}
  18488. */
  18489. /**
  18490. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  18491. *
  18492. * @private
  18493. * @method Player#handleTechTimeUpdate_
  18494. * @fires Player#timeupdate
  18495. * @listens Tech#timeupdate
  18496. */
  18497. 'timeupdate',
  18498. /**
  18499. * Fires when the video's intrinsic dimensions change
  18500. *
  18501. * @event Player#resize
  18502. * @type {event}
  18503. */
  18504. /**
  18505. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  18506. *
  18507. * @private
  18508. * @method Player#handleTechResize_
  18509. * @fires Player#resize
  18510. * @listens Tech#resize
  18511. */
  18512. 'resize',
  18513. /**
  18514. * Fires when the volume has been changed
  18515. *
  18516. * @event Player#volumechange
  18517. * @type {event}
  18518. */
  18519. /**
  18520. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  18521. *
  18522. * @private
  18523. * @method Player#handleTechVolumechange_
  18524. * @fires Player#volumechange
  18525. * @listens Tech#volumechange
  18526. */
  18527. 'volumechange',
  18528. /**
  18529. * Fires when the text track has been changed
  18530. *
  18531. * @event Player#texttrackchange
  18532. * @type {event}
  18533. */
  18534. /**
  18535. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  18536. *
  18537. * @private
  18538. * @method Player#handleTechTexttrackchange_
  18539. * @fires Player#texttrackchange
  18540. * @listens Tech#texttrackchange
  18541. */
  18542. 'texttrackchange'];
  18543. // events to queue when playback rate is zero
  18544. // this is a hash for the sole purpose of mapping non-camel-cased event names
  18545. // to camel-cased function names
  18546. const TECH_EVENTS_QUEUE = {
  18547. canplay: 'CanPlay',
  18548. canplaythrough: 'CanPlayThrough',
  18549. playing: 'Playing',
  18550. seeked: 'Seeked'
  18551. };
  18552. const BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  18553. const BREAKPOINT_CLASSES = {};
  18554. // grep: vjs-layout-tiny
  18555. // grep: vjs-layout-x-small
  18556. // grep: vjs-layout-small
  18557. // grep: vjs-layout-medium
  18558. // grep: vjs-layout-large
  18559. // grep: vjs-layout-x-large
  18560. // grep: vjs-layout-huge
  18561. BREAKPOINT_ORDER.forEach(k => {
  18562. const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
  18563. BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
  18564. });
  18565. const DEFAULT_BREAKPOINTS = {
  18566. tiny: 210,
  18567. xsmall: 320,
  18568. small: 425,
  18569. medium: 768,
  18570. large: 1440,
  18571. xlarge: 2560,
  18572. huge: Infinity
  18573. };
  18574. /**
  18575. * An instance of the `Player` class is created when any of the Video.js setup methods
  18576. * are used to initialize a video.
  18577. *
  18578. * After an instance has been created it can be accessed globally in three ways:
  18579. * 1. By calling `videojs.getPlayer('example_video_1');`
  18580. * 2. By calling `videojs('example_video_1');` (not recomended)
  18581. * 2. By using it directly via `videojs.players.example_video_1;`
  18582. *
  18583. * @extends Component
  18584. * @global
  18585. */
  18586. class Player extends Component$1 {
  18587. /**
  18588. * Create an instance of this class.
  18589. *
  18590. * @param {Element} tag
  18591. * The original video DOM element used for configuring options.
  18592. *
  18593. * @param {Object} [options]
  18594. * Object of option names and values.
  18595. *
  18596. * @param {Function} [ready]
  18597. * Ready callback function.
  18598. */
  18599. constructor(tag, options, ready) {
  18600. // Make sure tag ID exists
  18601. tag.id = tag.id || options.id || `vjs_video_${newGUID()}`;
  18602. // Set Options
  18603. // The options argument overrides options set in the video tag
  18604. // which overrides globally set options.
  18605. // This latter part coincides with the load order
  18606. // (tag must exist before Player)
  18607. options = Object.assign(Player.getTagSettings(tag), options);
  18608. // Delay the initialization of children because we need to set up
  18609. // player properties first, and can't use `this` before `super()`
  18610. options.initChildren = false;
  18611. // Same with creating the element
  18612. options.createEl = false;
  18613. // don't auto mixin the evented mixin
  18614. options.evented = false;
  18615. // we don't want the player to report touch activity on itself
  18616. // see enableTouchActivity in Component
  18617. options.reportTouchActivity = false;
  18618. // If language is not set, get the closest lang attribute
  18619. if (!options.language) {
  18620. const closest = tag.closest('[lang]');
  18621. if (closest) {
  18622. options.language = closest.getAttribute('lang');
  18623. }
  18624. }
  18625. // Run base component initializing with new options
  18626. super(null, options, ready);
  18627. // Create bound methods for document listeners.
  18628. this.boundDocumentFullscreenChange_ = e => this.documentFullscreenChange_(e);
  18629. this.boundFullWindowOnEscKey_ = e => this.fullWindowOnEscKey(e);
  18630. this.boundUpdateStyleEl_ = e => this.updateStyleEl_(e);
  18631. this.boundApplyInitTime_ = e => this.applyInitTime_(e);
  18632. this.boundUpdateCurrentBreakpoint_ = e => this.updateCurrentBreakpoint_(e);
  18633. this.boundHandleTechClick_ = e => this.handleTechClick_(e);
  18634. this.boundHandleTechDoubleClick_ = e => this.handleTechDoubleClick_(e);
  18635. this.boundHandleTechTouchStart_ = e => this.handleTechTouchStart_(e);
  18636. this.boundHandleTechTouchMove_ = e => this.handleTechTouchMove_(e);
  18637. this.boundHandleTechTouchEnd_ = e => this.handleTechTouchEnd_(e);
  18638. this.boundHandleTechTap_ = e => this.handleTechTap_(e);
  18639. // default isFullscreen_ to false
  18640. this.isFullscreen_ = false;
  18641. // create logger
  18642. this.log = createLogger(this.id_);
  18643. // Hold our own reference to fullscreen api so it can be mocked in tests
  18644. this.fsApi_ = FullscreenApi;
  18645. // Tracks when a tech changes the poster
  18646. this.isPosterFromTech_ = false;
  18647. // Holds callback info that gets queued when playback rate is zero
  18648. // and a seek is happening
  18649. this.queuedCallbacks_ = [];
  18650. // Turn off API access because we're loading a new tech that might load asynchronously
  18651. this.isReady_ = false;
  18652. // Init state hasStarted_
  18653. this.hasStarted_ = false;
  18654. // Init state userActive_
  18655. this.userActive_ = false;
  18656. // Init debugEnabled_
  18657. this.debugEnabled_ = false;
  18658. // Init state audioOnlyMode_
  18659. this.audioOnlyMode_ = false;
  18660. // Init state audioPosterMode_
  18661. this.audioPosterMode_ = false;
  18662. // Init state audioOnlyCache_
  18663. this.audioOnlyCache_ = {
  18664. playerHeight: null,
  18665. hiddenChildren: []
  18666. };
  18667. // if the global option object was accidentally blown away by
  18668. // someone, bail early with an informative error
  18669. if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) {
  18670. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  18671. }
  18672. // Store the original tag used to set options
  18673. this.tag = tag;
  18674. // Store the tag attributes used to restore html5 element
  18675. this.tagAttributes = tag && getAttributes(tag);
  18676. // Update current language
  18677. this.language(this.options_.language);
  18678. // Update Supported Languages
  18679. if (options.languages) {
  18680. // Normalise player option languages to lowercase
  18681. const languagesToLower = {};
  18682. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  18683. languagesToLower[name.toLowerCase()] = options.languages[name];
  18684. });
  18685. this.languages_ = languagesToLower;
  18686. } else {
  18687. this.languages_ = Player.prototype.options_.languages;
  18688. }
  18689. this.resetCache_();
  18690. // Set poster
  18691. this.poster_ = options.poster || '';
  18692. // Set controls
  18693. this.controls_ = !!options.controls;
  18694. // Original tag settings stored in options
  18695. // now remove immediately so native controls don't flash.
  18696. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  18697. tag.controls = false;
  18698. tag.removeAttribute('controls');
  18699. this.changingSrc_ = false;
  18700. this.playCallbacks_ = [];
  18701. this.playTerminatedQueue_ = [];
  18702. // the attribute overrides the option
  18703. if (tag.hasAttribute('autoplay')) {
  18704. this.autoplay(true);
  18705. } else {
  18706. // otherwise use the setter to validate and
  18707. // set the correct value.
  18708. this.autoplay(this.options_.autoplay);
  18709. }
  18710. // check plugins
  18711. if (options.plugins) {
  18712. Object.keys(options.plugins).forEach(name => {
  18713. if (typeof this[name] !== 'function') {
  18714. throw new Error(`plugin "${name}" does not exist`);
  18715. }
  18716. });
  18717. }
  18718. /*
  18719. * Store the internal state of scrubbing
  18720. *
  18721. * @private
  18722. * @return {Boolean} True if the user is scrubbing
  18723. */
  18724. this.scrubbing_ = false;
  18725. this.el_ = this.createEl();
  18726. // Make this an evented object and use `el_` as its event bus.
  18727. evented(this, {
  18728. eventBusKey: 'el_'
  18729. });
  18730. // listen to document and player fullscreenchange handlers so we receive those events
  18731. // before a user can receive them so we can update isFullscreen appropriately.
  18732. // make sure that we listen to fullscreenchange events before everything else to make sure that
  18733. // our isFullscreen method is updated properly for internal components as well as external.
  18734. if (this.fsApi_.requestFullscreen) {
  18735. on(document__default["default"], this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18736. this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18737. }
  18738. if (this.fluid_) {
  18739. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  18740. }
  18741. // We also want to pass the original player options to each component and plugin
  18742. // as well so they don't need to reach back into the player for options later.
  18743. // We also need to do another copy of this.options_ so we don't end up with
  18744. // an infinite loop.
  18745. const playerOptionsCopy = merge$1(this.options_);
  18746. // Load plugins
  18747. if (options.plugins) {
  18748. Object.keys(options.plugins).forEach(name => {
  18749. this[name](options.plugins[name]);
  18750. });
  18751. }
  18752. // Enable debug mode to fire debugon event for all plugins.
  18753. if (options.debug) {
  18754. this.debug(true);
  18755. }
  18756. this.options_.playerOptions = playerOptionsCopy;
  18757. this.middleware_ = [];
  18758. this.playbackRates(options.playbackRates);
  18759. this.initChildren();
  18760. // Set isAudio based on whether or not an audio tag was used
  18761. this.isAudio(tag.nodeName.toLowerCase() === 'audio');
  18762. // Update controls className. Can't do this when the controls are initially
  18763. // set because the element doesn't exist yet.
  18764. if (this.controls()) {
  18765. this.addClass('vjs-controls-enabled');
  18766. } else {
  18767. this.addClass('vjs-controls-disabled');
  18768. }
  18769. // Set ARIA label and region role depending on player type
  18770. this.el_.setAttribute('role', 'region');
  18771. if (this.isAudio()) {
  18772. this.el_.setAttribute('aria-label', this.localize('Audio Player'));
  18773. } else {
  18774. this.el_.setAttribute('aria-label', this.localize('Video Player'));
  18775. }
  18776. if (this.isAudio()) {
  18777. this.addClass('vjs-audio');
  18778. }
  18779. // TODO: Make this smarter. Toggle user state between touching/mousing
  18780. // using events, since devices can have both touch and mouse events.
  18781. // TODO: Make this check be performed again when the window switches between monitors
  18782. // (See https://github.com/videojs/video.js/issues/5683)
  18783. if (TOUCH_ENABLED) {
  18784. this.addClass('vjs-touch-enabled');
  18785. }
  18786. // iOS Safari has broken hover handling
  18787. if (!IS_IOS) {
  18788. this.addClass('vjs-workinghover');
  18789. }
  18790. // Make player easily findable by ID
  18791. Player.players[this.id_] = this;
  18792. // Add a major version class to aid css in plugins
  18793. const majorVersion = version$6.split('.')[0];
  18794. this.addClass(`vjs-v${majorVersion}`);
  18795. // When the player is first initialized, trigger activity so components
  18796. // like the control bar show themselves if needed
  18797. this.userActive(true);
  18798. this.reportUserActivity();
  18799. this.one('play', e => this.listenForUserActivity_(e));
  18800. this.on('keydown', e => this.handleKeyDown(e));
  18801. this.on('languagechange', e => this.handleLanguagechange(e));
  18802. this.breakpoints(this.options_.breakpoints);
  18803. this.responsive(this.options_.responsive);
  18804. // Calling both the audio mode methods after the player is fully
  18805. // setup to be able to listen to the events triggered by them
  18806. this.on('ready', () => {
  18807. // Calling the audioPosterMode method first so that
  18808. // the audioOnlyMode can take precedence when both options are set to true
  18809. this.audioPosterMode(this.options_.audioPosterMode);
  18810. this.audioOnlyMode(this.options_.audioOnlyMode);
  18811. });
  18812. }
  18813. /**
  18814. * Destroys the video player and does any necessary cleanup.
  18815. *
  18816. * This is especially helpful if you are dynamically adding and removing videos
  18817. * to/from the DOM.
  18818. *
  18819. * @fires Player#dispose
  18820. */
  18821. dispose() {
  18822. /**
  18823. * Called when the player is being disposed of.
  18824. *
  18825. * @event Player#dispose
  18826. * @type {Event}
  18827. */
  18828. this.trigger('dispose');
  18829. // prevent dispose from being called twice
  18830. this.off('dispose');
  18831. // Make sure all player-specific document listeners are unbound. This is
  18832. off(document__default["default"], this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  18833. off(document__default["default"], 'keydown', this.boundFullWindowOnEscKey_);
  18834. if (this.styleEl_ && this.styleEl_.parentNode) {
  18835. this.styleEl_.parentNode.removeChild(this.styleEl_);
  18836. this.styleEl_ = null;
  18837. }
  18838. // Kill reference to this player
  18839. Player.players[this.id_] = null;
  18840. if (this.tag && this.tag.player) {
  18841. this.tag.player = null;
  18842. }
  18843. if (this.el_ && this.el_.player) {
  18844. this.el_.player = null;
  18845. }
  18846. if (this.tech_) {
  18847. this.tech_.dispose();
  18848. this.isPosterFromTech_ = false;
  18849. this.poster_ = '';
  18850. }
  18851. if (this.playerElIngest_) {
  18852. this.playerElIngest_ = null;
  18853. }
  18854. if (this.tag) {
  18855. this.tag = null;
  18856. }
  18857. clearCacheForPlayer(this);
  18858. // remove all event handlers for track lists
  18859. // all tracks and track listeners are removed on
  18860. // tech dispose
  18861. ALL.names.forEach(name => {
  18862. const props = ALL[name];
  18863. const list = this[props.getterName]();
  18864. // if it is not a native list
  18865. // we have to manually remove event listeners
  18866. if (list && list.off) {
  18867. list.off();
  18868. }
  18869. });
  18870. // the actual .el_ is removed here, or replaced if
  18871. super.dispose({
  18872. restoreEl: this.options_.restoreEl
  18873. });
  18874. }
  18875. /**
  18876. * Create the `Player`'s DOM element.
  18877. *
  18878. * @return {Element}
  18879. * The DOM element that gets created.
  18880. */
  18881. createEl() {
  18882. let tag = this.tag;
  18883. let el;
  18884. let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  18885. const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  18886. if (playerElIngest) {
  18887. el = this.el_ = tag.parentNode;
  18888. } else if (!divEmbed) {
  18889. el = this.el_ = super.createEl('div');
  18890. }
  18891. // Copy over all the attributes from the tag, including ID and class
  18892. // ID will now reference player box, not the video tag
  18893. const attrs = getAttributes(tag);
  18894. if (divEmbed) {
  18895. el = this.el_ = tag;
  18896. tag = this.tag = document__default["default"].createElement('video');
  18897. while (el.children.length) {
  18898. tag.appendChild(el.firstChild);
  18899. }
  18900. if (!hasClass(el, 'video-js')) {
  18901. addClass(el, 'video-js');
  18902. }
  18903. el.appendChild(tag);
  18904. playerElIngest = this.playerElIngest_ = el;
  18905. // move properties over from our custom `video-js` element
  18906. // to our new `video` element. This will move things like
  18907. // `src` or `controls` that were set via js before the player
  18908. // was initialized.
  18909. Object.keys(el).forEach(k => {
  18910. try {
  18911. tag[k] = el[k];
  18912. } catch (e) {
  18913. // we got a a property like outerHTML which we can't actually copy, ignore it
  18914. }
  18915. });
  18916. }
  18917. // set tabindex to -1 to remove the video element from the focus order
  18918. tag.setAttribute('tabindex', '-1');
  18919. attrs.tabindex = '-1';
  18920. // Workaround for #4583 on Chrome (on Windows) with JAWS.
  18921. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  18922. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  18923. // doesn't change behavior of Chrome if JAWS is not being used
  18924. if (IS_CHROME && IS_WINDOWS) {
  18925. tag.setAttribute('role', 'application');
  18926. attrs.role = 'application';
  18927. }
  18928. // Remove width/height attrs from tag so CSS can make it 100% width/height
  18929. tag.removeAttribute('width');
  18930. tag.removeAttribute('height');
  18931. if ('width' in attrs) {
  18932. delete attrs.width;
  18933. }
  18934. if ('height' in attrs) {
  18935. delete attrs.height;
  18936. }
  18937. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  18938. // don't copy over the class attribute to the player element when we're in a div embed
  18939. // the class is already set up properly in the divEmbed case
  18940. // and we want to make sure that the `video-js` class doesn't get lost
  18941. if (!(divEmbed && attr === 'class')) {
  18942. el.setAttribute(attr, attrs[attr]);
  18943. }
  18944. if (divEmbed) {
  18945. tag.setAttribute(attr, attrs[attr]);
  18946. }
  18947. });
  18948. // Update tag id/class for use as HTML5 playback tech
  18949. // Might think we should do this after embedding in container so .vjs-tech class
  18950. // doesn't flash 100% width/height, but class only applies with .video-js parent
  18951. tag.playerId = tag.id;
  18952. tag.id += '_html5_api';
  18953. tag.className = 'vjs-tech';
  18954. // Make player findable on elements
  18955. tag.player = el.player = this;
  18956. // Default state of video is paused
  18957. this.addClass('vjs-paused');
  18958. // Add a style element in the player that we'll use to set the width/height
  18959. // of the player in a way that's still overridable by CSS, just like the
  18960. // video element
  18961. if (window__default["default"].VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  18962. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  18963. const defaultsStyleEl = $('.vjs-styles-defaults');
  18964. const head = $('head');
  18965. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  18966. }
  18967. this.fill_ = false;
  18968. this.fluid_ = false;
  18969. // Pass in the width/height/aspectRatio options which will update the style el
  18970. this.width(this.options_.width);
  18971. this.height(this.options_.height);
  18972. this.fill(this.options_.fill);
  18973. this.fluid(this.options_.fluid);
  18974. this.aspectRatio(this.options_.aspectRatio);
  18975. // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  18976. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
  18977. // Hide any links within the video/audio tag,
  18978. // because IE doesn't hide them completely from screen readers.
  18979. const links = tag.getElementsByTagName('a');
  18980. for (let i = 0; i < links.length; i++) {
  18981. const linkEl = links.item(i);
  18982. addClass(linkEl, 'vjs-hidden');
  18983. linkEl.setAttribute('hidden', 'hidden');
  18984. }
  18985. // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  18986. // keep track of the original for later so we can know if the source originally failed
  18987. tag.initNetworkState_ = tag.networkState;
  18988. // Wrap video tag in div (el/box) container
  18989. if (tag.parentNode && !playerElIngest) {
  18990. tag.parentNode.insertBefore(el, tag);
  18991. }
  18992. // insert the tag as the first child of the player element
  18993. // then manually add it to the children array so that this.addChild
  18994. // will work properly for other components
  18995. //
  18996. // Breaks iPhone, fixed in HTML5 setup.
  18997. prependTo(tag, el);
  18998. this.children_.unshift(tag);
  18999. // Set lang attr on player to ensure CSS :lang() in consistent with player
  19000. // if it's been set to something different to the doc
  19001. this.el_.setAttribute('lang', this.language_);
  19002. this.el_.setAttribute('translate', 'no');
  19003. this.el_ = el;
  19004. return el;
  19005. }
  19006. /**
  19007. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  19008. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  19009. * behavior.
  19010. *
  19011. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  19012. *
  19013. * @param {string|null} [value]
  19014. * The value to set the `Player`'s crossOrigin to. If an argument is
  19015. * given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
  19016. *
  19017. * @return {string|null|undefined}
  19018. * - The current crossOrigin value of the `Player` when getting.
  19019. * - undefined when setting
  19020. */
  19021. crossOrigin(value) {
  19022. // `null` can be set to unset a value
  19023. if (typeof value === 'undefined') {
  19024. return this.techGet_('crossOrigin');
  19025. }
  19026. if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
  19027. log$1.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
  19028. return;
  19029. }
  19030. this.techCall_('setCrossOrigin', value);
  19031. if (this.posterImage) {
  19032. this.posterImage.crossOrigin(value);
  19033. }
  19034. return;
  19035. }
  19036. /**
  19037. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19038. * To get the current width use `currentWidth()`.
  19039. *
  19040. * @param {number} [value]
  19041. * The value to set the `Player`'s width to.
  19042. *
  19043. * @return {number}
  19044. * The current width of the `Player` when getting.
  19045. */
  19046. width(value) {
  19047. return this.dimension('width', value);
  19048. }
  19049. /**
  19050. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19051. * To get the current height use `currentheight()`.
  19052. *
  19053. * @param {number} [value]
  19054. * The value to set the `Player`'s height to.
  19055. *
  19056. * @return {number}
  19057. * The current height of the `Player` when getting.
  19058. */
  19059. height(value) {
  19060. return this.dimension('height', value);
  19061. }
  19062. /**
  19063. * A getter/setter for the `Player`'s width & height.
  19064. *
  19065. * @param {string} dimension
  19066. * This string can be:
  19067. * - 'width'
  19068. * - 'height'
  19069. *
  19070. * @param {number} [value]
  19071. * Value for dimension specified in the first argument.
  19072. *
  19073. * @return {number}
  19074. * The dimension arguments value when getting (width/height).
  19075. */
  19076. dimension(dimension, value) {
  19077. const privDimension = dimension + '_';
  19078. if (value === undefined) {
  19079. return this[privDimension] || 0;
  19080. }
  19081. if (value === '' || value === 'auto') {
  19082. // If an empty string is given, reset the dimension to be automatic
  19083. this[privDimension] = undefined;
  19084. this.updateStyleEl_();
  19085. return;
  19086. }
  19087. const parsedVal = parseFloat(value);
  19088. if (isNaN(parsedVal)) {
  19089. log$1.error(`Improper value "${value}" supplied for for ${dimension}`);
  19090. return;
  19091. }
  19092. this[privDimension] = parsedVal;
  19093. this.updateStyleEl_();
  19094. }
  19095. /**
  19096. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19097. *
  19098. * Turning this on will turn off fill mode.
  19099. *
  19100. * @param {boolean} [bool]
  19101. * - A value of true adds the class.
  19102. * - A value of false removes the class.
  19103. * - No value will be a getter.
  19104. *
  19105. * @return {boolean|undefined}
  19106. * - The value of fluid when getting.
  19107. * - `undefined` when setting.
  19108. */
  19109. fluid(bool) {
  19110. if (bool === undefined) {
  19111. return !!this.fluid_;
  19112. }
  19113. this.fluid_ = !!bool;
  19114. if (isEvented(this)) {
  19115. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19116. }
  19117. if (bool) {
  19118. this.addClass('vjs-fluid');
  19119. this.fill(false);
  19120. addEventedCallback(this, () => {
  19121. this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19122. });
  19123. } else {
  19124. this.removeClass('vjs-fluid');
  19125. }
  19126. this.updateStyleEl_();
  19127. }
  19128. /**
  19129. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  19130. *
  19131. * Turning this on will turn off fluid mode.
  19132. *
  19133. * @param {boolean} [bool]
  19134. * - A value of true adds the class.
  19135. * - A value of false removes the class.
  19136. * - No value will be a getter.
  19137. *
  19138. * @return {boolean|undefined}
  19139. * - The value of fluid when getting.
  19140. * - `undefined` when setting.
  19141. */
  19142. fill(bool) {
  19143. if (bool === undefined) {
  19144. return !!this.fill_;
  19145. }
  19146. this.fill_ = !!bool;
  19147. if (bool) {
  19148. this.addClass('vjs-fill');
  19149. this.fluid(false);
  19150. } else {
  19151. this.removeClass('vjs-fill');
  19152. }
  19153. }
  19154. /**
  19155. * Get/Set the aspect ratio
  19156. *
  19157. * @param {string} [ratio]
  19158. * Aspect ratio for player
  19159. *
  19160. * @return {string|undefined}
  19161. * returns the current aspect ratio when getting
  19162. */
  19163. /**
  19164. * A getter/setter for the `Player`'s aspect ratio.
  19165. *
  19166. * @param {string} [ratio]
  19167. * The value to set the `Player`'s aspect ratio to.
  19168. *
  19169. * @return {string|undefined}
  19170. * - The current aspect ratio of the `Player` when getting.
  19171. * - undefined when setting
  19172. */
  19173. aspectRatio(ratio) {
  19174. if (ratio === undefined) {
  19175. return this.aspectRatio_;
  19176. }
  19177. // Check for width:height format
  19178. if (!/^\d+\:\d+$/.test(ratio)) {
  19179. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  19180. }
  19181. this.aspectRatio_ = ratio;
  19182. // We're assuming if you set an aspect ratio you want fluid mode,
  19183. // because in fixed mode you could calculate width and height yourself.
  19184. this.fluid(true);
  19185. this.updateStyleEl_();
  19186. }
  19187. /**
  19188. * Update styles of the `Player` element (height, width and aspect ratio).
  19189. *
  19190. * @private
  19191. * @listens Tech#loadedmetadata
  19192. */
  19193. updateStyleEl_() {
  19194. if (window__default["default"].VIDEOJS_NO_DYNAMIC_STYLE === true) {
  19195. const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  19196. const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  19197. const techEl = this.tech_ && this.tech_.el();
  19198. if (techEl) {
  19199. if (width >= 0) {
  19200. techEl.width = width;
  19201. }
  19202. if (height >= 0) {
  19203. techEl.height = height;
  19204. }
  19205. }
  19206. return;
  19207. }
  19208. let width;
  19209. let height;
  19210. let aspectRatio;
  19211. let idClass;
  19212. // The aspect ratio is either used directly or to calculate width and height.
  19213. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  19214. // Use any aspectRatio that's been specifically set
  19215. aspectRatio = this.aspectRatio_;
  19216. } else if (this.videoWidth() > 0) {
  19217. // Otherwise try to get the aspect ratio from the video metadata
  19218. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  19219. } else {
  19220. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  19221. aspectRatio = '16:9';
  19222. }
  19223. // Get the ratio as a decimal we can use to calculate dimensions
  19224. const ratioParts = aspectRatio.split(':');
  19225. const ratioMultiplier = ratioParts[1] / ratioParts[0];
  19226. if (this.width_ !== undefined) {
  19227. // Use any width that's been specifically set
  19228. width = this.width_;
  19229. } else if (this.height_ !== undefined) {
  19230. // Or calculate the width from the aspect ratio if a height has been set
  19231. width = this.height_ / ratioMultiplier;
  19232. } else {
  19233. // Or use the video's metadata, or use the video el's default of 300
  19234. width = this.videoWidth() || 300;
  19235. }
  19236. if (this.height_ !== undefined) {
  19237. // Use any height that's been specifically set
  19238. height = this.height_;
  19239. } else {
  19240. // Otherwise calculate the height from the ratio and the width
  19241. height = width * ratioMultiplier;
  19242. }
  19243. // Ensure the CSS class is valid by starting with an alpha character
  19244. if (/^[^a-zA-Z]/.test(this.id())) {
  19245. idClass = 'dimensions-' + this.id();
  19246. } else {
  19247. idClass = this.id() + '-dimensions';
  19248. }
  19249. // Ensure the right class is still on the player for the style element
  19250. this.addClass(idClass);
  19251. setTextContent(this.styleEl_, `
  19252. .${idClass} {
  19253. width: ${width}px;
  19254. height: ${height}px;
  19255. }
  19256. .${idClass}.vjs-fluid:not(.vjs-audio-only-mode) {
  19257. padding-top: ${ratioMultiplier * 100}%;
  19258. }
  19259. `);
  19260. }
  19261. /**
  19262. * Load/Create an instance of playback {@link Tech} including element
  19263. * and API methods. Then append the `Tech` element in `Player` as a child.
  19264. *
  19265. * @param {string} techName
  19266. * name of the playback technology
  19267. *
  19268. * @param {string} source
  19269. * video source
  19270. *
  19271. * @private
  19272. */
  19273. loadTech_(techName, source) {
  19274. // Pause and remove current playback technology
  19275. if (this.tech_) {
  19276. this.unloadTech_();
  19277. }
  19278. const titleTechName = toTitleCase$1(techName);
  19279. const camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1);
  19280. // get rid of the HTML5 video tag as soon as we are using another tech
  19281. if (titleTechName !== 'Html5' && this.tag) {
  19282. Tech.getTech('Html5').disposeMediaElement(this.tag);
  19283. this.tag.player = null;
  19284. this.tag = null;
  19285. }
  19286. this.techName_ = titleTechName;
  19287. // Turn off API access because we're loading a new tech that might load asynchronously
  19288. this.isReady_ = false;
  19289. let autoplay = this.autoplay();
  19290. // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  19291. // because the player is going to handle autoplay on `loadstart`
  19292. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  19293. autoplay = false;
  19294. }
  19295. // Grab tech-specific options from player options and add source and parent element to use.
  19296. const techOptions = {
  19297. source,
  19298. autoplay,
  19299. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  19300. 'playerId': this.id(),
  19301. 'techId': `${this.id()}_${camelTechName}_api`,
  19302. 'playsinline': this.options_.playsinline,
  19303. 'preload': this.options_.preload,
  19304. 'loop': this.options_.loop,
  19305. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  19306. 'muted': this.options_.muted,
  19307. 'poster': this.poster(),
  19308. 'language': this.language(),
  19309. 'playerElIngest': this.playerElIngest_ || false,
  19310. 'vtt.js': this.options_['vtt.js'],
  19311. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  19312. 'enableSourceset': this.options_.enableSourceset
  19313. };
  19314. ALL.names.forEach(name => {
  19315. const props = ALL[name];
  19316. techOptions[props.getterName] = this[props.privateName];
  19317. });
  19318. Object.assign(techOptions, this.options_[titleTechName]);
  19319. Object.assign(techOptions, this.options_[camelTechName]);
  19320. Object.assign(techOptions, this.options_[techName.toLowerCase()]);
  19321. if (this.tag) {
  19322. techOptions.tag = this.tag;
  19323. }
  19324. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  19325. techOptions.startTime = this.cache_.currentTime;
  19326. }
  19327. // Initialize tech instance
  19328. const TechClass = Tech.getTech(techName);
  19329. if (!TechClass) {
  19330. throw new Error(`No Tech named '${titleTechName}' exists! '${titleTechName}' should be registered using videojs.registerTech()'`);
  19331. }
  19332. this.tech_ = new TechClass(techOptions);
  19333. // player.triggerReady is always async, so don't need this to be async
  19334. this.tech_.ready(bind_(this, this.handleTechReady_), true);
  19335. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
  19336. // Listen to all HTML5-defined events and trigger them on the player
  19337. TECH_EVENTS_RETRIGGER.forEach(event => {
  19338. this.on(this.tech_, event, e => this[`handleTech${toTitleCase$1(event)}_`](e));
  19339. });
  19340. Object.keys(TECH_EVENTS_QUEUE).forEach(event => {
  19341. this.on(this.tech_, event, eventObj => {
  19342. if (this.tech_.playbackRate() === 0 && this.tech_.seeking()) {
  19343. this.queuedCallbacks_.push({
  19344. callback: this[`handleTech${TECH_EVENTS_QUEUE[event]}_`].bind(this),
  19345. event: eventObj
  19346. });
  19347. return;
  19348. }
  19349. this[`handleTech${TECH_EVENTS_QUEUE[event]}_`](eventObj);
  19350. });
  19351. });
  19352. this.on(this.tech_, 'loadstart', e => this.handleTechLoadStart_(e));
  19353. this.on(this.tech_, 'sourceset', e => this.handleTechSourceset_(e));
  19354. this.on(this.tech_, 'waiting', e => this.handleTechWaiting_(e));
  19355. this.on(this.tech_, 'ended', e => this.handleTechEnded_(e));
  19356. this.on(this.tech_, 'seeking', e => this.handleTechSeeking_(e));
  19357. this.on(this.tech_, 'play', e => this.handleTechPlay_(e));
  19358. this.on(this.tech_, 'pause', e => this.handleTechPause_(e));
  19359. this.on(this.tech_, 'durationchange', e => this.handleTechDurationChange_(e));
  19360. this.on(this.tech_, 'fullscreenchange', (e, data) => this.handleTechFullscreenChange_(e, data));
  19361. this.on(this.tech_, 'fullscreenerror', (e, err) => this.handleTechFullscreenError_(e, err));
  19362. this.on(this.tech_, 'enterpictureinpicture', e => this.handleTechEnterPictureInPicture_(e));
  19363. this.on(this.tech_, 'leavepictureinpicture', e => this.handleTechLeavePictureInPicture_(e));
  19364. this.on(this.tech_, 'error', e => this.handleTechError_(e));
  19365. this.on(this.tech_, 'posterchange', e => this.handleTechPosterChange_(e));
  19366. this.on(this.tech_, 'textdata', e => this.handleTechTextData_(e));
  19367. this.on(this.tech_, 'ratechange', e => this.handleTechRateChange_(e));
  19368. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  19369. this.usingNativeControls(this.techGet_('controls'));
  19370. if (this.controls() && !this.usingNativeControls()) {
  19371. this.addTechControlsListeners_();
  19372. }
  19373. // Add the tech element in the DOM if it was not already there
  19374. // Make sure to not insert the original video element if using Html5
  19375. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  19376. prependTo(this.tech_.el(), this.el());
  19377. }
  19378. // Get rid of the original video tag reference after the first tech is loaded
  19379. if (this.tag) {
  19380. this.tag.player = null;
  19381. this.tag = null;
  19382. }
  19383. }
  19384. /**
  19385. * Unload and dispose of the current playback {@link Tech}.
  19386. *
  19387. * @private
  19388. */
  19389. unloadTech_() {
  19390. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  19391. ALL.names.forEach(name => {
  19392. const props = ALL[name];
  19393. this[props.privateName] = this[props.getterName]();
  19394. });
  19395. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  19396. this.isReady_ = false;
  19397. this.tech_.dispose();
  19398. this.tech_ = false;
  19399. if (this.isPosterFromTech_) {
  19400. this.poster_ = '';
  19401. this.trigger('posterchange');
  19402. }
  19403. this.isPosterFromTech_ = false;
  19404. }
  19405. /**
  19406. * Return a reference to the current {@link Tech}.
  19407. * It will print a warning by default about the danger of using the tech directly
  19408. * but any argument that is passed in will silence the warning.
  19409. *
  19410. * @param {*} [safety]
  19411. * Anything passed in to silence the warning
  19412. *
  19413. * @return {Tech}
  19414. * The Tech
  19415. */
  19416. tech(safety) {
  19417. if (safety === undefined) {
  19418. log$1.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\n');
  19419. }
  19420. return this.tech_;
  19421. }
  19422. /**
  19423. * Set up click and touch listeners for the playback element
  19424. *
  19425. * - On desktops: a click on the video itself will toggle playback
  19426. * - On mobile devices: a click on the video toggles controls
  19427. * which is done by toggling the user state between active and
  19428. * inactive
  19429. * - A tap can signal that a user has become active or has become inactive
  19430. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  19431. * quick tap should hide them again (signaling the user is in an inactive
  19432. * viewing state)
  19433. * - In addition to this, we still want the user to be considered inactive after
  19434. * a few seconds of inactivity.
  19435. *
  19436. * > Note: the only part of iOS interaction we can't mimic with this setup
  19437. * is a touch and hold on the video element counting as activity in order to
  19438. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  19439. * on any controls will still keep the user active
  19440. *
  19441. * @private
  19442. */
  19443. addTechControlsListeners_() {
  19444. // Make sure to remove all the previous listeners in case we are called multiple times.
  19445. this.removeTechControlsListeners_();
  19446. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  19447. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19448. // If the controls were hidden we don't want that to change without a tap event
  19449. // so we'll check if the controls were already showing before reporting user
  19450. // activity
  19451. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19452. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19453. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19454. // The tap listener needs to come after the touchend listener because the tap
  19455. // listener cancels out any reportedUserActivity when setting userActive(false)
  19456. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  19457. }
  19458. /**
  19459. * Remove the listeners used for click and tap controls. This is needed for
  19460. * toggling to controls disabled, where a tap/touch should do nothing.
  19461. *
  19462. * @private
  19463. */
  19464. removeTechControlsListeners_() {
  19465. // We don't want to just use `this.off()` because there might be other needed
  19466. // listeners added by techs that extend this.
  19467. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  19468. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19469. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19470. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19471. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  19472. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19473. }
  19474. /**
  19475. * Player waits for the tech to be ready
  19476. *
  19477. * @private
  19478. */
  19479. handleTechReady_() {
  19480. this.triggerReady();
  19481. // Keep the same volume as before
  19482. if (this.cache_.volume) {
  19483. this.techCall_('setVolume', this.cache_.volume);
  19484. }
  19485. // Look if the tech found a higher resolution poster while loading
  19486. this.handleTechPosterChange_();
  19487. // Update the duration if available
  19488. this.handleTechDurationChange_();
  19489. }
  19490. /**
  19491. * Retrigger the `loadstart` event that was triggered by the {@link Tech}.
  19492. *
  19493. * @fires Player#loadstart
  19494. * @listens Tech#loadstart
  19495. * @private
  19496. */
  19497. handleTechLoadStart_() {
  19498. // TODO: Update to use `emptied` event instead. See #1277.
  19499. this.removeClass('vjs-ended', 'vjs-seeking');
  19500. // reset the error state
  19501. this.error(null);
  19502. // Update the duration
  19503. this.handleTechDurationChange_();
  19504. if (!this.paused()) {
  19505. /**
  19506. * Fired when the user agent begins looking for media data
  19507. *
  19508. * @event Player#loadstart
  19509. * @type {Event}
  19510. */
  19511. this.trigger('loadstart');
  19512. } else {
  19513. // reset the hasStarted state
  19514. this.hasStarted(false);
  19515. this.trigger('loadstart');
  19516. }
  19517. // autoplay happens after loadstart for the browser,
  19518. // so we mimic that behavior
  19519. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  19520. }
  19521. /**
  19522. * Handle autoplay string values, rather than the typical boolean
  19523. * values that should be handled by the tech. Note that this is not
  19524. * part of any specification. Valid values and what they do can be
  19525. * found on the autoplay getter at Player#autoplay()
  19526. */
  19527. manualAutoplay_(type) {
  19528. if (!this.tech_ || typeof type !== 'string') {
  19529. return;
  19530. }
  19531. // Save original muted() value, set muted to true, and attempt to play().
  19532. // On promise rejection, restore muted from saved value
  19533. const resolveMuted = () => {
  19534. const previouslyMuted = this.muted();
  19535. this.muted(true);
  19536. const restoreMuted = () => {
  19537. this.muted(previouslyMuted);
  19538. };
  19539. // restore muted on play terminatation
  19540. this.playTerminatedQueue_.push(restoreMuted);
  19541. const mutedPromise = this.play();
  19542. if (!isPromise(mutedPromise)) {
  19543. return;
  19544. }
  19545. return mutedPromise.catch(err => {
  19546. restoreMuted();
  19547. throw new Error(`Rejection at manualAutoplay. Restoring muted value. ${err ? err : ''}`);
  19548. });
  19549. };
  19550. let promise;
  19551. // if muted defaults to true
  19552. // the only thing we can do is call play
  19553. if (type === 'any' && !this.muted()) {
  19554. promise = this.play();
  19555. if (isPromise(promise)) {
  19556. promise = promise.catch(resolveMuted);
  19557. }
  19558. } else if (type === 'muted' && !this.muted()) {
  19559. promise = resolveMuted();
  19560. } else {
  19561. promise = this.play();
  19562. }
  19563. if (!isPromise(promise)) {
  19564. return;
  19565. }
  19566. return promise.then(() => {
  19567. this.trigger({
  19568. type: 'autoplay-success',
  19569. autoplay: type
  19570. });
  19571. }).catch(() => {
  19572. this.trigger({
  19573. type: 'autoplay-failure',
  19574. autoplay: type
  19575. });
  19576. });
  19577. }
  19578. /**
  19579. * Update the internal source caches so that we return the correct source from
  19580. * `src()`, `currentSource()`, and `currentSources()`.
  19581. *
  19582. * > Note: `currentSources` will not be updated if the source that is passed in exists
  19583. * in the current `currentSources` cache.
  19584. *
  19585. *
  19586. * @param {Tech~SourceObject} srcObj
  19587. * A string or object source to update our caches to.
  19588. */
  19589. updateSourceCaches_(srcObj = '') {
  19590. let src = srcObj;
  19591. let type = '';
  19592. if (typeof src !== 'string') {
  19593. src = srcObj.src;
  19594. type = srcObj.type;
  19595. }
  19596. // make sure all the caches are set to default values
  19597. // to prevent null checking
  19598. this.cache_.source = this.cache_.source || {};
  19599. this.cache_.sources = this.cache_.sources || [];
  19600. // try to get the type of the src that was passed in
  19601. if (src && !type) {
  19602. type = findMimetype(this, src);
  19603. }
  19604. // update `currentSource` cache always
  19605. this.cache_.source = merge$1({}, srcObj, {
  19606. src,
  19607. type
  19608. });
  19609. const matchingSources = this.cache_.sources.filter(s => s.src && s.src === src);
  19610. const sourceElSources = [];
  19611. const sourceEls = this.$$('source');
  19612. const matchingSourceEls = [];
  19613. for (let i = 0; i < sourceEls.length; i++) {
  19614. const sourceObj = getAttributes(sourceEls[i]);
  19615. sourceElSources.push(sourceObj);
  19616. if (sourceObj.src && sourceObj.src === src) {
  19617. matchingSourceEls.push(sourceObj.src);
  19618. }
  19619. }
  19620. // if we have matching source els but not matching sources
  19621. // the current source cache is not up to date
  19622. if (matchingSourceEls.length && !matchingSources.length) {
  19623. this.cache_.sources = sourceElSources;
  19624. // if we don't have matching source or source els set the
  19625. // sources cache to the `currentSource` cache
  19626. } else if (!matchingSources.length) {
  19627. this.cache_.sources = [this.cache_.source];
  19628. }
  19629. // update the tech `src` cache
  19630. this.cache_.src = src;
  19631. }
  19632. /**
  19633. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  19634. * causing the media element to reload.
  19635. *
  19636. * It will fire for the initial source and each subsequent source.
  19637. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  19638. *
  19639. * The event object for this event contains a `src` property that will contain the source
  19640. * that was available when the event was triggered. This is generally only necessary if Video.js
  19641. * is switching techs while the source was being changed.
  19642. *
  19643. * It is also fired when `load` is called on the player (or media element)
  19644. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  19645. * says that the resource selection algorithm needs to be aborted and restarted.
  19646. * In this case, it is very likely that the `src` property will be set to the
  19647. * empty string `""` to indicate we do not know what the source will be but
  19648. * that it is changing.
  19649. *
  19650. * *This event is currently still experimental and may change in minor releases.*
  19651. * __To use this, pass `enableSourceset` option to the player.__
  19652. *
  19653. * @event Player#sourceset
  19654. * @type {Event}
  19655. * @prop {string} src
  19656. * The source url available when the `sourceset` was triggered.
  19657. * It will be an empty string if we cannot know what the source is
  19658. * but know that the source will change.
  19659. */
  19660. /**
  19661. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  19662. *
  19663. * @fires Player#sourceset
  19664. * @listens Tech#sourceset
  19665. * @private
  19666. */
  19667. handleTechSourceset_(event) {
  19668. // only update the source cache when the source
  19669. // was not updated using the player api
  19670. if (!this.changingSrc_) {
  19671. let updateSourceCaches = src => this.updateSourceCaches_(src);
  19672. const playerSrc = this.currentSource().src;
  19673. const eventSrc = event.src;
  19674. // if we have a playerSrc that is not a blob, and a tech src that is a blob
  19675. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  19676. // if both the tech source and the player source were updated we assume
  19677. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  19678. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  19679. updateSourceCaches = () => {};
  19680. }
  19681. }
  19682. // update the source to the initial source right away
  19683. // in some cases this will be empty string
  19684. updateSourceCaches(eventSrc);
  19685. // if the `sourceset` `src` was an empty string
  19686. // wait for a `loadstart` to update the cache to `currentSrc`.
  19687. // If a sourceset happens before a `loadstart`, we reset the state
  19688. if (!event.src) {
  19689. this.tech_.any(['sourceset', 'loadstart'], e => {
  19690. // if a sourceset happens before a `loadstart` there
  19691. // is nothing to do as this `handleTechSourceset_`
  19692. // will be called again and this will be handled there.
  19693. if (e.type === 'sourceset') {
  19694. return;
  19695. }
  19696. const techSrc = this.techGet('currentSrc');
  19697. this.lastSource_.tech = techSrc;
  19698. this.updateSourceCaches_(techSrc);
  19699. });
  19700. }
  19701. }
  19702. this.lastSource_ = {
  19703. player: this.currentSource().src,
  19704. tech: event.src
  19705. };
  19706. this.trigger({
  19707. src: event.src,
  19708. type: 'sourceset'
  19709. });
  19710. }
  19711. /**
  19712. * Add/remove the vjs-has-started class
  19713. *
  19714. *
  19715. * @param {boolean} request
  19716. * - true: adds the class
  19717. * - false: remove the class
  19718. *
  19719. * @return {boolean}
  19720. * the boolean value of hasStarted_
  19721. */
  19722. hasStarted(request) {
  19723. if (request === undefined) {
  19724. // act as getter, if we have no request to change
  19725. return this.hasStarted_;
  19726. }
  19727. if (request === this.hasStarted_) {
  19728. return;
  19729. }
  19730. this.hasStarted_ = request;
  19731. if (this.hasStarted_) {
  19732. this.addClass('vjs-has-started');
  19733. } else {
  19734. this.removeClass('vjs-has-started');
  19735. }
  19736. }
  19737. /**
  19738. * Fired whenever the media begins or resumes playback
  19739. *
  19740. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  19741. * @fires Player#play
  19742. * @listens Tech#play
  19743. * @private
  19744. */
  19745. handleTechPlay_() {
  19746. this.removeClass('vjs-ended', 'vjs-paused');
  19747. this.addClass('vjs-playing');
  19748. // hide the poster when the user hits play
  19749. this.hasStarted(true);
  19750. /**
  19751. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  19752. * playback has started or resumed.
  19753. *
  19754. * @event Player#play
  19755. * @type {Event}
  19756. */
  19757. this.trigger('play');
  19758. }
  19759. /**
  19760. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  19761. *
  19762. * If there were any events queued while the playback rate was zero, fire
  19763. * those events now.
  19764. *
  19765. * @private
  19766. * @method Player#handleTechRateChange_
  19767. * @fires Player#ratechange
  19768. * @listens Tech#ratechange
  19769. */
  19770. handleTechRateChange_() {
  19771. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  19772. this.queuedCallbacks_.forEach(queued => queued.callback(queued.event));
  19773. this.queuedCallbacks_ = [];
  19774. }
  19775. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  19776. /**
  19777. * Fires when the playing speed of the audio/video is changed
  19778. *
  19779. * @event Player#ratechange
  19780. * @type {event}
  19781. */
  19782. this.trigger('ratechange');
  19783. }
  19784. /**
  19785. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  19786. *
  19787. * @fires Player#waiting
  19788. * @listens Tech#waiting
  19789. * @private
  19790. */
  19791. handleTechWaiting_() {
  19792. this.addClass('vjs-waiting');
  19793. /**
  19794. * A readyState change on the DOM element has caused playback to stop.
  19795. *
  19796. * @event Player#waiting
  19797. * @type {Event}
  19798. */
  19799. this.trigger('waiting');
  19800. // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  19801. // premature removal of the waiting class, wait for the time to change.
  19802. const timeWhenWaiting = this.currentTime();
  19803. const timeUpdateListener = () => {
  19804. if (timeWhenWaiting !== this.currentTime()) {
  19805. this.removeClass('vjs-waiting');
  19806. this.off('timeupdate', timeUpdateListener);
  19807. }
  19808. };
  19809. this.on('timeupdate', timeUpdateListener);
  19810. }
  19811. /**
  19812. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  19813. * > Note: This is not consistent between browsers. See #1351
  19814. *
  19815. * @fires Player#canplay
  19816. * @listens Tech#canplay
  19817. * @private
  19818. */
  19819. handleTechCanPlay_() {
  19820. this.removeClass('vjs-waiting');
  19821. /**
  19822. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  19823. *
  19824. * @event Player#canplay
  19825. * @type {Event}
  19826. */
  19827. this.trigger('canplay');
  19828. }
  19829. /**
  19830. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  19831. *
  19832. * @fires Player#canplaythrough
  19833. * @listens Tech#canplaythrough
  19834. * @private
  19835. */
  19836. handleTechCanPlayThrough_() {
  19837. this.removeClass('vjs-waiting');
  19838. /**
  19839. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  19840. * entire media file can be played without buffering.
  19841. *
  19842. * @event Player#canplaythrough
  19843. * @type {Event}
  19844. */
  19845. this.trigger('canplaythrough');
  19846. }
  19847. /**
  19848. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  19849. *
  19850. * @fires Player#playing
  19851. * @listens Tech#playing
  19852. * @private
  19853. */
  19854. handleTechPlaying_() {
  19855. this.removeClass('vjs-waiting');
  19856. /**
  19857. * The media is no longer blocked from playback, and has started playing.
  19858. *
  19859. * @event Player#playing
  19860. * @type {Event}
  19861. */
  19862. this.trigger('playing');
  19863. }
  19864. /**
  19865. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  19866. *
  19867. * @fires Player#seeking
  19868. * @listens Tech#seeking
  19869. * @private
  19870. */
  19871. handleTechSeeking_() {
  19872. this.addClass('vjs-seeking');
  19873. /**
  19874. * Fired whenever the player is jumping to a new time
  19875. *
  19876. * @event Player#seeking
  19877. * @type {Event}
  19878. */
  19879. this.trigger('seeking');
  19880. }
  19881. /**
  19882. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  19883. *
  19884. * @fires Player#seeked
  19885. * @listens Tech#seeked
  19886. * @private
  19887. */
  19888. handleTechSeeked_() {
  19889. this.removeClass('vjs-seeking', 'vjs-ended');
  19890. /**
  19891. * Fired when the player has finished jumping to a new time
  19892. *
  19893. * @event Player#seeked
  19894. * @type {Event}
  19895. */
  19896. this.trigger('seeked');
  19897. }
  19898. /**
  19899. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  19900. *
  19901. * @fires Player#pause
  19902. * @listens Tech#pause
  19903. * @private
  19904. */
  19905. handleTechPause_() {
  19906. this.removeClass('vjs-playing');
  19907. this.addClass('vjs-paused');
  19908. /**
  19909. * Fired whenever the media has been paused
  19910. *
  19911. * @event Player#pause
  19912. * @type {Event}
  19913. */
  19914. this.trigger('pause');
  19915. }
  19916. /**
  19917. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  19918. *
  19919. * @fires Player#ended
  19920. * @listens Tech#ended
  19921. * @private
  19922. */
  19923. handleTechEnded_() {
  19924. this.addClass('vjs-ended');
  19925. this.removeClass('vjs-waiting');
  19926. if (this.options_.loop) {
  19927. this.currentTime(0);
  19928. this.play();
  19929. } else if (!this.paused()) {
  19930. this.pause();
  19931. }
  19932. /**
  19933. * Fired when the end of the media resource is reached (currentTime == duration)
  19934. *
  19935. * @event Player#ended
  19936. * @type {Event}
  19937. */
  19938. this.trigger('ended');
  19939. }
  19940. /**
  19941. * Fired when the duration of the media resource is first known or changed
  19942. *
  19943. * @listens Tech#durationchange
  19944. * @private
  19945. */
  19946. handleTechDurationChange_() {
  19947. this.duration(this.techGet_('duration'));
  19948. }
  19949. /**
  19950. * Handle a click on the media element to play/pause
  19951. *
  19952. * @param {Event} event
  19953. * the event that caused this function to trigger
  19954. *
  19955. * @listens Tech#click
  19956. * @private
  19957. */
  19958. handleTechClick_(event) {
  19959. // When controls are disabled a click should not toggle playback because
  19960. // the click is considered a control
  19961. if (!this.controls_) {
  19962. return;
  19963. }
  19964. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  19965. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  19966. this.options_.userActions.click.call(this, event);
  19967. } else if (this.paused()) {
  19968. silencePromise(this.play());
  19969. } else {
  19970. this.pause();
  19971. }
  19972. }
  19973. }
  19974. /**
  19975. * Handle a double-click on the media element to enter/exit fullscreen
  19976. *
  19977. * @param {Event} event
  19978. * the event that caused this function to trigger
  19979. *
  19980. * @listens Tech#dblclick
  19981. * @private
  19982. */
  19983. handleTechDoubleClick_(event) {
  19984. if (!this.controls_) {
  19985. return;
  19986. }
  19987. // we do not want to toggle fullscreen state
  19988. // when double-clicking inside a control bar or a modal
  19989. const inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), el => el.contains(event.target));
  19990. if (!inAllowedEls) {
  19991. /*
  19992. * options.userActions.doubleClick
  19993. *
  19994. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  19995. * Set to `false` to disable double-click handling
  19996. * Set to a function to substitute an external double-click handler
  19997. */
  19998. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  19999. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  20000. this.options_.userActions.doubleClick.call(this, event);
  20001. } else if (this.isFullscreen()) {
  20002. this.exitFullscreen();
  20003. } else {
  20004. this.requestFullscreen();
  20005. }
  20006. }
  20007. }
  20008. }
  20009. /**
  20010. * Handle a tap on the media element. It will toggle the user
  20011. * activity state, which hides and shows the controls.
  20012. *
  20013. * @listens Tech#tap
  20014. * @private
  20015. */
  20016. handleTechTap_() {
  20017. this.userActive(!this.userActive());
  20018. }
  20019. /**
  20020. * Handle touch to start
  20021. *
  20022. * @listens Tech#touchstart
  20023. * @private
  20024. */
  20025. handleTechTouchStart_() {
  20026. this.userWasActive = this.userActive();
  20027. }
  20028. /**
  20029. * Handle touch to move
  20030. *
  20031. * @listens Tech#touchmove
  20032. * @private
  20033. */
  20034. handleTechTouchMove_() {
  20035. if (this.userWasActive) {
  20036. this.reportUserActivity();
  20037. }
  20038. }
  20039. /**
  20040. * Handle touch to end
  20041. *
  20042. * @param {Event} event
  20043. * the touchend event that triggered
  20044. * this function
  20045. *
  20046. * @listens Tech#touchend
  20047. * @private
  20048. */
  20049. handleTechTouchEnd_(event) {
  20050. // Stop the mouse events from also happening
  20051. if (event.cancelable) {
  20052. event.preventDefault();
  20053. }
  20054. }
  20055. /**
  20056. * @private
  20057. */
  20058. toggleFullscreenClass_() {
  20059. if (this.isFullscreen()) {
  20060. this.addClass('vjs-fullscreen');
  20061. } else {
  20062. this.removeClass('vjs-fullscreen');
  20063. }
  20064. }
  20065. /**
  20066. * when the document fschange event triggers it calls this
  20067. */
  20068. documentFullscreenChange_(e) {
  20069. const targetPlayer = e.target.player;
  20070. // if another player was fullscreen
  20071. // do a null check for targetPlayer because older firefox's would put document as e.target
  20072. if (targetPlayer && targetPlayer !== this) {
  20073. return;
  20074. }
  20075. const el = this.el();
  20076. let isFs = document__default["default"][this.fsApi_.fullscreenElement] === el;
  20077. if (!isFs && el.matches) {
  20078. isFs = el.matches(':' + this.fsApi_.fullscreen);
  20079. } else if (!isFs && el.msMatchesSelector) {
  20080. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  20081. }
  20082. this.isFullscreen(isFs);
  20083. }
  20084. /**
  20085. * Handle Tech Fullscreen Change
  20086. *
  20087. * @param {Event} event
  20088. * the fullscreenchange event that triggered this function
  20089. *
  20090. * @param {Object} data
  20091. * the data that was sent with the event
  20092. *
  20093. * @private
  20094. * @listens Tech#fullscreenchange
  20095. * @fires Player#fullscreenchange
  20096. */
  20097. handleTechFullscreenChange_(event, data) {
  20098. if (data) {
  20099. if (data.nativeIOSFullscreen) {
  20100. this.addClass('vjs-ios-native-fs');
  20101. this.tech_.one('webkitendfullscreen', () => {
  20102. this.removeClass('vjs-ios-native-fs');
  20103. });
  20104. }
  20105. this.isFullscreen(data.isFullscreen);
  20106. }
  20107. }
  20108. handleTechFullscreenError_(event, err) {
  20109. this.trigger('fullscreenerror', err);
  20110. }
  20111. /**
  20112. * @private
  20113. */
  20114. togglePictureInPictureClass_() {
  20115. if (this.isInPictureInPicture()) {
  20116. this.addClass('vjs-picture-in-picture');
  20117. } else {
  20118. this.removeClass('vjs-picture-in-picture');
  20119. }
  20120. }
  20121. /**
  20122. * Handle Tech Enter Picture-in-Picture.
  20123. *
  20124. * @param {Event} event
  20125. * the enterpictureinpicture event that triggered this function
  20126. *
  20127. * @private
  20128. * @listens Tech#enterpictureinpicture
  20129. */
  20130. handleTechEnterPictureInPicture_(event) {
  20131. this.isInPictureInPicture(true);
  20132. }
  20133. /**
  20134. * Handle Tech Leave Picture-in-Picture.
  20135. *
  20136. * @param {Event} event
  20137. * the leavepictureinpicture event that triggered this function
  20138. *
  20139. * @private
  20140. * @listens Tech#leavepictureinpicture
  20141. */
  20142. handleTechLeavePictureInPicture_(event) {
  20143. this.isInPictureInPicture(false);
  20144. }
  20145. /**
  20146. * Fires when an error occurred during the loading of an audio/video.
  20147. *
  20148. * @private
  20149. * @listens Tech#error
  20150. */
  20151. handleTechError_() {
  20152. const error = this.tech_.error();
  20153. this.error(error);
  20154. }
  20155. /**
  20156. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  20157. *
  20158. * @fires Player#textdata
  20159. * @listens Tech#textdata
  20160. * @private
  20161. */
  20162. handleTechTextData_() {
  20163. let data = null;
  20164. if (arguments.length > 1) {
  20165. data = arguments[1];
  20166. }
  20167. /**
  20168. * Fires when we get a textdata event from tech
  20169. *
  20170. * @event Player#textdata
  20171. * @type {Event}
  20172. */
  20173. this.trigger('textdata', data);
  20174. }
  20175. /**
  20176. * Get object for cached values.
  20177. *
  20178. * @return {Object}
  20179. * get the current object cache
  20180. */
  20181. getCache() {
  20182. return this.cache_;
  20183. }
  20184. /**
  20185. * Resets the internal cache object.
  20186. *
  20187. * Using this function outside the player constructor or reset method may
  20188. * have unintended side-effects.
  20189. *
  20190. * @private
  20191. */
  20192. resetCache_() {
  20193. this.cache_ = {
  20194. // Right now, the currentTime is not _really_ cached because it is always
  20195. // retrieved from the tech (see: currentTime). However, for completeness,
  20196. // we set it to zero here to ensure that if we do start actually caching
  20197. // it, we reset it along with everything else.
  20198. currentTime: 0,
  20199. initTime: 0,
  20200. inactivityTimeout: this.options_.inactivityTimeout,
  20201. duration: NaN,
  20202. lastVolume: 1,
  20203. lastPlaybackRate: this.defaultPlaybackRate(),
  20204. media: null,
  20205. src: '',
  20206. source: {},
  20207. sources: [],
  20208. playbackRates: [],
  20209. volume: 1
  20210. };
  20211. }
  20212. /**
  20213. * Pass values to the playback tech
  20214. *
  20215. * @param {string} [method]
  20216. * the method to call
  20217. *
  20218. * @param {Object} arg
  20219. * the argument to pass
  20220. *
  20221. * @private
  20222. */
  20223. techCall_(method, arg) {
  20224. // If it's not ready yet, call method when it is
  20225. this.ready(function () {
  20226. if (method in allowedSetters) {
  20227. return set(this.middleware_, this.tech_, method, arg);
  20228. } else if (method in allowedMediators) {
  20229. return mediate(this.middleware_, this.tech_, method, arg);
  20230. }
  20231. try {
  20232. if (this.tech_) {
  20233. this.tech_[method](arg);
  20234. }
  20235. } catch (e) {
  20236. log$1(e);
  20237. throw e;
  20238. }
  20239. }, true);
  20240. }
  20241. /**
  20242. * Mediate attempt to call playback tech method
  20243. * and return the value of the method called.
  20244. *
  20245. * @param {string} method
  20246. * Tech method
  20247. *
  20248. * @return {*}
  20249. * Value returned by the tech method called, undefined if tech
  20250. * is not ready or tech method is not present
  20251. *
  20252. * @private
  20253. */
  20254. techGet_(method) {
  20255. if (!this.tech_ || !this.tech_.isReady_) {
  20256. return;
  20257. }
  20258. if (method in allowedGetters) {
  20259. return get(this.middleware_, this.tech_, method);
  20260. } else if (method in allowedMediators) {
  20261. return mediate(this.middleware_, this.tech_, method);
  20262. }
  20263. // Log error when playback tech object is present but method
  20264. // is undefined or unavailable
  20265. try {
  20266. return this.tech_[method]();
  20267. } catch (e) {
  20268. // When building additional tech libs, an expected method may not be defined yet
  20269. if (this.tech_[method] === undefined) {
  20270. log$1(`Video.js: ${method} method not defined for ${this.techName_} playback technology.`, e);
  20271. throw e;
  20272. }
  20273. // When a method isn't available on the object it throws a TypeError
  20274. if (e.name === 'TypeError') {
  20275. log$1(`Video.js: ${method} unavailable on ${this.techName_} playback technology element.`, e);
  20276. this.tech_.isReady_ = false;
  20277. throw e;
  20278. }
  20279. // If error unknown, just log and throw
  20280. log$1(e);
  20281. throw e;
  20282. }
  20283. }
  20284. /**
  20285. * Attempt to begin playback at the first opportunity.
  20286. *
  20287. * @return {Promise|undefined}
  20288. * Returns a promise if the browser supports Promises (or one
  20289. * was passed in as an option). This promise will be resolved on
  20290. * the return value of play. If this is undefined it will fulfill the
  20291. * promise chain otherwise the promise chain will be fulfilled when
  20292. * the promise from play is fulfilled.
  20293. */
  20294. play() {
  20295. return new Promise(resolve => {
  20296. this.play_(resolve);
  20297. });
  20298. }
  20299. /**
  20300. * The actual logic for play, takes a callback that will be resolved on the
  20301. * return value of play. This allows us to resolve to the play promise if there
  20302. * is one on modern browsers.
  20303. *
  20304. * @private
  20305. * @param {Function} [callback]
  20306. * The callback that should be called when the techs play is actually called
  20307. */
  20308. play_(callback = silencePromise) {
  20309. this.playCallbacks_.push(callback);
  20310. const isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  20311. const isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS);
  20312. // treat calls to play_ somewhat like the `one` event function
  20313. if (this.waitToPlay_) {
  20314. this.off(['ready', 'loadstart'], this.waitToPlay_);
  20315. this.waitToPlay_ = null;
  20316. }
  20317. // if the player/tech is not ready or the src itself is not ready
  20318. // queue up a call to play on `ready` or `loadstart`
  20319. if (!this.isReady_ || !isSrcReady) {
  20320. this.waitToPlay_ = e => {
  20321. this.play_();
  20322. };
  20323. this.one(['ready', 'loadstart'], this.waitToPlay_);
  20324. // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  20325. // in that case, we need to prime the video element by calling load so it'll be ready in time
  20326. if (!isSrcReady && isSafariOrIOS) {
  20327. this.load();
  20328. }
  20329. return;
  20330. }
  20331. // If the player/tech is ready and we have a source, we can attempt playback.
  20332. const val = this.techGet_('play');
  20333. // For native playback, reset the progress bar if we get a play call from a replay.
  20334. const isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  20335. if (isNativeReplay) {
  20336. this.resetProgressBar_();
  20337. }
  20338. // play was terminated if the returned value is null
  20339. if (val === null) {
  20340. this.runPlayTerminatedQueue_();
  20341. } else {
  20342. this.runPlayCallbacks_(val);
  20343. }
  20344. }
  20345. /**
  20346. * These functions will be run when if play is terminated. If play
  20347. * runPlayCallbacks_ is run these function will not be run. This allows us
  20348. * to differentiate between a terminated play and an actual call to play.
  20349. */
  20350. runPlayTerminatedQueue_() {
  20351. const queue = this.playTerminatedQueue_.slice(0);
  20352. this.playTerminatedQueue_ = [];
  20353. queue.forEach(function (q) {
  20354. q();
  20355. });
  20356. }
  20357. /**
  20358. * When a callback to play is delayed we have to run these
  20359. * callbacks when play is actually called on the tech. This function
  20360. * runs the callbacks that were delayed and accepts the return value
  20361. * from the tech.
  20362. *
  20363. * @param {undefined|Promise} val
  20364. * The return value from the tech.
  20365. */
  20366. runPlayCallbacks_(val) {
  20367. const callbacks = this.playCallbacks_.slice(0);
  20368. this.playCallbacks_ = [];
  20369. // clear play terminatedQueue since we finished a real play
  20370. this.playTerminatedQueue_ = [];
  20371. callbacks.forEach(function (cb) {
  20372. cb(val);
  20373. });
  20374. }
  20375. /**
  20376. * Pause the video playback
  20377. *
  20378. * @return {Player}
  20379. * A reference to the player object this function was called on
  20380. */
  20381. pause() {
  20382. this.techCall_('pause');
  20383. }
  20384. /**
  20385. * Check if the player is paused or has yet to play
  20386. *
  20387. * @return {boolean}
  20388. * - false: if the media is currently playing
  20389. * - true: if media is not currently playing
  20390. */
  20391. paused() {
  20392. // The initial state of paused should be true (in Safari it's actually false)
  20393. return this.techGet_('paused') === false ? false : true;
  20394. }
  20395. /**
  20396. * Get a TimeRange object representing the current ranges of time that the user
  20397. * has played.
  20398. *
  20399. * @return { import('./utils/time').TimeRange }
  20400. * A time range object that represents all the increments of time that have
  20401. * been played.
  20402. */
  20403. played() {
  20404. return this.techGet_('played') || createTimeRanges$1(0, 0);
  20405. }
  20406. /**
  20407. * Returns whether or not the user is "scrubbing". Scrubbing is
  20408. * when the user has clicked the progress bar handle and is
  20409. * dragging it along the progress bar.
  20410. *
  20411. * @param {boolean} [isScrubbing]
  20412. * whether the user is or is not scrubbing
  20413. *
  20414. * @return {boolean}
  20415. * The value of scrubbing when getting
  20416. */
  20417. scrubbing(isScrubbing) {
  20418. if (typeof isScrubbing === 'undefined') {
  20419. return this.scrubbing_;
  20420. }
  20421. this.scrubbing_ = !!isScrubbing;
  20422. this.techCall_('setScrubbing', this.scrubbing_);
  20423. if (isScrubbing) {
  20424. this.addClass('vjs-scrubbing');
  20425. } else {
  20426. this.removeClass('vjs-scrubbing');
  20427. }
  20428. }
  20429. /**
  20430. * Get or set the current time (in seconds)
  20431. *
  20432. * @param {number|string} [seconds]
  20433. * The time to seek to in seconds
  20434. *
  20435. * @return {number}
  20436. * - the current time in seconds when getting
  20437. */
  20438. currentTime(seconds) {
  20439. if (typeof seconds !== 'undefined') {
  20440. if (seconds < 0) {
  20441. seconds = 0;
  20442. }
  20443. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  20444. this.cache_.initTime = seconds;
  20445. this.off('canplay', this.boundApplyInitTime_);
  20446. this.one('canplay', this.boundApplyInitTime_);
  20447. return;
  20448. }
  20449. this.techCall_('setCurrentTime', seconds);
  20450. this.cache_.initTime = 0;
  20451. return;
  20452. }
  20453. // cache last currentTime and return. default to 0 seconds
  20454. //
  20455. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  20456. // currentTime when scrubbing, but may not provide much performance benefit after all.
  20457. // Should be tested. Also something has to read the actual current time or the cache will
  20458. // never get updated.
  20459. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  20460. return this.cache_.currentTime;
  20461. }
  20462. /**
  20463. * Apply the value of initTime stored in cache as currentTime.
  20464. *
  20465. * @private
  20466. */
  20467. applyInitTime_() {
  20468. this.currentTime(this.cache_.initTime);
  20469. }
  20470. /**
  20471. * Normally gets the length in time of the video in seconds;
  20472. * in all but the rarest use cases an argument will NOT be passed to the method
  20473. *
  20474. * > **NOTE**: The video must have started loading before the duration can be
  20475. * known, and depending on preload behaviour may not be known until the video starts
  20476. * playing.
  20477. *
  20478. * @fires Player#durationchange
  20479. *
  20480. * @param {number} [seconds]
  20481. * The duration of the video to set in seconds
  20482. *
  20483. * @return {number}
  20484. * - The duration of the video in seconds when getting
  20485. */
  20486. duration(seconds) {
  20487. if (seconds === undefined) {
  20488. // return NaN if the duration is not known
  20489. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  20490. }
  20491. seconds = parseFloat(seconds);
  20492. // Standardize on Infinity for signaling video is live
  20493. if (seconds < 0) {
  20494. seconds = Infinity;
  20495. }
  20496. if (seconds !== this.cache_.duration) {
  20497. // Cache the last set value for optimized scrubbing
  20498. this.cache_.duration = seconds;
  20499. if (seconds === Infinity) {
  20500. this.addClass('vjs-live');
  20501. } else {
  20502. this.removeClass('vjs-live');
  20503. }
  20504. if (!isNaN(seconds)) {
  20505. // Do not fire durationchange unless the duration value is known.
  20506. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  20507. /**
  20508. * @event Player#durationchange
  20509. * @type {Event}
  20510. */
  20511. this.trigger('durationchange');
  20512. }
  20513. }
  20514. }
  20515. /**
  20516. * Calculates how much time is left in the video. Not part
  20517. * of the native video API.
  20518. *
  20519. * @return {number}
  20520. * The time remaining in seconds
  20521. */
  20522. remainingTime() {
  20523. return this.duration() - this.currentTime();
  20524. }
  20525. /**
  20526. * A remaining time function that is intended to be used when
  20527. * the time is to be displayed directly to the user.
  20528. *
  20529. * @return {number}
  20530. * The rounded time remaining in seconds
  20531. */
  20532. remainingTimeDisplay() {
  20533. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  20534. }
  20535. //
  20536. // Kind of like an array of portions of the video that have been downloaded.
  20537. /**
  20538. * Get a TimeRange object with an array of the times of the video
  20539. * that have been downloaded. If you just want the percent of the
  20540. * video that's been downloaded, use bufferedPercent.
  20541. *
  20542. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  20543. *
  20544. * @return { import('./utils/time').TimeRange }
  20545. * A mock {@link TimeRanges} object (following HTML spec)
  20546. */
  20547. buffered() {
  20548. let buffered = this.techGet_('buffered');
  20549. if (!buffered || !buffered.length) {
  20550. buffered = createTimeRanges$1(0, 0);
  20551. }
  20552. return buffered;
  20553. }
  20554. /**
  20555. * Get the percent (as a decimal) of the video that's been downloaded.
  20556. * This method is not a part of the native HTML video API.
  20557. *
  20558. * @return {number}
  20559. * A decimal between 0 and 1 representing the percent
  20560. * that is buffered 0 being 0% and 1 being 100%
  20561. */
  20562. bufferedPercent() {
  20563. return bufferedPercent(this.buffered(), this.duration());
  20564. }
  20565. /**
  20566. * Get the ending time of the last buffered time range
  20567. * This is used in the progress bar to encapsulate all time ranges.
  20568. *
  20569. * @return {number}
  20570. * The end of the last buffered time range
  20571. */
  20572. bufferedEnd() {
  20573. const buffered = this.buffered();
  20574. const duration = this.duration();
  20575. let end = buffered.end(buffered.length - 1);
  20576. if (end > duration) {
  20577. end = duration;
  20578. }
  20579. return end;
  20580. }
  20581. /**
  20582. * Get or set the current volume of the media
  20583. *
  20584. * @param {number} [percentAsDecimal]
  20585. * The new volume as a decimal percent:
  20586. * - 0 is muted/0%/off
  20587. * - 1.0 is 100%/full
  20588. * - 0.5 is half volume or 50%
  20589. *
  20590. * @return {number}
  20591. * The current volume as a percent when getting
  20592. */
  20593. volume(percentAsDecimal) {
  20594. let vol;
  20595. if (percentAsDecimal !== undefined) {
  20596. // Force value to between 0 and 1
  20597. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  20598. this.cache_.volume = vol;
  20599. this.techCall_('setVolume', vol);
  20600. if (vol > 0) {
  20601. this.lastVolume_(vol);
  20602. }
  20603. return;
  20604. }
  20605. // Default to 1 when returning current volume.
  20606. vol = parseFloat(this.techGet_('volume'));
  20607. return isNaN(vol) ? 1 : vol;
  20608. }
  20609. /**
  20610. * Get the current muted state, or turn mute on or off
  20611. *
  20612. * @param {boolean} [muted]
  20613. * - true to mute
  20614. * - false to unmute
  20615. *
  20616. * @return {boolean}
  20617. * - true if mute is on and getting
  20618. * - false if mute is off and getting
  20619. */
  20620. muted(muted) {
  20621. if (muted !== undefined) {
  20622. this.techCall_('setMuted', muted);
  20623. return;
  20624. }
  20625. return this.techGet_('muted') || false;
  20626. }
  20627. /**
  20628. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  20629. * indicates the state of muted on initial playback.
  20630. *
  20631. * ```js
  20632. * var myPlayer = videojs('some-player-id');
  20633. *
  20634. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  20635. *
  20636. * // get, should be false
  20637. * console.log(myPlayer.defaultMuted());
  20638. * // set to true
  20639. * myPlayer.defaultMuted(true);
  20640. * // get should be true
  20641. * console.log(myPlayer.defaultMuted());
  20642. * ```
  20643. *
  20644. * @param {boolean} [defaultMuted]
  20645. * - true to mute
  20646. * - false to unmute
  20647. *
  20648. * @return {boolean|Player}
  20649. * - true if defaultMuted is on and getting
  20650. * - false if defaultMuted is off and getting
  20651. * - A reference to the current player when setting
  20652. */
  20653. defaultMuted(defaultMuted) {
  20654. if (defaultMuted !== undefined) {
  20655. return this.techCall_('setDefaultMuted', defaultMuted);
  20656. }
  20657. return this.techGet_('defaultMuted') || false;
  20658. }
  20659. /**
  20660. * Get the last volume, or set it
  20661. *
  20662. * @param {number} [percentAsDecimal]
  20663. * The new last volume as a decimal percent:
  20664. * - 0 is muted/0%/off
  20665. * - 1.0 is 100%/full
  20666. * - 0.5 is half volume or 50%
  20667. *
  20668. * @return {number}
  20669. * the current value of lastVolume as a percent when getting
  20670. *
  20671. * @private
  20672. */
  20673. lastVolume_(percentAsDecimal) {
  20674. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  20675. this.cache_.lastVolume = percentAsDecimal;
  20676. return;
  20677. }
  20678. return this.cache_.lastVolume;
  20679. }
  20680. /**
  20681. * Check if current tech can support native fullscreen
  20682. * (e.g. with built in controls like iOS)
  20683. *
  20684. * @return {boolean}
  20685. * if native fullscreen is supported
  20686. */
  20687. supportsFullScreen() {
  20688. return this.techGet_('supportsFullScreen') || false;
  20689. }
  20690. /**
  20691. * Check if the player is in fullscreen mode or tell the player that it
  20692. * is or is not in fullscreen mode.
  20693. *
  20694. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  20695. * property and instead document.fullscreenElement is used. But isFullscreen is
  20696. * still a valuable property for internal player workings.
  20697. *
  20698. * @param {boolean} [isFS]
  20699. * Set the players current fullscreen state
  20700. *
  20701. * @return {boolean}
  20702. * - true if fullscreen is on and getting
  20703. * - false if fullscreen is off and getting
  20704. */
  20705. isFullscreen(isFS) {
  20706. if (isFS !== undefined) {
  20707. const oldValue = this.isFullscreen_;
  20708. this.isFullscreen_ = Boolean(isFS);
  20709. // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  20710. // this is the only place where we trigger fullscreenchange events for older browsers
  20711. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  20712. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  20713. /**
  20714. * @event Player#fullscreenchange
  20715. * @type {Event}
  20716. */
  20717. this.trigger('fullscreenchange');
  20718. }
  20719. this.toggleFullscreenClass_();
  20720. return;
  20721. }
  20722. return this.isFullscreen_;
  20723. }
  20724. /**
  20725. * Increase the size of the video to full screen
  20726. * In some browsers, full screen is not supported natively, so it enters
  20727. * "full window mode", where the video fills the browser window.
  20728. * In browsers and devices that support native full screen, sometimes the
  20729. * browser's default controls will be shown, and not the Video.js custom skin.
  20730. * This includes most mobile devices (iOS, Android) and older versions of
  20731. * Safari.
  20732. *
  20733. * @param {Object} [fullscreenOptions]
  20734. * Override the player fullscreen options
  20735. *
  20736. * @fires Player#fullscreenchange
  20737. */
  20738. requestFullscreen(fullscreenOptions) {
  20739. if (this.isInPictureInPicture()) {
  20740. this.exitPictureInPicture();
  20741. }
  20742. const self = this;
  20743. return new Promise((resolve, reject) => {
  20744. function offHandler() {
  20745. self.off('fullscreenerror', errorHandler);
  20746. self.off('fullscreenchange', changeHandler);
  20747. }
  20748. function changeHandler() {
  20749. offHandler();
  20750. resolve();
  20751. }
  20752. function errorHandler(e, err) {
  20753. offHandler();
  20754. reject(err);
  20755. }
  20756. self.one('fullscreenchange', changeHandler);
  20757. self.one('fullscreenerror', errorHandler);
  20758. const promise = self.requestFullscreenHelper_(fullscreenOptions);
  20759. if (promise) {
  20760. promise.then(offHandler, offHandler);
  20761. promise.then(resolve, reject);
  20762. }
  20763. });
  20764. }
  20765. requestFullscreenHelper_(fullscreenOptions) {
  20766. let fsOptions;
  20767. // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  20768. // Use defaults or player configured option unless passed directly to this method.
  20769. if (!this.fsApi_.prefixed) {
  20770. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  20771. if (fullscreenOptions !== undefined) {
  20772. fsOptions = fullscreenOptions;
  20773. }
  20774. }
  20775. // This method works as follows:
  20776. // 1. if a fullscreen api is available, use it
  20777. // 1. call requestFullscreen with potential options
  20778. // 2. if we got a promise from above, use it to update isFullscreen()
  20779. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  20780. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  20781. // 3. otherwise, use "fullWindow" mode
  20782. if (this.fsApi_.requestFullscreen) {
  20783. const promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  20784. // Even on browsers with promise support this may not return a promise
  20785. if (promise) {
  20786. promise.then(() => this.isFullscreen(true), () => this.isFullscreen(false));
  20787. }
  20788. return promise;
  20789. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20790. // we can't take the video.js controls fullscreen but we can go fullscreen
  20791. // with native controls
  20792. this.techCall_('enterFullScreen');
  20793. } else {
  20794. // fullscreen isn't supported so we'll just stretch the video element to
  20795. // fill the viewport
  20796. this.enterFullWindow();
  20797. }
  20798. }
  20799. /**
  20800. * Return the video to its normal size after having been in full screen mode
  20801. *
  20802. * @fires Player#fullscreenchange
  20803. */
  20804. exitFullscreen() {
  20805. const self = this;
  20806. return new Promise((resolve, reject) => {
  20807. function offHandler() {
  20808. self.off('fullscreenerror', errorHandler);
  20809. self.off('fullscreenchange', changeHandler);
  20810. }
  20811. function changeHandler() {
  20812. offHandler();
  20813. resolve();
  20814. }
  20815. function errorHandler(e, err) {
  20816. offHandler();
  20817. reject(err);
  20818. }
  20819. self.one('fullscreenchange', changeHandler);
  20820. self.one('fullscreenerror', errorHandler);
  20821. const promise = self.exitFullscreenHelper_();
  20822. if (promise) {
  20823. promise.then(offHandler, offHandler);
  20824. // map the promise to our resolve/reject methods
  20825. promise.then(resolve, reject);
  20826. }
  20827. });
  20828. }
  20829. exitFullscreenHelper_() {
  20830. if (this.fsApi_.requestFullscreen) {
  20831. const promise = document__default["default"][this.fsApi_.exitFullscreen]();
  20832. // Even on browsers with promise support this may not return a promise
  20833. if (promise) {
  20834. // we're splitting the promise here, so, we want to catch the
  20835. // potential error so that this chain doesn't have unhandled errors
  20836. silencePromise(promise.then(() => this.isFullscreen(false)));
  20837. }
  20838. return promise;
  20839. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  20840. this.techCall_('exitFullScreen');
  20841. } else {
  20842. this.exitFullWindow();
  20843. }
  20844. }
  20845. /**
  20846. * When fullscreen isn't supported we can stretch the
  20847. * video container to as wide as the browser will let us.
  20848. *
  20849. * @fires Player#enterFullWindow
  20850. */
  20851. enterFullWindow() {
  20852. this.isFullscreen(true);
  20853. this.isFullWindow = true;
  20854. // Storing original doc overflow value to return to when fullscreen is off
  20855. this.docOrigOverflow = document__default["default"].documentElement.style.overflow;
  20856. // Add listener for esc key to exit fullscreen
  20857. on(document__default["default"], 'keydown', this.boundFullWindowOnEscKey_);
  20858. // Hide any scroll bars
  20859. document__default["default"].documentElement.style.overflow = 'hidden';
  20860. // Apply fullscreen styles
  20861. addClass(document__default["default"].body, 'vjs-full-window');
  20862. /**
  20863. * @event Player#enterFullWindow
  20864. * @type {Event}
  20865. */
  20866. this.trigger('enterFullWindow');
  20867. }
  20868. /**
  20869. * Check for call to either exit full window or
  20870. * full screen on ESC key
  20871. *
  20872. * @param {string} event
  20873. * Event to check for key press
  20874. */
  20875. fullWindowOnEscKey(event) {
  20876. if (keycode__default["default"].isEventKey(event, 'Esc')) {
  20877. if (this.isFullscreen() === true) {
  20878. if (!this.isFullWindow) {
  20879. this.exitFullscreen();
  20880. } else {
  20881. this.exitFullWindow();
  20882. }
  20883. }
  20884. }
  20885. }
  20886. /**
  20887. * Exit full window
  20888. *
  20889. * @fires Player#exitFullWindow
  20890. */
  20891. exitFullWindow() {
  20892. this.isFullscreen(false);
  20893. this.isFullWindow = false;
  20894. off(document__default["default"], 'keydown', this.boundFullWindowOnEscKey_);
  20895. // Unhide scroll bars.
  20896. document__default["default"].documentElement.style.overflow = this.docOrigOverflow;
  20897. // Remove fullscreen styles
  20898. removeClass(document__default["default"].body, 'vjs-full-window');
  20899. // Resize the box, controller, and poster to original sizes
  20900. // this.positionAll();
  20901. /**
  20902. * @event Player#exitFullWindow
  20903. * @type {Event}
  20904. */
  20905. this.trigger('exitFullWindow');
  20906. }
  20907. /**
  20908. * Disable Picture-in-Picture mode.
  20909. *
  20910. * @param {boolean} value
  20911. * - true will disable Picture-in-Picture mode
  20912. * - false will enable Picture-in-Picture mode
  20913. */
  20914. disablePictureInPicture(value) {
  20915. if (value === undefined) {
  20916. return this.techGet_('disablePictureInPicture');
  20917. }
  20918. this.techCall_('setDisablePictureInPicture', value);
  20919. this.options_.disablePictureInPicture = value;
  20920. this.trigger('disablepictureinpicturechanged');
  20921. }
  20922. /**
  20923. * Check if the player is in Picture-in-Picture mode or tell the player that it
  20924. * is or is not in Picture-in-Picture mode.
  20925. *
  20926. * @param {boolean} [isPiP]
  20927. * Set the players current Picture-in-Picture state
  20928. *
  20929. * @return {boolean}
  20930. * - true if Picture-in-Picture is on and getting
  20931. * - false if Picture-in-Picture is off and getting
  20932. */
  20933. isInPictureInPicture(isPiP) {
  20934. if (isPiP !== undefined) {
  20935. this.isInPictureInPicture_ = !!isPiP;
  20936. this.togglePictureInPictureClass_();
  20937. return;
  20938. }
  20939. return !!this.isInPictureInPicture_;
  20940. }
  20941. /**
  20942. * Create a floating video window always on top of other windows so that users may
  20943. * continue consuming media while they interact with other content sites, or
  20944. * applications on their device.
  20945. *
  20946. * This can use document picture-in-picture or element picture in picture
  20947. *
  20948. * Set `enableDocumentPictureInPicture` to `true` to use docPiP on a supported browser
  20949. * Else set `disablePictureInPicture` to `false` to disable elPiP on a supported browser
  20950. *
  20951. *
  20952. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/}
  20953. * @see [Spec]{@link https://wicg.github.io/document-picture-in-picture/}
  20954. *
  20955. * @fires Player#enterpictureinpicture
  20956. *
  20957. * @return {Promise}
  20958. * A promise with a Picture-in-Picture window.
  20959. */
  20960. requestPictureInPicture() {
  20961. if (this.options_.enableDocumentPictureInPicture && window__default["default"].documentPictureInPicture) {
  20962. const pipContainer = document__default["default"].createElement(this.el().tagName);
  20963. pipContainer.classList = this.el().classList;
  20964. pipContainer.classList.add('vjs-pip-container');
  20965. if (this.posterImage) {
  20966. pipContainer.appendChild(this.posterImage.el().cloneNode(true));
  20967. }
  20968. if (this.titleBar) {
  20969. pipContainer.appendChild(this.titleBar.el().cloneNode(true));
  20970. }
  20971. pipContainer.appendChild(createEl('p', {
  20972. className: 'vjs-pip-text'
  20973. }, {}, this.localize('Playing in picture-in-picture')));
  20974. return window__default["default"].documentPictureInPicture.requestWindow({
  20975. // The aspect ratio won't be correct, Chrome bug https://crbug.com/1407629
  20976. initialAspectRatio: this.videoWidth() / this.videoHeight(),
  20977. copyStyleSheets: true
  20978. }).then(pipWindow => {
  20979. this.el_.parentNode.insertBefore(pipContainer, this.el_);
  20980. pipWindow.document.body.append(this.el_);
  20981. pipWindow.document.body.classList.add('vjs-pip-window');
  20982. this.player_.isInPictureInPicture(true);
  20983. this.player_.trigger('enterpictureinpicture');
  20984. // Listen for the PiP closing event to move the video back.
  20985. pipWindow.addEventListener('unload', event => {
  20986. const pipVideo = event.target.querySelector('.video-js');
  20987. pipContainer.replaceWith(pipVideo);
  20988. this.player_.isInPictureInPicture(false);
  20989. this.player_.trigger('leavepictureinpicture');
  20990. });
  20991. return pipWindow;
  20992. });
  20993. }
  20994. if ('pictureInPictureEnabled' in document__default["default"] && this.disablePictureInPicture() === false) {
  20995. /**
  20996. * This event fires when the player enters picture in picture mode
  20997. *
  20998. * @event Player#enterpictureinpicture
  20999. * @type {Event}
  21000. */
  21001. return this.techGet_('requestPictureInPicture');
  21002. }
  21003. return Promise.reject('No PiP mode is available');
  21004. }
  21005. /**
  21006. * Exit Picture-in-Picture mode.
  21007. *
  21008. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21009. *
  21010. * @fires Player#leavepictureinpicture
  21011. *
  21012. * @return {Promise}
  21013. * A promise.
  21014. */
  21015. exitPictureInPicture() {
  21016. if (window__default["default"].documentPictureInPicture && window__default["default"].documentPictureInPicture.window) {
  21017. // With documentPictureInPicture, Player#leavepictureinpicture is fired in the unload handler
  21018. window__default["default"].documentPictureInPicture.window.close();
  21019. return Promise.resolve();
  21020. }
  21021. if ('pictureInPictureEnabled' in document__default["default"]) {
  21022. /**
  21023. * This event fires when the player leaves picture in picture mode
  21024. *
  21025. * @event Player#leavepictureinpicture
  21026. * @type {Event}
  21027. */
  21028. return document__default["default"].exitPictureInPicture();
  21029. }
  21030. }
  21031. /**
  21032. * Called when this Player has focus and a key gets pressed down, or when
  21033. * any Component of this player receives a key press that it doesn't handle.
  21034. * This allows player-wide hotkeys (either as defined below, or optionally
  21035. * by an external function).
  21036. *
  21037. * @param {Event} event
  21038. * The `keydown` event that caused this function to be called.
  21039. *
  21040. * @listens keydown
  21041. */
  21042. handleKeyDown(event) {
  21043. const {
  21044. userActions
  21045. } = this.options_;
  21046. // Bail out if hotkeys are not configured.
  21047. if (!userActions || !userActions.hotkeys) {
  21048. return;
  21049. }
  21050. // Function that determines whether or not to exclude an element from
  21051. // hotkeys handling.
  21052. const excludeElement = el => {
  21053. const tagName = el.tagName.toLowerCase();
  21054. // The first and easiest test is for `contenteditable` elements.
  21055. if (el.isContentEditable) {
  21056. return true;
  21057. }
  21058. // Inputs matching these types will still trigger hotkey handling as
  21059. // they are not text inputs.
  21060. const allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  21061. if (tagName === 'input') {
  21062. return allowedInputTypes.indexOf(el.type) === -1;
  21063. }
  21064. // The final test is by tag name. These tags will be excluded entirely.
  21065. const excludedTags = ['textarea'];
  21066. return excludedTags.indexOf(tagName) !== -1;
  21067. };
  21068. // Bail out if the user is focused on an interactive form element.
  21069. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  21070. return;
  21071. }
  21072. if (typeof userActions.hotkeys === 'function') {
  21073. userActions.hotkeys.call(this, event);
  21074. } else {
  21075. this.handleHotkeys(event);
  21076. }
  21077. }
  21078. /**
  21079. * Called when this Player receives a hotkey keydown event.
  21080. * Supported player-wide hotkeys are:
  21081. *
  21082. * f - toggle fullscreen
  21083. * m - toggle mute
  21084. * k or Space - toggle play/pause
  21085. *
  21086. * @param {Event} event
  21087. * The `keydown` event that caused this function to be called.
  21088. */
  21089. handleHotkeys(event) {
  21090. const hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {};
  21091. // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  21092. const {
  21093. fullscreenKey = keydownEvent => keycode__default["default"].isEventKey(keydownEvent, 'f'),
  21094. muteKey = keydownEvent => keycode__default["default"].isEventKey(keydownEvent, 'm'),
  21095. playPauseKey = keydownEvent => keycode__default["default"].isEventKey(keydownEvent, 'k') || keycode__default["default"].isEventKey(keydownEvent, 'Space')
  21096. } = hotkeys;
  21097. if (fullscreenKey.call(this, event)) {
  21098. event.preventDefault();
  21099. event.stopPropagation();
  21100. const FSToggle = Component$1.getComponent('FullscreenToggle');
  21101. if (document__default["default"][this.fsApi_.fullscreenEnabled] !== false) {
  21102. FSToggle.prototype.handleClick.call(this, event);
  21103. }
  21104. } else if (muteKey.call(this, event)) {
  21105. event.preventDefault();
  21106. event.stopPropagation();
  21107. const MuteToggle = Component$1.getComponent('MuteToggle');
  21108. MuteToggle.prototype.handleClick.call(this, event);
  21109. } else if (playPauseKey.call(this, event)) {
  21110. event.preventDefault();
  21111. event.stopPropagation();
  21112. const PlayToggle = Component$1.getComponent('PlayToggle');
  21113. PlayToggle.prototype.handleClick.call(this, event);
  21114. }
  21115. }
  21116. /**
  21117. * Check whether the player can play a given mimetype
  21118. *
  21119. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  21120. *
  21121. * @param {string} type
  21122. * The mimetype to check
  21123. *
  21124. * @return {string}
  21125. * 'probably', 'maybe', or '' (empty string)
  21126. */
  21127. canPlayType(type) {
  21128. let can;
  21129. // Loop through each playback technology in the options order
  21130. for (let i = 0, j = this.options_.techOrder; i < j.length; i++) {
  21131. const techName = j[i];
  21132. let tech = Tech.getTech(techName);
  21133. // Support old behavior of techs being registered as components.
  21134. // Remove once that deprecated behavior is removed.
  21135. if (!tech) {
  21136. tech = Component$1.getComponent(techName);
  21137. }
  21138. // Check if the current tech is defined before continuing
  21139. if (!tech) {
  21140. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21141. continue;
  21142. }
  21143. // Check if the browser supports this technology
  21144. if (tech.isSupported()) {
  21145. can = tech.canPlayType(type);
  21146. if (can) {
  21147. return can;
  21148. }
  21149. }
  21150. }
  21151. return '';
  21152. }
  21153. /**
  21154. * Select source based on tech-order or source-order
  21155. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  21156. * defaults to tech-order selection
  21157. *
  21158. * @param {Array} sources
  21159. * The sources for a media asset
  21160. *
  21161. * @return {Object|boolean}
  21162. * Object of source and tech order or false
  21163. */
  21164. selectSource(sources) {
  21165. // Get only the techs specified in `techOrder` that exist and are supported by the
  21166. // current platform
  21167. const techs = this.options_.techOrder.map(techName => {
  21168. return [techName, Tech.getTech(techName)];
  21169. }).filter(([techName, tech]) => {
  21170. // Check if the current tech is defined before continuing
  21171. if (tech) {
  21172. // Check if the browser supports this technology
  21173. return tech.isSupported();
  21174. }
  21175. log$1.error(`The "${techName}" tech is undefined. Skipped browser support check for that tech.`);
  21176. return false;
  21177. });
  21178. // Iterate over each `innerArray` element once per `outerArray` element and execute
  21179. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  21180. // that value.
  21181. const findFirstPassingTechSourcePair = function (outerArray, innerArray, tester) {
  21182. let found;
  21183. outerArray.some(outerChoice => {
  21184. return innerArray.some(innerChoice => {
  21185. found = tester(outerChoice, innerChoice);
  21186. if (found) {
  21187. return true;
  21188. }
  21189. });
  21190. });
  21191. return found;
  21192. };
  21193. let foundSourceAndTech;
  21194. const flip = fn => (a, b) => fn(b, a);
  21195. const finder = ([techName, tech], source) => {
  21196. if (tech.canPlaySource(source, this.options_[techName.toLowerCase()])) {
  21197. return {
  21198. source,
  21199. tech: techName
  21200. };
  21201. }
  21202. };
  21203. // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  21204. // to select from them based on their priority.
  21205. if (this.options_.sourceOrder) {
  21206. // Source-first ordering
  21207. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  21208. } else {
  21209. // Tech-first ordering
  21210. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  21211. }
  21212. return foundSourceAndTech || false;
  21213. }
  21214. /**
  21215. * Executes source setting and getting logic
  21216. *
  21217. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21218. * A SourceObject, an array of SourceObjects, or a string referencing
  21219. * a URL to a media source. It is _highly recommended_ that an object
  21220. * or array of objects is used here, so that source selection
  21221. * algorithms can take the `type` into account.
  21222. *
  21223. * If not provided, this method acts as a getter.
  21224. * @param {boolean} isRetry
  21225. * Indicates whether this is being called internally as a result of a retry
  21226. *
  21227. * @return {string|undefined}
  21228. * If the `source` argument is missing, returns the current source
  21229. * URL. Otherwise, returns nothing/undefined.
  21230. */
  21231. handleSrc_(source, isRetry) {
  21232. // getter usage
  21233. if (typeof source === 'undefined') {
  21234. return this.cache_.src || '';
  21235. }
  21236. // Reset retry behavior for new source
  21237. if (this.resetRetryOnError_) {
  21238. this.resetRetryOnError_();
  21239. }
  21240. // filter out invalid sources and turn our source into
  21241. // an array of source objects
  21242. const sources = filterSource(source);
  21243. // if a source was passed in then it is invalid because
  21244. // it was filtered to a zero length Array. So we have to
  21245. // show an error
  21246. if (!sources.length) {
  21247. this.setTimeout(function () {
  21248. this.error({
  21249. code: 4,
  21250. message: this.options_.notSupportedMessage
  21251. });
  21252. }, 0);
  21253. return;
  21254. }
  21255. // initial sources
  21256. this.changingSrc_ = true;
  21257. // Only update the cached source list if we are not retrying a new source after error,
  21258. // since in that case we want to include the failed source(s) in the cache
  21259. if (!isRetry) {
  21260. this.cache_.sources = sources;
  21261. }
  21262. this.updateSourceCaches_(sources[0]);
  21263. // middlewareSource is the source after it has been changed by middleware
  21264. setSource(this, sources[0], (middlewareSource, mws) => {
  21265. this.middleware_ = mws;
  21266. // since sourceSet is async we have to update the cache again after we select a source since
  21267. // the source that is selected could be out of order from the cache update above this callback.
  21268. if (!isRetry) {
  21269. this.cache_.sources = sources;
  21270. }
  21271. this.updateSourceCaches_(middlewareSource);
  21272. const err = this.src_(middlewareSource);
  21273. if (err) {
  21274. if (sources.length > 1) {
  21275. return this.handleSrc_(sources.slice(1));
  21276. }
  21277. this.changingSrc_ = false;
  21278. // We need to wrap this in a timeout to give folks a chance to add error event handlers
  21279. this.setTimeout(function () {
  21280. this.error({
  21281. code: 4,
  21282. message: this.options_.notSupportedMessage
  21283. });
  21284. }, 0);
  21285. // we could not find an appropriate tech, but let's still notify the delegate that this is it
  21286. // this needs a better comment about why this is needed
  21287. this.triggerReady();
  21288. return;
  21289. }
  21290. setTech(mws, this.tech_);
  21291. });
  21292. // Try another available source if this one fails before playback.
  21293. if (sources.length > 1) {
  21294. const retry = () => {
  21295. // Remove the error modal
  21296. this.error(null);
  21297. this.handleSrc_(sources.slice(1), true);
  21298. };
  21299. const stopListeningForErrors = () => {
  21300. this.off('error', retry);
  21301. };
  21302. this.one('error', retry);
  21303. this.one('playing', stopListeningForErrors);
  21304. this.resetRetryOnError_ = () => {
  21305. this.off('error', retry);
  21306. this.off('playing', stopListeningForErrors);
  21307. };
  21308. }
  21309. }
  21310. /**
  21311. * Get or set the video source.
  21312. *
  21313. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21314. * A SourceObject, an array of SourceObjects, or a string referencing
  21315. * a URL to a media source. It is _highly recommended_ that an object
  21316. * or array of objects is used here, so that source selection
  21317. * algorithms can take the `type` into account.
  21318. *
  21319. * If not provided, this method acts as a getter.
  21320. *
  21321. * @return {string|undefined}
  21322. * If the `source` argument is missing, returns the current source
  21323. * URL. Otherwise, returns nothing/undefined.
  21324. */
  21325. src(source) {
  21326. return this.handleSrc_(source, false);
  21327. }
  21328. /**
  21329. * Set the source object on the tech, returns a boolean that indicates whether
  21330. * there is a tech that can play the source or not
  21331. *
  21332. * @param {Tech~SourceObject} source
  21333. * The source object to set on the Tech
  21334. *
  21335. * @return {boolean}
  21336. * - True if there is no Tech to playback this source
  21337. * - False otherwise
  21338. *
  21339. * @private
  21340. */
  21341. src_(source) {
  21342. const sourceTech = this.selectSource([source]);
  21343. if (!sourceTech) {
  21344. return true;
  21345. }
  21346. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  21347. this.changingSrc_ = true;
  21348. // load this technology with the chosen source
  21349. this.loadTech_(sourceTech.tech, sourceTech.source);
  21350. this.tech_.ready(() => {
  21351. this.changingSrc_ = false;
  21352. });
  21353. return false;
  21354. }
  21355. // wait until the tech is ready to set the source
  21356. // and set it synchronously if possible (#2326)
  21357. this.ready(function () {
  21358. // The setSource tech method was added with source handlers
  21359. // so older techs won't support it
  21360. // We need to check the direct prototype for the case where subclasses
  21361. // of the tech do not support source handlers
  21362. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  21363. this.techCall_('setSource', source);
  21364. } else {
  21365. this.techCall_('src', source.src);
  21366. }
  21367. this.changingSrc_ = false;
  21368. }, true);
  21369. return false;
  21370. }
  21371. /**
  21372. * Begin loading the src data.
  21373. */
  21374. load() {
  21375. this.techCall_('load');
  21376. }
  21377. /**
  21378. * Reset the player. Loads the first tech in the techOrder,
  21379. * removes all the text tracks in the existing `tech`,
  21380. * and calls `reset` on the `tech`.
  21381. */
  21382. reset() {
  21383. if (this.paused()) {
  21384. this.doReset_();
  21385. } else {
  21386. const playPromise = this.play();
  21387. silencePromise(playPromise.then(() => this.doReset_()));
  21388. }
  21389. }
  21390. doReset_() {
  21391. if (this.tech_) {
  21392. this.tech_.clearTracks('text');
  21393. }
  21394. this.resetCache_();
  21395. this.poster('');
  21396. this.loadTech_(this.options_.techOrder[0], null);
  21397. this.techCall_('reset');
  21398. this.resetControlBarUI_();
  21399. if (isEvented(this)) {
  21400. this.trigger('playerreset');
  21401. }
  21402. }
  21403. /**
  21404. * Reset Control Bar's UI by calling sub-methods that reset
  21405. * all of Control Bar's components
  21406. */
  21407. resetControlBarUI_() {
  21408. this.resetProgressBar_();
  21409. this.resetPlaybackRate_();
  21410. this.resetVolumeBar_();
  21411. }
  21412. /**
  21413. * Reset tech's progress so progress bar is reset in the UI
  21414. */
  21415. resetProgressBar_() {
  21416. this.currentTime(0);
  21417. const {
  21418. currentTimeDisplay,
  21419. durationDisplay,
  21420. progressControl,
  21421. remainingTimeDisplay
  21422. } = this.controlBar || {};
  21423. const {
  21424. seekBar
  21425. } = progressControl || {};
  21426. if (currentTimeDisplay) {
  21427. currentTimeDisplay.updateContent();
  21428. }
  21429. if (durationDisplay) {
  21430. durationDisplay.updateContent();
  21431. }
  21432. if (remainingTimeDisplay) {
  21433. remainingTimeDisplay.updateContent();
  21434. }
  21435. if (seekBar) {
  21436. seekBar.update();
  21437. if (seekBar.loadProgressBar) {
  21438. seekBar.loadProgressBar.update();
  21439. }
  21440. }
  21441. }
  21442. /**
  21443. * Reset Playback ratio
  21444. */
  21445. resetPlaybackRate_() {
  21446. this.playbackRate(this.defaultPlaybackRate());
  21447. this.handleTechRateChange_();
  21448. }
  21449. /**
  21450. * Reset Volume bar
  21451. */
  21452. resetVolumeBar_() {
  21453. this.volume(1.0);
  21454. this.trigger('volumechange');
  21455. }
  21456. /**
  21457. * Returns all of the current source objects.
  21458. *
  21459. * @return {Tech~SourceObject[]}
  21460. * The current source objects
  21461. */
  21462. currentSources() {
  21463. const source = this.currentSource();
  21464. const sources = [];
  21465. // assume `{}` or `{ src }`
  21466. if (Object.keys(source).length !== 0) {
  21467. sources.push(source);
  21468. }
  21469. return this.cache_.sources || sources;
  21470. }
  21471. /**
  21472. * Returns the current source object.
  21473. *
  21474. * @return {Tech~SourceObject}
  21475. * The current source object
  21476. */
  21477. currentSource() {
  21478. return this.cache_.source || {};
  21479. }
  21480. /**
  21481. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  21482. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  21483. *
  21484. * @return {string}
  21485. * The current source
  21486. */
  21487. currentSrc() {
  21488. return this.currentSource() && this.currentSource().src || '';
  21489. }
  21490. /**
  21491. * Get the current source type e.g. video/mp4
  21492. * This can allow you rebuild the current source object so that you could load the same
  21493. * source and tech later
  21494. *
  21495. * @return {string}
  21496. * The source MIME type
  21497. */
  21498. currentType() {
  21499. return this.currentSource() && this.currentSource().type || '';
  21500. }
  21501. /**
  21502. * Get or set the preload attribute
  21503. *
  21504. * @param {boolean} [value]
  21505. * - true means that we should preload
  21506. * - false means that we should not preload
  21507. *
  21508. * @return {string}
  21509. * The preload attribute value when getting
  21510. */
  21511. preload(value) {
  21512. if (value !== undefined) {
  21513. this.techCall_('setPreload', value);
  21514. this.options_.preload = value;
  21515. return;
  21516. }
  21517. return this.techGet_('preload');
  21518. }
  21519. /**
  21520. * Get or set the autoplay option. When this is a boolean it will
  21521. * modify the attribute on the tech. When this is a string the attribute on
  21522. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  21523. *
  21524. * @param {boolean|string} [value]
  21525. * - true: autoplay using the browser behavior
  21526. * - false: do not autoplay
  21527. * - 'play': call play() on every loadstart
  21528. * - 'muted': call muted() then play() on every loadstart
  21529. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  21530. * - *: values other than those listed here will be set `autoplay` to true
  21531. *
  21532. * @return {boolean|string}
  21533. * The current value of autoplay when getting
  21534. */
  21535. autoplay(value) {
  21536. // getter usage
  21537. if (value === undefined) {
  21538. return this.options_.autoplay || false;
  21539. }
  21540. let techAutoplay;
  21541. // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  21542. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  21543. this.options_.autoplay = value;
  21544. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  21545. techAutoplay = false;
  21546. // any falsy value sets autoplay to false in the browser,
  21547. // lets do the same
  21548. } else if (!value) {
  21549. this.options_.autoplay = false;
  21550. // any other value (ie truthy) sets autoplay to true
  21551. } else {
  21552. this.options_.autoplay = true;
  21553. }
  21554. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay;
  21555. // if we don't have a tech then we do not queue up
  21556. // a setAutoplay call on tech ready. We do this because the
  21557. // autoplay option will be passed in the constructor and we
  21558. // do not need to set it twice
  21559. if (this.tech_) {
  21560. this.techCall_('setAutoplay', techAutoplay);
  21561. }
  21562. }
  21563. /**
  21564. * Set or unset the playsinline attribute.
  21565. * Playsinline tells the browser that non-fullscreen playback is preferred.
  21566. *
  21567. * @param {boolean} [value]
  21568. * - true means that we should try to play inline by default
  21569. * - false means that we should use the browser's default playback mode,
  21570. * which in most cases is inline. iOS Safari is a notable exception
  21571. * and plays fullscreen by default.
  21572. *
  21573. * @return {string|Player}
  21574. * - the current value of playsinline
  21575. * - the player when setting
  21576. *
  21577. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  21578. */
  21579. playsinline(value) {
  21580. if (value !== undefined) {
  21581. this.techCall_('setPlaysinline', value);
  21582. this.options_.playsinline = value;
  21583. return this;
  21584. }
  21585. return this.techGet_('playsinline');
  21586. }
  21587. /**
  21588. * Get or set the loop attribute on the video element.
  21589. *
  21590. * @param {boolean} [value]
  21591. * - true means that we should loop the video
  21592. * - false means that we should not loop the video
  21593. *
  21594. * @return {boolean}
  21595. * The current value of loop when getting
  21596. */
  21597. loop(value) {
  21598. if (value !== undefined) {
  21599. this.techCall_('setLoop', value);
  21600. this.options_.loop = value;
  21601. return;
  21602. }
  21603. return this.techGet_('loop');
  21604. }
  21605. /**
  21606. * Get or set the poster image source url
  21607. *
  21608. * @fires Player#posterchange
  21609. *
  21610. * @param {string} [src]
  21611. * Poster image source URL
  21612. *
  21613. * @return {string}
  21614. * The current value of poster when getting
  21615. */
  21616. poster(src) {
  21617. if (src === undefined) {
  21618. return this.poster_;
  21619. }
  21620. // The correct way to remove a poster is to set as an empty string
  21621. // other falsey values will throw errors
  21622. if (!src) {
  21623. src = '';
  21624. }
  21625. if (src === this.poster_) {
  21626. return;
  21627. }
  21628. // update the internal poster variable
  21629. this.poster_ = src;
  21630. // update the tech's poster
  21631. this.techCall_('setPoster', src);
  21632. this.isPosterFromTech_ = false;
  21633. // alert components that the poster has been set
  21634. /**
  21635. * This event fires when the poster image is changed on the player.
  21636. *
  21637. * @event Player#posterchange
  21638. * @type {Event}
  21639. */
  21640. this.trigger('posterchange');
  21641. }
  21642. /**
  21643. * Some techs (e.g. YouTube) can provide a poster source in an
  21644. * asynchronous way. We want the poster component to use this
  21645. * poster source so that it covers up the tech's controls.
  21646. * (YouTube's play button). However we only want to use this
  21647. * source if the player user hasn't set a poster through
  21648. * the normal APIs.
  21649. *
  21650. * @fires Player#posterchange
  21651. * @listens Tech#posterchange
  21652. * @private
  21653. */
  21654. handleTechPosterChange_() {
  21655. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  21656. const newPoster = this.tech_.poster() || '';
  21657. if (newPoster !== this.poster_) {
  21658. this.poster_ = newPoster;
  21659. this.isPosterFromTech_ = true;
  21660. // Let components know the poster has changed
  21661. this.trigger('posterchange');
  21662. }
  21663. }
  21664. }
  21665. /**
  21666. * Get or set whether or not the controls are showing.
  21667. *
  21668. * @fires Player#controlsenabled
  21669. *
  21670. * @param {boolean} [bool]
  21671. * - true to turn controls on
  21672. * - false to turn controls off
  21673. *
  21674. * @return {boolean}
  21675. * The current value of controls when getting
  21676. */
  21677. controls(bool) {
  21678. if (bool === undefined) {
  21679. return !!this.controls_;
  21680. }
  21681. bool = !!bool;
  21682. // Don't trigger a change event unless it actually changed
  21683. if (this.controls_ === bool) {
  21684. return;
  21685. }
  21686. this.controls_ = bool;
  21687. if (this.usingNativeControls()) {
  21688. this.techCall_('setControls', bool);
  21689. }
  21690. if (this.controls_) {
  21691. this.removeClass('vjs-controls-disabled');
  21692. this.addClass('vjs-controls-enabled');
  21693. /**
  21694. * @event Player#controlsenabled
  21695. * @type {Event}
  21696. */
  21697. this.trigger('controlsenabled');
  21698. if (!this.usingNativeControls()) {
  21699. this.addTechControlsListeners_();
  21700. }
  21701. } else {
  21702. this.removeClass('vjs-controls-enabled');
  21703. this.addClass('vjs-controls-disabled');
  21704. /**
  21705. * @event Player#controlsdisabled
  21706. * @type {Event}
  21707. */
  21708. this.trigger('controlsdisabled');
  21709. if (!this.usingNativeControls()) {
  21710. this.removeTechControlsListeners_();
  21711. }
  21712. }
  21713. }
  21714. /**
  21715. * Toggle native controls on/off. Native controls are the controls built into
  21716. * devices (e.g. default iPhone controls) or other techs
  21717. * (e.g. Vimeo Controls)
  21718. * **This should only be set by the current tech, because only the tech knows
  21719. * if it can support native controls**
  21720. *
  21721. * @fires Player#usingnativecontrols
  21722. * @fires Player#usingcustomcontrols
  21723. *
  21724. * @param {boolean} [bool]
  21725. * - true to turn native controls on
  21726. * - false to turn native controls off
  21727. *
  21728. * @return {boolean}
  21729. * The current value of native controls when getting
  21730. */
  21731. usingNativeControls(bool) {
  21732. if (bool === undefined) {
  21733. return !!this.usingNativeControls_;
  21734. }
  21735. bool = !!bool;
  21736. // Don't trigger a change event unless it actually changed
  21737. if (this.usingNativeControls_ === bool) {
  21738. return;
  21739. }
  21740. this.usingNativeControls_ = bool;
  21741. if (this.usingNativeControls_) {
  21742. this.addClass('vjs-using-native-controls');
  21743. /**
  21744. * player is using the native device controls
  21745. *
  21746. * @event Player#usingnativecontrols
  21747. * @type {Event}
  21748. */
  21749. this.trigger('usingnativecontrols');
  21750. } else {
  21751. this.removeClass('vjs-using-native-controls');
  21752. /**
  21753. * player is using the custom HTML controls
  21754. *
  21755. * @event Player#usingcustomcontrols
  21756. * @type {Event}
  21757. */
  21758. this.trigger('usingcustomcontrols');
  21759. }
  21760. }
  21761. /**
  21762. * Set or get the current MediaError
  21763. *
  21764. * @fires Player#error
  21765. *
  21766. * @param {MediaError|string|number} [err]
  21767. * A MediaError or a string/number to be turned
  21768. * into a MediaError
  21769. *
  21770. * @return {MediaError|null}
  21771. * The current MediaError when getting (or null)
  21772. */
  21773. error(err) {
  21774. if (err === undefined) {
  21775. return this.error_ || null;
  21776. }
  21777. // allow hooks to modify error object
  21778. hooks('beforeerror').forEach(hookFunction => {
  21779. const newErr = hookFunction(this, err);
  21780. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  21781. this.log.error('please return a value that MediaError expects in beforeerror hooks');
  21782. return;
  21783. }
  21784. err = newErr;
  21785. });
  21786. // Suppress the first error message for no compatible source until
  21787. // user interaction
  21788. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  21789. const triggerSuppressedError = function () {
  21790. this.error(err);
  21791. };
  21792. this.options_.suppressNotSupportedError = false;
  21793. this.any(['click', 'touchstart'], triggerSuppressedError);
  21794. this.one('loadstart', function () {
  21795. this.off(['click', 'touchstart'], triggerSuppressedError);
  21796. });
  21797. return;
  21798. }
  21799. // restoring to default
  21800. if (err === null) {
  21801. this.error_ = err;
  21802. this.removeClass('vjs-error');
  21803. if (this.errorDisplay) {
  21804. this.errorDisplay.close();
  21805. }
  21806. return;
  21807. }
  21808. this.error_ = new MediaError(err);
  21809. // add the vjs-error classname to the player
  21810. this.addClass('vjs-error');
  21811. // log the name of the error type and any message
  21812. // IE11 logs "[object object]" and required you to expand message to see error object
  21813. log$1.error(`(CODE:${this.error_.code} ${MediaError.errorTypes[this.error_.code]})`, this.error_.message, this.error_);
  21814. /**
  21815. * @event Player#error
  21816. * @type {Event}
  21817. */
  21818. this.trigger('error');
  21819. // notify hooks of the per player error
  21820. hooks('error').forEach(hookFunction => hookFunction(this, this.error_));
  21821. return;
  21822. }
  21823. /**
  21824. * Report user activity
  21825. *
  21826. * @param {Object} event
  21827. * Event object
  21828. */
  21829. reportUserActivity(event) {
  21830. this.userActivity_ = true;
  21831. }
  21832. /**
  21833. * Get/set if user is active
  21834. *
  21835. * @fires Player#useractive
  21836. * @fires Player#userinactive
  21837. *
  21838. * @param {boolean} [bool]
  21839. * - true if the user is active
  21840. * - false if the user is inactive
  21841. *
  21842. * @return {boolean}
  21843. * The current value of userActive when getting
  21844. */
  21845. userActive(bool) {
  21846. if (bool === undefined) {
  21847. return this.userActive_;
  21848. }
  21849. bool = !!bool;
  21850. if (bool === this.userActive_) {
  21851. return;
  21852. }
  21853. this.userActive_ = bool;
  21854. if (this.userActive_) {
  21855. this.userActivity_ = true;
  21856. this.removeClass('vjs-user-inactive');
  21857. this.addClass('vjs-user-active');
  21858. /**
  21859. * @event Player#useractive
  21860. * @type {Event}
  21861. */
  21862. this.trigger('useractive');
  21863. return;
  21864. }
  21865. // Chrome/Safari/IE have bugs where when you change the cursor it can
  21866. // trigger a mousemove event. This causes an issue when you're hiding
  21867. // the cursor when the user is inactive, and a mousemove signals user
  21868. // activity. Making it impossible to go into inactive mode. Specifically
  21869. // this happens in fullscreen when we really need to hide the cursor.
  21870. //
  21871. // When this gets resolved in ALL browsers it can be removed
  21872. // https://code.google.com/p/chromium/issues/detail?id=103041
  21873. if (this.tech_) {
  21874. this.tech_.one('mousemove', function (e) {
  21875. e.stopPropagation();
  21876. e.preventDefault();
  21877. });
  21878. }
  21879. this.userActivity_ = false;
  21880. this.removeClass('vjs-user-active');
  21881. this.addClass('vjs-user-inactive');
  21882. /**
  21883. * @event Player#userinactive
  21884. * @type {Event}
  21885. */
  21886. this.trigger('userinactive');
  21887. }
  21888. /**
  21889. * Listen for user activity based on timeout value
  21890. *
  21891. * @private
  21892. */
  21893. listenForUserActivity_() {
  21894. let mouseInProgress;
  21895. let lastMoveX;
  21896. let lastMoveY;
  21897. const handleActivity = bind_(this, this.reportUserActivity);
  21898. const handleMouseMove = function (e) {
  21899. // #1068 - Prevent mousemove spamming
  21900. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  21901. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  21902. lastMoveX = e.screenX;
  21903. lastMoveY = e.screenY;
  21904. handleActivity();
  21905. }
  21906. };
  21907. const handleMouseDown = function () {
  21908. handleActivity();
  21909. // For as long as the they are touching the device or have their mouse down,
  21910. // we consider them active even if they're not moving their finger or mouse.
  21911. // So we want to continue to update that they are active
  21912. this.clearInterval(mouseInProgress);
  21913. // Setting userActivity=true now and setting the interval to the same time
  21914. // as the activityCheck interval (250) should ensure we never miss the
  21915. // next activityCheck
  21916. mouseInProgress = this.setInterval(handleActivity, 250);
  21917. };
  21918. const handleMouseUpAndMouseLeave = function (event) {
  21919. handleActivity();
  21920. // Stop the interval that maintains activity if the mouse/touch is down
  21921. this.clearInterval(mouseInProgress);
  21922. };
  21923. // Any mouse movement will be considered user activity
  21924. this.on('mousedown', handleMouseDown);
  21925. this.on('mousemove', handleMouseMove);
  21926. this.on('mouseup', handleMouseUpAndMouseLeave);
  21927. this.on('mouseleave', handleMouseUpAndMouseLeave);
  21928. const controlBar = this.getChild('controlBar');
  21929. // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  21930. // controlBar would no longer be hidden by default timeout.
  21931. if (controlBar && !IS_IOS && !IS_ANDROID) {
  21932. controlBar.on('mouseenter', function (event) {
  21933. if (this.player().options_.inactivityTimeout !== 0) {
  21934. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  21935. }
  21936. this.player().options_.inactivityTimeout = 0;
  21937. });
  21938. controlBar.on('mouseleave', function (event) {
  21939. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  21940. });
  21941. }
  21942. // Listen for keyboard navigation
  21943. // Shouldn't need to use inProgress interval because of key repeat
  21944. this.on('keydown', handleActivity);
  21945. this.on('keyup', handleActivity);
  21946. // Run an interval every 250 milliseconds instead of stuffing everything into
  21947. // the mousemove/touchmove function itself, to prevent performance degradation.
  21948. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  21949. // then gets picked up by this loop
  21950. // http://ejohn.org/blog/learning-from-twitter/
  21951. let inactivityTimeout;
  21952. this.setInterval(function () {
  21953. // Check to see if mouse/touch activity has happened
  21954. if (!this.userActivity_) {
  21955. return;
  21956. }
  21957. // Reset the activity tracker
  21958. this.userActivity_ = false;
  21959. // If the user state was inactive, set the state to active
  21960. this.userActive(true);
  21961. // Clear any existing inactivity timeout to start the timer over
  21962. this.clearTimeout(inactivityTimeout);
  21963. const timeout = this.options_.inactivityTimeout;
  21964. if (timeout <= 0) {
  21965. return;
  21966. }
  21967. // In <timeout> milliseconds, if no more activity has occurred the
  21968. // user will be considered inactive
  21969. inactivityTimeout = this.setTimeout(function () {
  21970. // Protect against the case where the inactivityTimeout can trigger just
  21971. // before the next user activity is picked up by the activity check loop
  21972. // causing a flicker
  21973. if (!this.userActivity_) {
  21974. this.userActive(false);
  21975. }
  21976. }, timeout);
  21977. }, 250);
  21978. }
  21979. /**
  21980. * Gets or sets the current playback rate. A playback rate of
  21981. * 1.0 represents normal speed and 0.5 would indicate half-speed
  21982. * playback, for instance.
  21983. *
  21984. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  21985. *
  21986. * @param {number} [rate]
  21987. * New playback rate to set.
  21988. *
  21989. * @return {number}
  21990. * The current playback rate when getting or 1.0
  21991. */
  21992. playbackRate(rate) {
  21993. if (rate !== undefined) {
  21994. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  21995. // that is registered above
  21996. this.techCall_('setPlaybackRate', rate);
  21997. return;
  21998. }
  21999. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22000. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  22001. }
  22002. return 1.0;
  22003. }
  22004. /**
  22005. * Gets or sets the current default playback rate. A default playback rate of
  22006. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  22007. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  22008. * not the current playbackRate.
  22009. *
  22010. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  22011. *
  22012. * @param {number} [rate]
  22013. * New default playback rate to set.
  22014. *
  22015. * @return {number|Player}
  22016. * - The default playback rate when getting or 1.0
  22017. * - the player when setting
  22018. */
  22019. defaultPlaybackRate(rate) {
  22020. if (rate !== undefined) {
  22021. return this.techCall_('setDefaultPlaybackRate', rate);
  22022. }
  22023. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22024. return this.techGet_('defaultPlaybackRate');
  22025. }
  22026. return 1.0;
  22027. }
  22028. /**
  22029. * Gets or sets the audio flag
  22030. *
  22031. * @param {boolean} bool
  22032. * - true signals that this is an audio player
  22033. * - false signals that this is not an audio player
  22034. *
  22035. * @return {boolean}
  22036. * The current value of isAudio when getting
  22037. */
  22038. isAudio(bool) {
  22039. if (bool !== undefined) {
  22040. this.isAudio_ = !!bool;
  22041. return;
  22042. }
  22043. return !!this.isAudio_;
  22044. }
  22045. enableAudioOnlyUI_() {
  22046. // Update styling immediately to show the control bar so we can get its height
  22047. this.addClass('vjs-audio-only-mode');
  22048. const playerChildren = this.children();
  22049. const controlBar = this.getChild('ControlBar');
  22050. const controlBarHeight = controlBar && controlBar.currentHeight();
  22051. // Hide all player components except the control bar. Control bar components
  22052. // needed only for video are hidden with CSS
  22053. playerChildren.forEach(child => {
  22054. if (child === controlBar) {
  22055. return;
  22056. }
  22057. if (child.el_ && !child.hasClass('vjs-hidden')) {
  22058. child.hide();
  22059. this.audioOnlyCache_.hiddenChildren.push(child);
  22060. }
  22061. });
  22062. this.audioOnlyCache_.playerHeight = this.currentHeight();
  22063. // Set the player height the same as the control bar
  22064. this.height(controlBarHeight);
  22065. this.trigger('audioonlymodechange');
  22066. }
  22067. disableAudioOnlyUI_() {
  22068. this.removeClass('vjs-audio-only-mode');
  22069. // Show player components that were previously hidden
  22070. this.audioOnlyCache_.hiddenChildren.forEach(child => child.show());
  22071. // Reset player height
  22072. this.height(this.audioOnlyCache_.playerHeight);
  22073. this.trigger('audioonlymodechange');
  22074. }
  22075. /**
  22076. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  22077. *
  22078. * Setting this to `true` will hide all player components except the control bar,
  22079. * as well as control bar components needed only for video.
  22080. *
  22081. * @param {boolean} [value]
  22082. * The value to set audioOnlyMode to.
  22083. *
  22084. * @return {Promise|boolean}
  22085. * A Promise is returned when setting the state, and a boolean when getting
  22086. * the present state
  22087. */
  22088. audioOnlyMode(value) {
  22089. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  22090. return this.audioOnlyMode_;
  22091. }
  22092. this.audioOnlyMode_ = value;
  22093. // Enable Audio Only Mode
  22094. if (value) {
  22095. const exitPromises = [];
  22096. // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  22097. if (this.isInPictureInPicture()) {
  22098. exitPromises.push(this.exitPictureInPicture());
  22099. }
  22100. if (this.isFullscreen()) {
  22101. exitPromises.push(this.exitFullscreen());
  22102. }
  22103. if (this.audioPosterMode()) {
  22104. exitPromises.push(this.audioPosterMode(false));
  22105. }
  22106. return Promise.all(exitPromises).then(() => this.enableAudioOnlyUI_());
  22107. }
  22108. // Disable Audio Only Mode
  22109. return Promise.resolve().then(() => this.disableAudioOnlyUI_());
  22110. }
  22111. enablePosterModeUI_() {
  22112. // Hide the video element and show the poster image to enable posterModeUI
  22113. const tech = this.tech_ && this.tech_;
  22114. tech.hide();
  22115. this.addClass('vjs-audio-poster-mode');
  22116. this.trigger('audiopostermodechange');
  22117. }
  22118. disablePosterModeUI_() {
  22119. // Show the video element and hide the poster image to disable posterModeUI
  22120. const tech = this.tech_ && this.tech_;
  22121. tech.show();
  22122. this.removeClass('vjs-audio-poster-mode');
  22123. this.trigger('audiopostermodechange');
  22124. }
  22125. /**
  22126. * Get the current audioPosterMode state or set audioPosterMode to true or false
  22127. *
  22128. * @param {boolean} [value]
  22129. * The value to set audioPosterMode to.
  22130. *
  22131. * @return {Promise|boolean}
  22132. * A Promise is returned when setting the state, and a boolean when getting
  22133. * the present state
  22134. */
  22135. audioPosterMode(value) {
  22136. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  22137. return this.audioPosterMode_;
  22138. }
  22139. this.audioPosterMode_ = value;
  22140. if (value) {
  22141. if (this.audioOnlyMode()) {
  22142. const audioOnlyModePromise = this.audioOnlyMode(false);
  22143. return audioOnlyModePromise.then(() => {
  22144. // enable audio poster mode after audio only mode is disabled
  22145. this.enablePosterModeUI_();
  22146. });
  22147. }
  22148. return Promise.resolve().then(() => {
  22149. // enable audio poster mode
  22150. this.enablePosterModeUI_();
  22151. });
  22152. }
  22153. return Promise.resolve().then(() => {
  22154. // disable audio poster mode
  22155. this.disablePosterModeUI_();
  22156. });
  22157. }
  22158. /**
  22159. * A helper method for adding a {@link TextTrack} to our
  22160. * {@link TextTrackList}.
  22161. *
  22162. * In addition to the W3C settings we allow adding additional info through options.
  22163. *
  22164. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  22165. *
  22166. * @param {string} [kind]
  22167. * the kind of TextTrack you are adding
  22168. *
  22169. * @param {string} [label]
  22170. * the label to give the TextTrack label
  22171. *
  22172. * @param {string} [language]
  22173. * the language to set on the TextTrack
  22174. *
  22175. * @return {TextTrack|undefined}
  22176. * the TextTrack that was added or undefined
  22177. * if there is no tech
  22178. */
  22179. addTextTrack(kind, label, language) {
  22180. if (this.tech_) {
  22181. return this.tech_.addTextTrack(kind, label, language);
  22182. }
  22183. }
  22184. /**
  22185. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  22186. *
  22187. * @param {Object} options
  22188. * Options to pass to {@link HTMLTrackElement} during creation. See
  22189. * {@link HTMLTrackElement} for object properties that you should use.
  22190. *
  22191. * @param {boolean} [manualCleanup=false] if set to true, the TextTrack will not be removed
  22192. * from the TextTrackList and HtmlTrackElementList
  22193. * after a source change
  22194. *
  22195. * @return { import('./tracks/html-track-element').default }
  22196. * the HTMLTrackElement that was created and added
  22197. * to the HtmlTrackElementList and the remote
  22198. * TextTrackList
  22199. *
  22200. */
  22201. addRemoteTextTrack(options, manualCleanup) {
  22202. if (this.tech_) {
  22203. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  22204. }
  22205. }
  22206. /**
  22207. * Remove a remote {@link TextTrack} from the respective
  22208. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  22209. *
  22210. * @param {Object} track
  22211. * Remote {@link TextTrack} to remove
  22212. *
  22213. * @return {undefined}
  22214. * does not return anything
  22215. */
  22216. removeRemoteTextTrack(obj = {}) {
  22217. let {
  22218. track
  22219. } = obj;
  22220. if (!track) {
  22221. track = obj;
  22222. }
  22223. // destructure the input into an object with a track argument, defaulting to arguments[0]
  22224. // default the whole argument to an empty object if nothing was passed in
  22225. if (this.tech_) {
  22226. return this.tech_.removeRemoteTextTrack(track);
  22227. }
  22228. }
  22229. /**
  22230. * Gets available media playback quality metrics as specified by the W3C's Media
  22231. * Playback Quality API.
  22232. *
  22233. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  22234. *
  22235. * @return {Object|undefined}
  22236. * An object with supported media playback quality metrics or undefined if there
  22237. * is no tech or the tech does not support it.
  22238. */
  22239. getVideoPlaybackQuality() {
  22240. return this.techGet_('getVideoPlaybackQuality');
  22241. }
  22242. /**
  22243. * Get video width
  22244. *
  22245. * @return {number}
  22246. * current video width
  22247. */
  22248. videoWidth() {
  22249. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  22250. }
  22251. /**
  22252. * Get video height
  22253. *
  22254. * @return {number}
  22255. * current video height
  22256. */
  22257. videoHeight() {
  22258. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  22259. }
  22260. /**
  22261. * The player's language code.
  22262. *
  22263. * Changing the language will trigger
  22264. * [languagechange]{@link Player#event:languagechange}
  22265. * which Components can use to update control text.
  22266. * ClickableComponent will update its control text by default on
  22267. * [languagechange]{@link Player#event:languagechange}.
  22268. *
  22269. * @fires Player#languagechange
  22270. *
  22271. * @param {string} [code]
  22272. * the language code to set the player to
  22273. *
  22274. * @return {string}
  22275. * The current language code when getting
  22276. */
  22277. language(code) {
  22278. if (code === undefined) {
  22279. return this.language_;
  22280. }
  22281. if (this.language_ !== String(code).toLowerCase()) {
  22282. this.language_ = String(code).toLowerCase();
  22283. // during first init, it's possible some things won't be evented
  22284. if (isEvented(this)) {
  22285. /**
  22286. * fires when the player language change
  22287. *
  22288. * @event Player#languagechange
  22289. * @type {Event}
  22290. */
  22291. this.trigger('languagechange');
  22292. }
  22293. }
  22294. }
  22295. /**
  22296. * Get the player's language dictionary
  22297. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  22298. * Languages specified directly in the player options have precedence
  22299. *
  22300. * @return {Array}
  22301. * An array of of supported languages
  22302. */
  22303. languages() {
  22304. return merge$1(Player.prototype.options_.languages, this.languages_);
  22305. }
  22306. /**
  22307. * returns a JavaScript object representing the current track
  22308. * information. **DOES not return it as JSON**
  22309. *
  22310. * @return {Object}
  22311. * Object representing the current of track info
  22312. */
  22313. toJSON() {
  22314. const options = merge$1(this.options_);
  22315. const tracks = options.tracks;
  22316. options.tracks = [];
  22317. for (let i = 0; i < tracks.length; i++) {
  22318. let track = tracks[i];
  22319. // deep merge tracks and null out player so no circular references
  22320. track = merge$1(track);
  22321. track.player = undefined;
  22322. options.tracks[i] = track;
  22323. }
  22324. return options;
  22325. }
  22326. /**
  22327. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  22328. * component) that immediately overlays the player with arbitrary
  22329. * content and removes itself when closed.
  22330. *
  22331. * @param {string|Function|Element|Array|null} content
  22332. * Same as {@link ModalDialog#content}'s param of the same name.
  22333. * The most straight-forward usage is to provide a string or DOM
  22334. * element.
  22335. *
  22336. * @param {Object} [options]
  22337. * Extra options which will be passed on to the {@link ModalDialog}.
  22338. *
  22339. * @return {ModalDialog}
  22340. * the {@link ModalDialog} that was created
  22341. */
  22342. createModal(content, options) {
  22343. options = options || {};
  22344. options.content = content || '';
  22345. const modal = new ModalDialog(this, options);
  22346. this.addChild(modal);
  22347. modal.on('dispose', () => {
  22348. this.removeChild(modal);
  22349. });
  22350. modal.open();
  22351. return modal;
  22352. }
  22353. /**
  22354. * Change breakpoint classes when the player resizes.
  22355. *
  22356. * @private
  22357. */
  22358. updateCurrentBreakpoint_() {
  22359. if (!this.responsive()) {
  22360. return;
  22361. }
  22362. const currentBreakpoint = this.currentBreakpoint();
  22363. const currentWidth = this.currentWidth();
  22364. for (let i = 0; i < BREAKPOINT_ORDER.length; i++) {
  22365. const candidateBreakpoint = BREAKPOINT_ORDER[i];
  22366. const maxWidth = this.breakpoints_[candidateBreakpoint];
  22367. if (currentWidth <= maxWidth) {
  22368. // The current breakpoint did not change, nothing to do.
  22369. if (currentBreakpoint === candidateBreakpoint) {
  22370. return;
  22371. }
  22372. // Only remove a class if there is a current breakpoint.
  22373. if (currentBreakpoint) {
  22374. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  22375. }
  22376. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  22377. this.breakpoint_ = candidateBreakpoint;
  22378. break;
  22379. }
  22380. }
  22381. }
  22382. /**
  22383. * Removes the current breakpoint.
  22384. *
  22385. * @private
  22386. */
  22387. removeCurrentBreakpoint_() {
  22388. const className = this.currentBreakpointClass();
  22389. this.breakpoint_ = '';
  22390. if (className) {
  22391. this.removeClass(className);
  22392. }
  22393. }
  22394. /**
  22395. * Get or set breakpoints on the player.
  22396. *
  22397. * Calling this method with an object or `true` will remove any previous
  22398. * custom breakpoints and start from the defaults again.
  22399. *
  22400. * @param {Object|boolean} [breakpoints]
  22401. * If an object is given, it can be used to provide custom
  22402. * breakpoints. If `true` is given, will set default breakpoints.
  22403. * If this argument is not given, will simply return the current
  22404. * breakpoints.
  22405. *
  22406. * @param {number} [breakpoints.tiny]
  22407. * The maximum width for the "vjs-layout-tiny" class.
  22408. *
  22409. * @param {number} [breakpoints.xsmall]
  22410. * The maximum width for the "vjs-layout-x-small" class.
  22411. *
  22412. * @param {number} [breakpoints.small]
  22413. * The maximum width for the "vjs-layout-small" class.
  22414. *
  22415. * @param {number} [breakpoints.medium]
  22416. * The maximum width for the "vjs-layout-medium" class.
  22417. *
  22418. * @param {number} [breakpoints.large]
  22419. * The maximum width for the "vjs-layout-large" class.
  22420. *
  22421. * @param {number} [breakpoints.xlarge]
  22422. * The maximum width for the "vjs-layout-x-large" class.
  22423. *
  22424. * @param {number} [breakpoints.huge]
  22425. * The maximum width for the "vjs-layout-huge" class.
  22426. *
  22427. * @return {Object}
  22428. * An object mapping breakpoint names to maximum width values.
  22429. */
  22430. breakpoints(breakpoints) {
  22431. // Used as a getter.
  22432. if (breakpoints === undefined) {
  22433. return Object.assign(this.breakpoints_);
  22434. }
  22435. this.breakpoint_ = '';
  22436. this.breakpoints_ = Object.assign({}, DEFAULT_BREAKPOINTS, breakpoints);
  22437. // When breakpoint definitions change, we need to update the currently
  22438. // selected breakpoint.
  22439. this.updateCurrentBreakpoint_();
  22440. // Clone the breakpoints before returning.
  22441. return Object.assign(this.breakpoints_);
  22442. }
  22443. /**
  22444. * Get or set a flag indicating whether or not this player should adjust
  22445. * its UI based on its dimensions.
  22446. *
  22447. * @param {boolean} value
  22448. * Should be `true` if the player should adjust its UI based on its
  22449. * dimensions; otherwise, should be `false`.
  22450. *
  22451. * @return {boolean}
  22452. * Will be `true` if this player should adjust its UI based on its
  22453. * dimensions; otherwise, will be `false`.
  22454. */
  22455. responsive(value) {
  22456. // Used as a getter.
  22457. if (value === undefined) {
  22458. return this.responsive_;
  22459. }
  22460. value = Boolean(value);
  22461. const current = this.responsive_;
  22462. // Nothing changed.
  22463. if (value === current) {
  22464. return;
  22465. }
  22466. // The value actually changed, set it.
  22467. this.responsive_ = value;
  22468. // Start listening for breakpoints and set the initial breakpoint if the
  22469. // player is now responsive.
  22470. if (value) {
  22471. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  22472. this.updateCurrentBreakpoint_();
  22473. // Stop listening for breakpoints if the player is no longer responsive.
  22474. } else {
  22475. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  22476. this.removeCurrentBreakpoint_();
  22477. }
  22478. return value;
  22479. }
  22480. /**
  22481. * Get current breakpoint name, if any.
  22482. *
  22483. * @return {string}
  22484. * If there is currently a breakpoint set, returns a the key from the
  22485. * breakpoints object matching it. Otherwise, returns an empty string.
  22486. */
  22487. currentBreakpoint() {
  22488. return this.breakpoint_;
  22489. }
  22490. /**
  22491. * Get the current breakpoint class name.
  22492. *
  22493. * @return {string}
  22494. * The matching class name (e.g. `"vjs-layout-tiny"` or
  22495. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  22496. * there is no current breakpoint.
  22497. */
  22498. currentBreakpointClass() {
  22499. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  22500. }
  22501. /**
  22502. * An object that describes a single piece of media.
  22503. *
  22504. * Properties that are not part of this type description will be retained; so,
  22505. * this can be viewed as a generic metadata storage mechanism as well.
  22506. *
  22507. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  22508. * @typedef {Object} Player~MediaObject
  22509. *
  22510. * @property {string} [album]
  22511. * Unused, except if this object is passed to the `MediaSession`
  22512. * API.
  22513. *
  22514. * @property {string} [artist]
  22515. * Unused, except if this object is passed to the `MediaSession`
  22516. * API.
  22517. *
  22518. * @property {Object[]} [artwork]
  22519. * Unused, except if this object is passed to the `MediaSession`
  22520. * API. If not specified, will be populated via the `poster`, if
  22521. * available.
  22522. *
  22523. * @property {string} [poster]
  22524. * URL to an image that will display before playback.
  22525. *
  22526. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  22527. * A single source object, an array of source objects, or a string
  22528. * referencing a URL to a media source. It is _highly recommended_
  22529. * that an object or array of objects is used here, so that source
  22530. * selection algorithms can take the `type` into account.
  22531. *
  22532. * @property {string} [title]
  22533. * Unused, except if this object is passed to the `MediaSession`
  22534. * API.
  22535. *
  22536. * @property {Object[]} [textTracks]
  22537. * An array of objects to be used to create text tracks, following
  22538. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  22539. * For ease of removal, these will be created as "remote" text
  22540. * tracks and set to automatically clean up on source changes.
  22541. *
  22542. * These objects may have properties like `src`, `kind`, `label`,
  22543. * and `language`, see {@link Tech#createRemoteTextTrack}.
  22544. */
  22545. /**
  22546. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  22547. *
  22548. * @param {Player~MediaObject} media
  22549. * A media object.
  22550. *
  22551. * @param {Function} ready
  22552. * A callback to be called when the player is ready.
  22553. */
  22554. loadMedia(media, ready) {
  22555. if (!media || typeof media !== 'object') {
  22556. return;
  22557. }
  22558. this.reset();
  22559. // Clone the media object so it cannot be mutated from outside.
  22560. this.cache_.media = merge$1(media);
  22561. const {
  22562. artist,
  22563. artwork,
  22564. description,
  22565. poster,
  22566. src,
  22567. textTracks,
  22568. title
  22569. } = this.cache_.media;
  22570. // If `artwork` is not given, create it using `poster`.
  22571. if (!artwork && poster) {
  22572. this.cache_.media.artwork = [{
  22573. src: poster,
  22574. type: getMimetype(poster)
  22575. }];
  22576. }
  22577. if (src) {
  22578. this.src(src);
  22579. }
  22580. if (poster) {
  22581. this.poster(poster);
  22582. }
  22583. if (Array.isArray(textTracks)) {
  22584. textTracks.forEach(tt => this.addRemoteTextTrack(tt, false));
  22585. }
  22586. if (this.titleBar) {
  22587. this.titleBar.update({
  22588. title,
  22589. description: description || artist || ''
  22590. });
  22591. }
  22592. this.ready(ready);
  22593. }
  22594. /**
  22595. * Get a clone of the current {@link Player~MediaObject} for this player.
  22596. *
  22597. * If the `loadMedia` method has not been used, will attempt to return a
  22598. * {@link Player~MediaObject} based on the current state of the player.
  22599. *
  22600. * @return {Player~MediaObject}
  22601. */
  22602. getMedia() {
  22603. if (!this.cache_.media) {
  22604. const poster = this.poster();
  22605. const src = this.currentSources();
  22606. const textTracks = Array.prototype.map.call(this.remoteTextTracks(), tt => ({
  22607. kind: tt.kind,
  22608. label: tt.label,
  22609. language: tt.language,
  22610. src: tt.src
  22611. }));
  22612. const media = {
  22613. src,
  22614. textTracks
  22615. };
  22616. if (poster) {
  22617. media.poster = poster;
  22618. media.artwork = [{
  22619. src: media.poster,
  22620. type: getMimetype(media.poster)
  22621. }];
  22622. }
  22623. return media;
  22624. }
  22625. return merge$1(this.cache_.media);
  22626. }
  22627. /**
  22628. * Gets tag settings
  22629. *
  22630. * @param {Element} tag
  22631. * The player tag
  22632. *
  22633. * @return {Object}
  22634. * An object containing all of the settings
  22635. * for a player tag
  22636. */
  22637. static getTagSettings(tag) {
  22638. const baseOptions = {
  22639. sources: [],
  22640. tracks: []
  22641. };
  22642. const tagOptions = getAttributes(tag);
  22643. const dataSetup = tagOptions['data-setup'];
  22644. if (hasClass(tag, 'vjs-fill')) {
  22645. tagOptions.fill = true;
  22646. }
  22647. if (hasClass(tag, 'vjs-fluid')) {
  22648. tagOptions.fluid = true;
  22649. }
  22650. // Check if data-setup attr exists.
  22651. if (dataSetup !== null) {
  22652. // Parse options JSON
  22653. // If empty string, make it a parsable json object.
  22654. const [err, data] = safeParseTuple__default["default"](dataSetup || '{}');
  22655. if (err) {
  22656. log$1.error(err);
  22657. }
  22658. Object.assign(tagOptions, data);
  22659. }
  22660. Object.assign(baseOptions, tagOptions);
  22661. // Get tag children settings
  22662. if (tag.hasChildNodes()) {
  22663. const children = tag.childNodes;
  22664. for (let i = 0, j = children.length; i < j; i++) {
  22665. const child = children[i];
  22666. // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  22667. const childName = child.nodeName.toLowerCase();
  22668. if (childName === 'source') {
  22669. baseOptions.sources.push(getAttributes(child));
  22670. } else if (childName === 'track') {
  22671. baseOptions.tracks.push(getAttributes(child));
  22672. }
  22673. }
  22674. }
  22675. return baseOptions;
  22676. }
  22677. /**
  22678. * Set debug mode to enable/disable logs at info level.
  22679. *
  22680. * @param {boolean} enabled
  22681. * @fires Player#debugon
  22682. * @fires Player#debugoff
  22683. */
  22684. debug(enabled) {
  22685. if (enabled === undefined) {
  22686. return this.debugEnabled_;
  22687. }
  22688. if (enabled) {
  22689. this.trigger('debugon');
  22690. this.previousLogLevel_ = this.log.level;
  22691. this.log.level('debug');
  22692. this.debugEnabled_ = true;
  22693. } else {
  22694. this.trigger('debugoff');
  22695. this.log.level(this.previousLogLevel_);
  22696. this.previousLogLevel_ = undefined;
  22697. this.debugEnabled_ = false;
  22698. }
  22699. }
  22700. /**
  22701. * Set or get current playback rates.
  22702. * Takes an array and updates the playback rates menu with the new items.
  22703. * Pass in an empty array to hide the menu.
  22704. * Values other than arrays are ignored.
  22705. *
  22706. * @fires Player#playbackrateschange
  22707. * @param {number[]} newRates
  22708. * The new rates that the playback rates menu should update to.
  22709. * An empty array will hide the menu
  22710. * @return {number[]} When used as a getter will return the current playback rates
  22711. */
  22712. playbackRates(newRates) {
  22713. if (newRates === undefined) {
  22714. return this.cache_.playbackRates;
  22715. }
  22716. // ignore any value that isn't an array
  22717. if (!Array.isArray(newRates)) {
  22718. return;
  22719. }
  22720. // ignore any arrays that don't only contain numbers
  22721. if (!newRates.every(rate => typeof rate === 'number')) {
  22722. return;
  22723. }
  22724. this.cache_.playbackRates = newRates;
  22725. /**
  22726. * fires when the playback rates in a player are changed
  22727. *
  22728. * @event Player#playbackrateschange
  22729. * @type {Event}
  22730. */
  22731. this.trigger('playbackrateschange');
  22732. }
  22733. }
  22734. /**
  22735. * Get the {@link VideoTrackList}
  22736. *
  22737. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  22738. *
  22739. * @return {VideoTrackList}
  22740. * the current video track list
  22741. *
  22742. * @method Player.prototype.videoTracks
  22743. */
  22744. /**
  22745. * Get the {@link AudioTrackList}
  22746. *
  22747. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  22748. *
  22749. * @return {AudioTrackList}
  22750. * the current audio track list
  22751. *
  22752. * @method Player.prototype.audioTracks
  22753. */
  22754. /**
  22755. * Get the {@link TextTrackList}
  22756. *
  22757. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  22758. *
  22759. * @return {TextTrackList}
  22760. * the current text track list
  22761. *
  22762. * @method Player.prototype.textTracks
  22763. */
  22764. /**
  22765. * Get the remote {@link TextTrackList}
  22766. *
  22767. * @return {TextTrackList}
  22768. * The current remote text track list
  22769. *
  22770. * @method Player.prototype.remoteTextTracks
  22771. */
  22772. /**
  22773. * Get the remote {@link HtmlTrackElementList} tracks.
  22774. *
  22775. * @return {HtmlTrackElementList}
  22776. * The current remote text track element list
  22777. *
  22778. * @method Player.prototype.remoteTextTrackEls
  22779. */
  22780. ALL.names.forEach(function (name) {
  22781. const props = ALL[name];
  22782. Player.prototype[props.getterName] = function () {
  22783. if (this.tech_) {
  22784. return this.tech_[props.getterName]();
  22785. }
  22786. // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  22787. // these will be passed to the tech during loading
  22788. this[props.privateName] = this[props.privateName] || new props.ListClass();
  22789. return this[props.privateName];
  22790. };
  22791. });
  22792. /**
  22793. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  22794. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  22795. * behavior.
  22796. *
  22797. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  22798. *
  22799. * @param {string} [value]
  22800. * The value to set the `Player`'s crossorigin to. If an argument is
  22801. * given, must be one of `anonymous` or `use-credentials`.
  22802. *
  22803. * @return {string|undefined}
  22804. * - The current crossorigin value of the `Player` when getting.
  22805. * - undefined when setting
  22806. */
  22807. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  22808. /**
  22809. * Global enumeration of players.
  22810. *
  22811. * The keys are the player IDs and the values are either the {@link Player}
  22812. * instance or `null` for disposed players.
  22813. *
  22814. * @type {Object}
  22815. */
  22816. Player.players = {};
  22817. const navigator = window__default["default"].navigator;
  22818. /*
  22819. * Player instance options, surfaced using options
  22820. * options = Player.prototype.options_
  22821. * Make changes in options, not here.
  22822. *
  22823. * @type {Object}
  22824. * @private
  22825. */
  22826. Player.prototype.options_ = {
  22827. // Default order of fallback technology
  22828. techOrder: Tech.defaultTechOrder_,
  22829. html5: {},
  22830. // enable sourceset by default
  22831. enableSourceset: true,
  22832. // default inactivity timeout
  22833. inactivityTimeout: 2000,
  22834. // default playback rates
  22835. playbackRates: [],
  22836. // Add playback rate selection by adding rates
  22837. // 'playbackRates': [0.5, 1, 1.5, 2],
  22838. liveui: false,
  22839. // Included control sets
  22840. children: ['mediaLoader', 'posterImage', 'titleBar', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  22841. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  22842. // locales and their language translations
  22843. languages: {},
  22844. // Default message to show when a video cannot be played.
  22845. notSupportedMessage: 'No compatible source was found for this media.',
  22846. normalizeAutoplay: false,
  22847. fullscreen: {
  22848. options: {
  22849. navigationUI: 'hide'
  22850. }
  22851. },
  22852. breakpoints: {},
  22853. responsive: false,
  22854. audioOnlyMode: false,
  22855. audioPosterMode: false
  22856. };
  22857. [
  22858. /**
  22859. * Returns whether or not the player is in the "ended" state.
  22860. *
  22861. * @return {Boolean} True if the player is in the ended state, false if not.
  22862. * @method Player#ended
  22863. */
  22864. 'ended',
  22865. /**
  22866. * Returns whether or not the player is in the "seeking" state.
  22867. *
  22868. * @return {Boolean} True if the player is in the seeking state, false if not.
  22869. * @method Player#seeking
  22870. */
  22871. 'seeking',
  22872. /**
  22873. * Returns the TimeRanges of the media that are currently available
  22874. * for seeking to.
  22875. *
  22876. * @return {TimeRanges} the seekable intervals of the media timeline
  22877. * @method Player#seekable
  22878. */
  22879. 'seekable',
  22880. /**
  22881. * Returns the current state of network activity for the element, from
  22882. * the codes in the list below.
  22883. * - NETWORK_EMPTY (numeric value 0)
  22884. * The element has not yet been initialised. All attributes are in
  22885. * their initial states.
  22886. * - NETWORK_IDLE (numeric value 1)
  22887. * The element's resource selection algorithm is active and has
  22888. * selected a resource, but it is not actually using the network at
  22889. * this time.
  22890. * - NETWORK_LOADING (numeric value 2)
  22891. * The user agent is actively trying to download data.
  22892. * - NETWORK_NO_SOURCE (numeric value 3)
  22893. * The element's resource selection algorithm is active, but it has
  22894. * not yet found a resource to use.
  22895. *
  22896. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  22897. * @return {number} the current network activity state
  22898. * @method Player#networkState
  22899. */
  22900. 'networkState',
  22901. /**
  22902. * Returns a value that expresses the current state of the element
  22903. * with respect to rendering the current playback position, from the
  22904. * codes in the list below.
  22905. * - HAVE_NOTHING (numeric value 0)
  22906. * No information regarding the media resource is available.
  22907. * - HAVE_METADATA (numeric value 1)
  22908. * Enough of the resource has been obtained that the duration of the
  22909. * resource is available.
  22910. * - HAVE_CURRENT_DATA (numeric value 2)
  22911. * Data for the immediate current playback position is available.
  22912. * - HAVE_FUTURE_DATA (numeric value 3)
  22913. * Data for the immediate current playback position is available, as
  22914. * well as enough data for the user agent to advance the current
  22915. * playback position in the direction of playback.
  22916. * - HAVE_ENOUGH_DATA (numeric value 4)
  22917. * The user agent estimates that enough data is available for
  22918. * playback to proceed uninterrupted.
  22919. *
  22920. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  22921. * @return {number} the current playback rendering state
  22922. * @method Player#readyState
  22923. */
  22924. 'readyState'].forEach(function (fn) {
  22925. Player.prototype[fn] = function () {
  22926. return this.techGet_(fn);
  22927. };
  22928. });
  22929. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  22930. Player.prototype[`handleTech${toTitleCase$1(event)}_`] = function () {
  22931. return this.trigger(event);
  22932. };
  22933. });
  22934. /**
  22935. * Fired when the player has initial duration and dimension information
  22936. *
  22937. * @event Player#loadedmetadata
  22938. * @type {Event}
  22939. */
  22940. /**
  22941. * Fired when the player has downloaded data at the current playback position
  22942. *
  22943. * @event Player#loadeddata
  22944. * @type {Event}
  22945. */
  22946. /**
  22947. * Fired when the current playback position has changed *
  22948. * During playback this is fired every 15-250 milliseconds, depending on the
  22949. * playback technology in use.
  22950. *
  22951. * @event Player#timeupdate
  22952. * @type {Event}
  22953. */
  22954. /**
  22955. * Fired when the volume changes
  22956. *
  22957. * @event Player#volumechange
  22958. * @type {Event}
  22959. */
  22960. /**
  22961. * Reports whether or not a player has a plugin available.
  22962. *
  22963. * This does not report whether or not the plugin has ever been initialized
  22964. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  22965. *
  22966. * @method Player#hasPlugin
  22967. * @param {string} name
  22968. * The name of a plugin.
  22969. *
  22970. * @return {boolean}
  22971. * Whether or not this player has the requested plugin available.
  22972. */
  22973. /**
  22974. * Reports whether or not a player is using a plugin by name.
  22975. *
  22976. * For basic plugins, this only reports whether the plugin has _ever_ been
  22977. * initialized on this player.
  22978. *
  22979. * @method Player#usingPlugin
  22980. * @param {string} name
  22981. * The name of a plugin.
  22982. *
  22983. * @return {boolean}
  22984. * Whether or not this player is using the requested plugin.
  22985. */
  22986. Component$1.registerComponent('Player', Player);
  22987. /**
  22988. * @file plugin.js
  22989. */
  22990. /**
  22991. * The base plugin name.
  22992. *
  22993. * @private
  22994. * @constant
  22995. * @type {string}
  22996. */
  22997. const BASE_PLUGIN_NAME = 'plugin';
  22998. /**
  22999. * The key on which a player's active plugins cache is stored.
  23000. *
  23001. * @private
  23002. * @constant
  23003. * @type {string}
  23004. */
  23005. const PLUGIN_CACHE_KEY = 'activePlugins_';
  23006. /**
  23007. * Stores registered plugins in a private space.
  23008. *
  23009. * @private
  23010. * @type {Object}
  23011. */
  23012. const pluginStorage = {};
  23013. /**
  23014. * Reports whether or not a plugin has been registered.
  23015. *
  23016. * @private
  23017. * @param {string} name
  23018. * The name of a plugin.
  23019. *
  23020. * @return {boolean}
  23021. * Whether or not the plugin has been registered.
  23022. */
  23023. const pluginExists = name => pluginStorage.hasOwnProperty(name);
  23024. /**
  23025. * Get a single registered plugin by name.
  23026. *
  23027. * @private
  23028. * @param {string} name
  23029. * The name of a plugin.
  23030. *
  23031. * @return {typeof Plugin|Function|undefined}
  23032. * The plugin (or undefined).
  23033. */
  23034. const getPlugin = name => pluginExists(name) ? pluginStorage[name] : undefined;
  23035. /**
  23036. * Marks a plugin as "active" on a player.
  23037. *
  23038. * Also, ensures that the player has an object for tracking active plugins.
  23039. *
  23040. * @private
  23041. * @param {Player} player
  23042. * A Video.js player instance.
  23043. *
  23044. * @param {string} name
  23045. * The name of a plugin.
  23046. */
  23047. const markPluginAsActive = (player, name) => {
  23048. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  23049. player[PLUGIN_CACHE_KEY][name] = true;
  23050. };
  23051. /**
  23052. * Triggers a pair of plugin setup events.
  23053. *
  23054. * @private
  23055. * @param {Player} player
  23056. * A Video.js player instance.
  23057. *
  23058. * @param {Plugin~PluginEventHash} hash
  23059. * A plugin event hash.
  23060. *
  23061. * @param {boolean} [before]
  23062. * If true, prefixes the event name with "before". In other words,
  23063. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  23064. */
  23065. const triggerSetupEvent = (player, hash, before) => {
  23066. const eventName = (before ? 'before' : '') + 'pluginsetup';
  23067. player.trigger(eventName, hash);
  23068. player.trigger(eventName + ':' + hash.name, hash);
  23069. };
  23070. /**
  23071. * Takes a basic plugin function and returns a wrapper function which marks
  23072. * on the player that the plugin has been activated.
  23073. *
  23074. * @private
  23075. * @param {string} name
  23076. * The name of the plugin.
  23077. *
  23078. * @param {Function} plugin
  23079. * The basic plugin.
  23080. *
  23081. * @return {Function}
  23082. * A wrapper function for the given plugin.
  23083. */
  23084. const createBasicPlugin = function (name, plugin) {
  23085. const basicPluginWrapper = function () {
  23086. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  23087. // regardless, but we want the hash to be consistent with the hash provided
  23088. // for advanced plugins.
  23089. //
  23090. // The only potentially counter-intuitive thing here is the `instance` in
  23091. // the "pluginsetup" event is the value returned by the `plugin` function.
  23092. triggerSetupEvent(this, {
  23093. name,
  23094. plugin,
  23095. instance: null
  23096. }, true);
  23097. const instance = plugin.apply(this, arguments);
  23098. markPluginAsActive(this, name);
  23099. triggerSetupEvent(this, {
  23100. name,
  23101. plugin,
  23102. instance
  23103. });
  23104. return instance;
  23105. };
  23106. Object.keys(plugin).forEach(function (prop) {
  23107. basicPluginWrapper[prop] = plugin[prop];
  23108. });
  23109. return basicPluginWrapper;
  23110. };
  23111. /**
  23112. * Takes a plugin sub-class and returns a factory function for generating
  23113. * instances of it.
  23114. *
  23115. * This factory function will replace itself with an instance of the requested
  23116. * sub-class of Plugin.
  23117. *
  23118. * @private
  23119. * @param {string} name
  23120. * The name of the plugin.
  23121. *
  23122. * @param {Plugin} PluginSubClass
  23123. * The advanced plugin.
  23124. *
  23125. * @return {Function}
  23126. */
  23127. const createPluginFactory = (name, PluginSubClass) => {
  23128. // Add a `name` property to the plugin prototype so that each plugin can
  23129. // refer to itself by name.
  23130. PluginSubClass.prototype.name = name;
  23131. return function (...args) {
  23132. triggerSetupEvent(this, {
  23133. name,
  23134. plugin: PluginSubClass,
  23135. instance: null
  23136. }, true);
  23137. const instance = new PluginSubClass(...[this, ...args]);
  23138. // The plugin is replaced by a function that returns the current instance.
  23139. this[name] = () => instance;
  23140. triggerSetupEvent(this, instance.getEventHash());
  23141. return instance;
  23142. };
  23143. };
  23144. /**
  23145. * Parent class for all advanced plugins.
  23146. *
  23147. * @mixes module:evented~EventedMixin
  23148. * @mixes module:stateful~StatefulMixin
  23149. * @fires Player#beforepluginsetup
  23150. * @fires Player#beforepluginsetup:$name
  23151. * @fires Player#pluginsetup
  23152. * @fires Player#pluginsetup:$name
  23153. * @listens Player#dispose
  23154. * @throws {Error}
  23155. * If attempting to instantiate the base {@link Plugin} class
  23156. * directly instead of via a sub-class.
  23157. */
  23158. class Plugin {
  23159. /**
  23160. * Creates an instance of this class.
  23161. *
  23162. * Sub-classes should call `super` to ensure plugins are properly initialized.
  23163. *
  23164. * @param {Player} player
  23165. * A Video.js player instance.
  23166. */
  23167. constructor(player) {
  23168. if (this.constructor === Plugin) {
  23169. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  23170. }
  23171. this.player = player;
  23172. if (!this.log) {
  23173. this.log = this.player.log.createLogger(this.name);
  23174. }
  23175. // Make this object evented, but remove the added `trigger` method so we
  23176. // use the prototype version instead.
  23177. evented(this);
  23178. delete this.trigger;
  23179. stateful(this, this.constructor.defaultState);
  23180. markPluginAsActive(player, this.name);
  23181. // Auto-bind the dispose method so we can use it as a listener and unbind
  23182. // it later easily.
  23183. this.dispose = this.dispose.bind(this);
  23184. // If the player is disposed, dispose the plugin.
  23185. player.on('dispose', this.dispose);
  23186. }
  23187. /**
  23188. * Get the version of the plugin that was set on <pluginName>.VERSION
  23189. */
  23190. version() {
  23191. return this.constructor.VERSION;
  23192. }
  23193. /**
  23194. * Each event triggered by plugins includes a hash of additional data with
  23195. * conventional properties.
  23196. *
  23197. * This returns that object or mutates an existing hash.
  23198. *
  23199. * @param {Object} [hash={}]
  23200. * An object to be used as event an event hash.
  23201. *
  23202. * @return {Plugin~PluginEventHash}
  23203. * An event hash object with provided properties mixed-in.
  23204. */
  23205. getEventHash(hash = {}) {
  23206. hash.name = this.name;
  23207. hash.plugin = this.constructor;
  23208. hash.instance = this;
  23209. return hash;
  23210. }
  23211. /**
  23212. * Triggers an event on the plugin object and overrides
  23213. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  23214. *
  23215. * @param {string|Object} event
  23216. * An event type or an object with a type property.
  23217. *
  23218. * @param {Object} [hash={}]
  23219. * Additional data hash to merge with a
  23220. * {@link Plugin~PluginEventHash|PluginEventHash}.
  23221. *
  23222. * @return {boolean}
  23223. * Whether or not default was prevented.
  23224. */
  23225. trigger(event, hash = {}) {
  23226. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  23227. }
  23228. /**
  23229. * Handles "statechanged" events on the plugin. No-op by default, override by
  23230. * subclassing.
  23231. *
  23232. * @abstract
  23233. * @param {Event} e
  23234. * An event object provided by a "statechanged" event.
  23235. *
  23236. * @param {Object} e.changes
  23237. * An object describing changes that occurred with the "statechanged"
  23238. * event.
  23239. */
  23240. handleStateChanged(e) {}
  23241. /**
  23242. * Disposes a plugin.
  23243. *
  23244. * Subclasses can override this if they want, but for the sake of safety,
  23245. * it's probably best to subscribe the "dispose" event.
  23246. *
  23247. * @fires Plugin#dispose
  23248. */
  23249. dispose() {
  23250. const {
  23251. name,
  23252. player
  23253. } = this;
  23254. /**
  23255. * Signals that a advanced plugin is about to be disposed.
  23256. *
  23257. * @event Plugin#dispose
  23258. * @type {Event}
  23259. */
  23260. this.trigger('dispose');
  23261. this.off();
  23262. player.off('dispose', this.dispose);
  23263. // Eliminate any possible sources of leaking memory by clearing up
  23264. // references between the player and the plugin instance and nulling out
  23265. // the plugin's state and replacing methods with a function that throws.
  23266. player[PLUGIN_CACHE_KEY][name] = false;
  23267. this.player = this.state = null;
  23268. // Finally, replace the plugin name on the player with a new factory
  23269. // function, so that the plugin is ready to be set up again.
  23270. player[name] = createPluginFactory(name, pluginStorage[name]);
  23271. }
  23272. /**
  23273. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  23274. *
  23275. * @param {string|Function} plugin
  23276. * If a string, matches the name of a plugin. If a function, will be
  23277. * tested directly.
  23278. *
  23279. * @return {boolean}
  23280. * Whether or not a plugin is a basic plugin.
  23281. */
  23282. static isBasic(plugin) {
  23283. const p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  23284. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  23285. }
  23286. /**
  23287. * Register a Video.js plugin.
  23288. *
  23289. * @param {string} name
  23290. * The name of the plugin to be registered. Must be a string and
  23291. * must not match an existing plugin or a method on the `Player`
  23292. * prototype.
  23293. *
  23294. * @param {typeof Plugin|Function} plugin
  23295. * A sub-class of `Plugin` or a function for basic plugins.
  23296. *
  23297. * @return {typeof Plugin|Function}
  23298. * For advanced plugins, a factory function for that plugin. For
  23299. * basic plugins, a wrapper function that initializes the plugin.
  23300. */
  23301. static registerPlugin(name, plugin) {
  23302. if (typeof name !== 'string') {
  23303. throw new Error(`Illegal plugin name, "${name}", must be a string, was ${typeof name}.`);
  23304. }
  23305. if (pluginExists(name)) {
  23306. log$1.warn(`A plugin named "${name}" already exists. You may want to avoid re-registering plugins!`);
  23307. } else if (Player.prototype.hasOwnProperty(name)) {
  23308. throw new Error(`Illegal plugin name, "${name}", cannot share a name with an existing player method!`);
  23309. }
  23310. if (typeof plugin !== 'function') {
  23311. throw new Error(`Illegal plugin for "${name}", must be a function, was ${typeof plugin}.`);
  23312. }
  23313. pluginStorage[name] = plugin;
  23314. // Add a player prototype method for all sub-classed plugins (but not for
  23315. // the base Plugin class).
  23316. if (name !== BASE_PLUGIN_NAME) {
  23317. if (Plugin.isBasic(plugin)) {
  23318. Player.prototype[name] = createBasicPlugin(name, plugin);
  23319. } else {
  23320. Player.prototype[name] = createPluginFactory(name, plugin);
  23321. }
  23322. }
  23323. return plugin;
  23324. }
  23325. /**
  23326. * De-register a Video.js plugin.
  23327. *
  23328. * @param {string} name
  23329. * The name of the plugin to be de-registered. Must be a string that
  23330. * matches an existing plugin.
  23331. *
  23332. * @throws {Error}
  23333. * If an attempt is made to de-register the base plugin.
  23334. */
  23335. static deregisterPlugin(name) {
  23336. if (name === BASE_PLUGIN_NAME) {
  23337. throw new Error('Cannot de-register base plugin.');
  23338. }
  23339. if (pluginExists(name)) {
  23340. delete pluginStorage[name];
  23341. delete Player.prototype[name];
  23342. }
  23343. }
  23344. /**
  23345. * Gets an object containing multiple Video.js plugins.
  23346. *
  23347. * @param {Array} [names]
  23348. * If provided, should be an array of plugin names. Defaults to _all_
  23349. * plugin names.
  23350. *
  23351. * @return {Object|undefined}
  23352. * An object containing plugin(s) associated with their name(s) or
  23353. * `undefined` if no matching plugins exist).
  23354. */
  23355. static getPlugins(names = Object.keys(pluginStorage)) {
  23356. let result;
  23357. names.forEach(name => {
  23358. const plugin = getPlugin(name);
  23359. if (plugin) {
  23360. result = result || {};
  23361. result[name] = plugin;
  23362. }
  23363. });
  23364. return result;
  23365. }
  23366. /**
  23367. * Gets a plugin's version, if available
  23368. *
  23369. * @param {string} name
  23370. * The name of a plugin.
  23371. *
  23372. * @return {string}
  23373. * The plugin's version or an empty string.
  23374. */
  23375. static getPluginVersion(name) {
  23376. const plugin = getPlugin(name);
  23377. return plugin && plugin.VERSION || '';
  23378. }
  23379. }
  23380. /**
  23381. * Gets a plugin by name if it exists.
  23382. *
  23383. * @static
  23384. * @method getPlugin
  23385. * @memberOf Plugin
  23386. * @param {string} name
  23387. * The name of a plugin.
  23388. *
  23389. * @returns {typeof Plugin|Function|undefined}
  23390. * The plugin (or `undefined`).
  23391. */
  23392. Plugin.getPlugin = getPlugin;
  23393. /**
  23394. * The name of the base plugin class as it is registered.
  23395. *
  23396. * @type {string}
  23397. */
  23398. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  23399. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  23400. /**
  23401. * Documented in player.js
  23402. *
  23403. * @ignore
  23404. */
  23405. Player.prototype.usingPlugin = function (name) {
  23406. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  23407. };
  23408. /**
  23409. * Documented in player.js
  23410. *
  23411. * @ignore
  23412. */
  23413. Player.prototype.hasPlugin = function (name) {
  23414. return !!pluginExists(name);
  23415. };
  23416. /**
  23417. * Signals that a plugin is about to be set up on a player.
  23418. *
  23419. * @event Player#beforepluginsetup
  23420. * @type {Plugin~PluginEventHash}
  23421. */
  23422. /**
  23423. * Signals that a plugin is about to be set up on a player - by name. The name
  23424. * is the name of the plugin.
  23425. *
  23426. * @event Player#beforepluginsetup:$name
  23427. * @type {Plugin~PluginEventHash}
  23428. */
  23429. /**
  23430. * Signals that a plugin has just been set up on a player.
  23431. *
  23432. * @event Player#pluginsetup
  23433. * @type {Plugin~PluginEventHash}
  23434. */
  23435. /**
  23436. * Signals that a plugin has just been set up on a player - by name. The name
  23437. * is the name of the plugin.
  23438. *
  23439. * @event Player#pluginsetup:$name
  23440. * @type {Plugin~PluginEventHash}
  23441. */
  23442. /**
  23443. * @typedef {Object} Plugin~PluginEventHash
  23444. *
  23445. * @property {string} instance
  23446. * For basic plugins, the return value of the plugin function. For
  23447. * advanced plugins, the plugin instance on which the event is fired.
  23448. *
  23449. * @property {string} name
  23450. * The name of the plugin.
  23451. *
  23452. * @property {string} plugin
  23453. * For basic plugins, the plugin function. For advanced plugins, the
  23454. * plugin class/constructor.
  23455. */
  23456. /**
  23457. * @file deprecate.js
  23458. * @module deprecate
  23459. */
  23460. /**
  23461. * Decorate a function with a deprecation message the first time it is called.
  23462. *
  23463. * @param {string} message
  23464. * A deprecation message to log the first time the returned function
  23465. * is called.
  23466. *
  23467. * @param {Function} fn
  23468. * The function to be deprecated.
  23469. *
  23470. * @return {Function}
  23471. * A wrapper function that will log a deprecation warning the first
  23472. * time it is called. The return value will be the return value of
  23473. * the wrapped function.
  23474. */
  23475. function deprecate(message, fn) {
  23476. let warned = false;
  23477. return function (...args) {
  23478. if (!warned) {
  23479. log$1.warn(message);
  23480. }
  23481. warned = true;
  23482. return fn.apply(this, args);
  23483. };
  23484. }
  23485. /**
  23486. * Internal function used to mark a function as deprecated in the next major
  23487. * version with consistent messaging.
  23488. *
  23489. * @param {number} major The major version where it will be removed
  23490. * @param {string} oldName The old function name
  23491. * @param {string} newName The new function name
  23492. * @param {Function} fn The function to deprecate
  23493. * @return {Function} The decorated function
  23494. */
  23495. function deprecateForMajor(major, oldName, newName, fn) {
  23496. return deprecate(`${oldName} is deprecated and will be removed in ${major}.0; please use ${newName} instead.`, fn);
  23497. }
  23498. /**
  23499. * @file video.js
  23500. * @module videojs
  23501. */
  23502. /**
  23503. * Normalize an `id` value by trimming off a leading `#`
  23504. *
  23505. * @private
  23506. * @param {string} id
  23507. * A string, maybe with a leading `#`.
  23508. *
  23509. * @return {string}
  23510. * The string, without any leading `#`.
  23511. */
  23512. const normalizeId = id => id.indexOf('#') === 0 ? id.slice(1) : id;
  23513. /**
  23514. * A callback that is called when a component is ready. Does not have any
  23515. * parameters and any callback value will be ignored. See: {@link Component~ReadyCallback}
  23516. *
  23517. * @callback ReadyCallback
  23518. */
  23519. /**
  23520. * The `videojs()` function doubles as the main function for users to create a
  23521. * {@link Player} instance as well as the main library namespace.
  23522. *
  23523. * It can also be used as a getter for a pre-existing {@link Player} instance.
  23524. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  23525. * purpose because it avoids any potential for unintended initialization.
  23526. *
  23527. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  23528. * of our JSDoc template, we cannot properly document this as both a function
  23529. * and a namespace, so its function signature is documented here.
  23530. *
  23531. * #### Arguments
  23532. * ##### id
  23533. * string|Element, **required**
  23534. *
  23535. * Video element or video element ID.
  23536. *
  23537. * ##### options
  23538. * Object, optional
  23539. *
  23540. * Options object for providing settings.
  23541. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23542. *
  23543. * ##### ready
  23544. * {@link Component~ReadyCallback}, optional
  23545. *
  23546. * A function to be called when the {@link Player} and {@link Tech} are ready.
  23547. *
  23548. * #### Return Value
  23549. *
  23550. * The `videojs()` function returns a {@link Player} instance.
  23551. *
  23552. * @namespace
  23553. *
  23554. * @borrows AudioTrack as AudioTrack
  23555. * @borrows Component.getComponent as getComponent
  23556. * @borrows module:events.on as on
  23557. * @borrows module:events.one as one
  23558. * @borrows module:events.off as off
  23559. * @borrows module:events.trigger as trigger
  23560. * @borrows EventTarget as EventTarget
  23561. * @borrows module:middleware.use as use
  23562. * @borrows Player.players as players
  23563. * @borrows Plugin.registerPlugin as registerPlugin
  23564. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  23565. * @borrows Plugin.getPlugins as getPlugins
  23566. * @borrows Plugin.getPlugin as getPlugin
  23567. * @borrows Plugin.getPluginVersion as getPluginVersion
  23568. * @borrows Tech.getTech as getTech
  23569. * @borrows Tech.registerTech as registerTech
  23570. * @borrows TextTrack as TextTrack
  23571. * @borrows VideoTrack as VideoTrack
  23572. *
  23573. * @param {string|Element} id
  23574. * Video element or video element ID.
  23575. *
  23576. * @param {Object} [options]
  23577. * Options object for providing settings.
  23578. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  23579. *
  23580. * @param {ReadyCallback} [ready]
  23581. * A function to be called when the {@link Player} and {@link Tech} are
  23582. * ready.
  23583. *
  23584. * @return {Player}
  23585. * The `videojs()` function returns a {@link Player|Player} instance.
  23586. */
  23587. function videojs(id, options, ready) {
  23588. let player = videojs.getPlayer(id);
  23589. if (player) {
  23590. if (options) {
  23591. log$1.warn(`Player "${id}" is already initialised. Options will not be applied.`);
  23592. }
  23593. if (ready) {
  23594. player.ready(ready);
  23595. }
  23596. return player;
  23597. }
  23598. const el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  23599. if (!isEl(el)) {
  23600. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  23601. }
  23602. // document.body.contains(el) will only check if el is contained within that one document.
  23603. // This causes problems for elements in iframes.
  23604. // Instead, use the element's ownerDocument instead of the global document.
  23605. // This will make sure that the element is indeed in the dom of that document.
  23606. // Additionally, check that the document in question has a default view.
  23607. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  23608. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  23609. log$1.warn('The element supplied is not included in the DOM');
  23610. }
  23611. options = options || {};
  23612. // Store a copy of the el before modification, if it is to be restored in destroy()
  23613. // If div ingest, store the parent div
  23614. if (options.restoreEl === true) {
  23615. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  23616. }
  23617. hooks('beforesetup').forEach(hookFunction => {
  23618. const opts = hookFunction(el, merge$1(options));
  23619. if (!isObject(opts) || Array.isArray(opts)) {
  23620. log$1.error('please return an object in beforesetup hooks');
  23621. return;
  23622. }
  23623. options = merge$1(options, opts);
  23624. });
  23625. // We get the current "Player" component here in case an integration has
  23626. // replaced it with a custom player.
  23627. const PlayerComponent = Component$1.getComponent('Player');
  23628. player = new PlayerComponent(el, options, ready);
  23629. hooks('setup').forEach(hookFunction => hookFunction(player));
  23630. return player;
  23631. }
  23632. videojs.hooks_ = hooks_;
  23633. videojs.hooks = hooks;
  23634. videojs.hook = hook;
  23635. videojs.hookOnce = hookOnce;
  23636. videojs.removeHook = removeHook;
  23637. // Add default styles
  23638. if (window__default["default"].VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  23639. let style = $('.vjs-styles-defaults');
  23640. if (!style) {
  23641. style = createStyleElement('vjs-styles-defaults');
  23642. const head = $('head');
  23643. if (head) {
  23644. head.insertBefore(style, head.firstChild);
  23645. }
  23646. setTextContent(style, `
  23647. .video-js {
  23648. width: 300px;
  23649. height: 150px;
  23650. }
  23651. .vjs-fluid:not(.vjs-audio-only-mode) {
  23652. padding-top: 56.25%
  23653. }
  23654. `);
  23655. }
  23656. }
  23657. // Run Auto-load players
  23658. // You have to wait at least once in case this script is loaded after your
  23659. // video in the DOM (weird behavior only with minified version)
  23660. autoSetupTimeout(1, videojs);
  23661. /**
  23662. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  23663. *
  23664. * @type {string}
  23665. */
  23666. videojs.VERSION = version$6;
  23667. /**
  23668. * The global options object. These are the settings that take effect
  23669. * if no overrides are specified when the player is created.
  23670. *
  23671. * @type {Object}
  23672. */
  23673. videojs.options = Player.prototype.options_;
  23674. /**
  23675. * Get an object with the currently created players, keyed by player ID
  23676. *
  23677. * @return {Object}
  23678. * The created players
  23679. */
  23680. videojs.getPlayers = () => Player.players;
  23681. /**
  23682. * Get a single player based on an ID or DOM element.
  23683. *
  23684. * This is useful if you want to check if an element or ID has an associated
  23685. * Video.js player, but not create one if it doesn't.
  23686. *
  23687. * @param {string|Element} id
  23688. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  23689. * or a string matching the `id` of such an element.
  23690. *
  23691. * @return {Player|undefined}
  23692. * A player instance or `undefined` if there is no player instance
  23693. * matching the argument.
  23694. */
  23695. videojs.getPlayer = id => {
  23696. const players = Player.players;
  23697. let tag;
  23698. if (typeof id === 'string') {
  23699. const nId = normalizeId(id);
  23700. const player = players[nId];
  23701. if (player) {
  23702. return player;
  23703. }
  23704. tag = $('#' + nId);
  23705. } else {
  23706. tag = id;
  23707. }
  23708. if (isEl(tag)) {
  23709. const {
  23710. player,
  23711. playerId
  23712. } = tag;
  23713. // Element may have a `player` property referring to an already created
  23714. // player instance. If so, return that.
  23715. if (player || players[playerId]) {
  23716. return player || players[playerId];
  23717. }
  23718. }
  23719. };
  23720. /**
  23721. * Returns an array of all current players.
  23722. *
  23723. * @return {Array}
  23724. * An array of all players. The array will be in the order that
  23725. * `Object.keys` provides, which could potentially vary between
  23726. * JavaScript engines.
  23727. *
  23728. */
  23729. videojs.getAllPlayers = () =>
  23730. // Disposed players leave a key with a `null` value, so we need to make sure
  23731. // we filter those out.
  23732. Object.keys(Player.players).map(k => Player.players[k]).filter(Boolean);
  23733. videojs.players = Player.players;
  23734. videojs.getComponent = Component$1.getComponent;
  23735. /**
  23736. * Register a component so it can referred to by name. Used when adding to other
  23737. * components, either through addChild `component.addChild('myComponent')` or through
  23738. * default children options `{ children: ['myComponent'] }`.
  23739. *
  23740. * > NOTE: You could also just initialize the component before adding.
  23741. * `component.addChild(new MyComponent());`
  23742. *
  23743. * @param {string} name
  23744. * The class name of the component
  23745. *
  23746. * @param {Component} comp
  23747. * The component class
  23748. *
  23749. * @return {Component}
  23750. * The newly registered component
  23751. */
  23752. videojs.registerComponent = (name, comp) => {
  23753. if (Tech.isTech(comp)) {
  23754. log$1.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  23755. }
  23756. Component$1.registerComponent.call(Component$1, name, comp);
  23757. };
  23758. videojs.getTech = Tech.getTech;
  23759. videojs.registerTech = Tech.registerTech;
  23760. videojs.use = use;
  23761. /**
  23762. * An object that can be returned by a middleware to signify
  23763. * that the middleware is being terminated.
  23764. *
  23765. * @type {object}
  23766. * @property {object} middleware.TERMINATOR
  23767. */
  23768. Object.defineProperty(videojs, 'middleware', {
  23769. value: {},
  23770. writeable: false,
  23771. enumerable: true
  23772. });
  23773. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  23774. value: TERMINATOR,
  23775. writeable: false,
  23776. enumerable: true
  23777. });
  23778. /**
  23779. * A reference to the {@link module:browser|browser utility module} as an object.
  23780. *
  23781. * @type {Object}
  23782. * @see {@link module:browser|browser}
  23783. */
  23784. videojs.browser = browser;
  23785. /**
  23786. * A reference to the {@link module:obj|obj utility module} as an object.
  23787. *
  23788. * @type {Object}
  23789. * @see {@link module:obj|obj}
  23790. */
  23791. videojs.obj = Obj;
  23792. /**
  23793. * Deprecated reference to the {@link module:obj.merge|merge function}
  23794. *
  23795. * @type {Function}
  23796. * @see {@link module:obj.merge|merge}
  23797. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.merge instead.
  23798. */
  23799. videojs.mergeOptions = deprecateForMajor(9, 'videojs.mergeOptions', 'videojs.obj.merge', merge$1);
  23800. /**
  23801. * Deprecated reference to the {@link module:obj.defineLazyProperty|defineLazyProperty function}
  23802. *
  23803. * @type {Function}
  23804. * @see {@link module:obj.defineLazyProperty|defineLazyProperty}
  23805. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.obj.defineLazyProperty instead.
  23806. */
  23807. videojs.defineLazyProperty = deprecateForMajor(9, 'videojs.defineLazyProperty', 'videojs.obj.defineLazyProperty', defineLazyProperty);
  23808. /**
  23809. * Deprecated reference to the {@link module:fn.bind_|fn.bind_ function}
  23810. *
  23811. * @type {Function}
  23812. * @see {@link module:fn.bind_|fn.bind_}
  23813. * @deprecated Deprecated and will be removed in 9.0. Please use native Function.prototype.bind instead.
  23814. */
  23815. videojs.bind = deprecateForMajor(9, 'videojs.bind', 'native Function.prototype.bind', bind_);
  23816. videojs.registerPlugin = Plugin.registerPlugin;
  23817. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  23818. /**
  23819. * Deprecated method to register a plugin with Video.js
  23820. *
  23821. * @deprecated Deprecated and will be removed in 9.0. Use videojs.registerPlugin() instead.
  23822. *
  23823. * @param {string} name
  23824. * The plugin name
  23825. *
  23826. * @param {Plugin|Function} plugin
  23827. * The plugin sub-class or function
  23828. */
  23829. videojs.plugin = (name, plugin) => {
  23830. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  23831. return Plugin.registerPlugin(name, plugin);
  23832. };
  23833. videojs.getPlugins = Plugin.getPlugins;
  23834. videojs.getPlugin = Plugin.getPlugin;
  23835. videojs.getPluginVersion = Plugin.getPluginVersion;
  23836. /**
  23837. * Adding languages so that they're available to all players.
  23838. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  23839. *
  23840. * @param {string} code
  23841. * The language code or dictionary property
  23842. *
  23843. * @param {Object} data
  23844. * The data values to be translated
  23845. *
  23846. * @return {Object}
  23847. * The resulting language dictionary object
  23848. */
  23849. videojs.addLanguage = function (code, data) {
  23850. code = ('' + code).toLowerCase();
  23851. videojs.options.languages = merge$1(videojs.options.languages, {
  23852. [code]: data
  23853. });
  23854. return videojs.options.languages[code];
  23855. };
  23856. /**
  23857. * A reference to the {@link module:log|log utility module} as an object.
  23858. *
  23859. * @type {Function}
  23860. * @see {@link module:log|log}
  23861. */
  23862. videojs.log = log$1;
  23863. videojs.createLogger = createLogger;
  23864. /**
  23865. * A reference to the {@link module:time|time utility module} as an object.
  23866. *
  23867. * @type {Object}
  23868. * @see {@link module:time|time}
  23869. */
  23870. videojs.time = Time;
  23871. /**
  23872. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23873. *
  23874. * @type {Function}
  23875. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23876. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23877. */
  23878. videojs.createTimeRange = deprecateForMajor(9, 'videojs.createTimeRange', 'videojs.time.createTimeRanges', createTimeRanges$1);
  23879. /**
  23880. * Deprecated reference to the {@link module:time.createTimeRanges|createTimeRanges function}
  23881. *
  23882. * @type {Function}
  23883. * @see {@link module:time.createTimeRanges|createTimeRanges}
  23884. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.createTimeRanges instead.
  23885. */
  23886. videojs.createTimeRanges = deprecateForMajor(9, 'videojs.createTimeRanges', 'videojs.time.createTimeRanges', createTimeRanges$1);
  23887. /**
  23888. * Deprecated reference to the {@link module:time.formatTime|formatTime function}
  23889. *
  23890. * @type {Function}
  23891. * @see {@link module:time.formatTime|formatTime}
  23892. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.format instead.
  23893. */
  23894. videojs.formatTime = deprecateForMajor(9, 'videojs.formatTime', 'videojs.time.formatTime', formatTime);
  23895. /**
  23896. * Deprecated reference to the {@link module:time.setFormatTime|setFormatTime function}
  23897. *
  23898. * @type {Function}
  23899. * @see {@link module:time.setFormatTime|setFormatTime}
  23900. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.setFormat instead.
  23901. */
  23902. videojs.setFormatTime = deprecateForMajor(9, 'videojs.setFormatTime', 'videojs.time.setFormatTime', setFormatTime);
  23903. /**
  23904. * Deprecated reference to the {@link module:time.resetFormatTime|resetFormatTime function}
  23905. *
  23906. * @type {Function}
  23907. * @see {@link module:time.resetFormatTime|resetFormatTime}
  23908. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.time.resetFormat instead.
  23909. */
  23910. videojs.resetFormatTime = deprecateForMajor(9, 'videojs.resetFormatTime', 'videojs.time.resetFormatTime', resetFormatTime);
  23911. /**
  23912. * Deprecated reference to the {@link module:url.parseUrl|Url.parseUrl function}
  23913. *
  23914. * @type {Function}
  23915. * @see {@link module:url.parseUrl|parseUrl}
  23916. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.parseUrl instead.
  23917. */
  23918. videojs.parseUrl = deprecateForMajor(9, 'videojs.parseUrl', 'videojs.url.parseUrl', parseUrl);
  23919. /**
  23920. * Deprecated reference to the {@link module:url.isCrossOrigin|Url.isCrossOrigin function}
  23921. *
  23922. * @type {Function}
  23923. * @see {@link module:url.isCrossOrigin|isCrossOrigin}
  23924. * @deprecated Deprecated and will be removed in 9.0. Please use videojs.url.isCrossOrigin instead.
  23925. */
  23926. videojs.isCrossOrigin = deprecateForMajor(9, 'videojs.isCrossOrigin', 'videojs.url.isCrossOrigin', isCrossOrigin);
  23927. videojs.EventTarget = EventTarget$2;
  23928. videojs.any = any;
  23929. videojs.on = on;
  23930. videojs.one = one;
  23931. videojs.off = off;
  23932. videojs.trigger = trigger;
  23933. /**
  23934. * A cross-browser XMLHttpRequest wrapper.
  23935. *
  23936. * @function
  23937. * @param {Object} options
  23938. * Settings for the request.
  23939. *
  23940. * @return {XMLHttpRequest|XDomainRequest}
  23941. * The request object.
  23942. *
  23943. * @see https://github.com/Raynos/xhr
  23944. */
  23945. videojs.xhr = XHR__default["default"];
  23946. videojs.TextTrack = TextTrack;
  23947. videojs.AudioTrack = AudioTrack;
  23948. videojs.VideoTrack = VideoTrack;
  23949. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(k => {
  23950. videojs[k] = function () {
  23951. log$1.warn(`videojs.${k}() is deprecated; use videojs.dom.${k}() instead`);
  23952. return Dom[k].apply(null, arguments);
  23953. };
  23954. });
  23955. videojs.computedStyle = deprecateForMajor(9, 'videojs.computedStyle', 'videojs.dom.computedStyle', computedStyle);
  23956. /**
  23957. * A reference to the {@link module:dom|DOM utility module} as an object.
  23958. *
  23959. * @type {Object}
  23960. * @see {@link module:dom|dom}
  23961. */
  23962. videojs.dom = Dom;
  23963. /**
  23964. * A reference to the {@link module:fn|fn utility module} as an object.
  23965. *
  23966. * @type {Object}
  23967. * @see {@link module:fn|fn}
  23968. */
  23969. videojs.fn = Fn;
  23970. /**
  23971. * A reference to the {@link module:num|num utility module} as an object.
  23972. *
  23973. * @type {Object}
  23974. * @see {@link module:num|num}
  23975. */
  23976. videojs.num = Num;
  23977. /**
  23978. * A reference to the {@link module:str|str utility module} as an object.
  23979. *
  23980. * @type {Object}
  23981. * @see {@link module:str|str}
  23982. */
  23983. videojs.str = Str;
  23984. /**
  23985. * A reference to the {@link module:url|URL utility module} as an object.
  23986. *
  23987. * @type {Object}
  23988. * @see {@link module:url|url}
  23989. */
  23990. videojs.url = Url;
  23991. /*! @name videojs-contrib-quality-levels @version 3.0.0 @license Apache-2.0 */
  23992. /**
  23993. * A single QualityLevel.
  23994. *
  23995. * interface QualityLevel {
  23996. * readonly attribute DOMString id;
  23997. * attribute DOMString label;
  23998. * readonly attribute long width;
  23999. * readonly attribute long height;
  24000. * readonly attribute long bitrate;
  24001. * attribute boolean enabled;
  24002. * };
  24003. *
  24004. * @class QualityLevel
  24005. */
  24006. class QualityLevel {
  24007. /**
  24008. * Creates a QualityLevel
  24009. *
  24010. * @param {Representation|Object} representation The representation of the quality level
  24011. * @param {string} representation.id Unique id of the QualityLevel
  24012. * @param {number=} representation.width Resolution width of the QualityLevel
  24013. * @param {number=} representation.height Resolution height of the QualityLevel
  24014. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24015. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24016. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24017. */
  24018. constructor(representation) {
  24019. let level = this; // eslint-disable-line
  24020. level.id = representation.id;
  24021. level.label = level.id;
  24022. level.width = representation.width;
  24023. level.height = representation.height;
  24024. level.bitrate = representation.bandwidth;
  24025. level.frameRate = representation.frameRate;
  24026. level.enabled_ = representation.enabled;
  24027. Object.defineProperty(level, 'enabled', {
  24028. /**
  24029. * Get whether the QualityLevel is enabled.
  24030. *
  24031. * @return {boolean} True if the QualityLevel is enabled.
  24032. */
  24033. get() {
  24034. return level.enabled_();
  24035. },
  24036. /**
  24037. * Enable or disable the QualityLevel.
  24038. *
  24039. * @param {boolean} enable true to enable QualityLevel, false to disable.
  24040. */
  24041. set(enable) {
  24042. level.enabled_(enable);
  24043. }
  24044. });
  24045. return level;
  24046. }
  24047. }
  24048. /**
  24049. * A list of QualityLevels.
  24050. *
  24051. * interface QualityLevelList : EventTarget {
  24052. * getter QualityLevel (unsigned long index);
  24053. * readonly attribute unsigned long length;
  24054. * readonly attribute long selectedIndex;
  24055. *
  24056. * void addQualityLevel(QualityLevel qualityLevel)
  24057. * void removeQualityLevel(QualityLevel remove)
  24058. * QualityLevel? getQualityLevelById(DOMString id);
  24059. *
  24060. * attribute EventHandler onchange;
  24061. * attribute EventHandler onaddqualitylevel;
  24062. * attribute EventHandler onremovequalitylevel;
  24063. * };
  24064. *
  24065. * @extends videojs.EventTarget
  24066. * @class QualityLevelList
  24067. */
  24068. class QualityLevelList extends videojs.EventTarget {
  24069. constructor() {
  24070. super();
  24071. let list = this; // eslint-disable-line
  24072. list.levels_ = [];
  24073. list.selectedIndex_ = -1;
  24074. /**
  24075. * Get the index of the currently selected QualityLevel.
  24076. *
  24077. * @returns {number} The index of the selected QualityLevel. -1 if none selected.
  24078. * @readonly
  24079. */
  24080. Object.defineProperty(list, 'selectedIndex', {
  24081. get() {
  24082. return list.selectedIndex_;
  24083. }
  24084. });
  24085. /**
  24086. * Get the length of the list of QualityLevels.
  24087. *
  24088. * @returns {number} The length of the list.
  24089. * @readonly
  24090. */
  24091. Object.defineProperty(list, 'length', {
  24092. get() {
  24093. return list.levels_.length;
  24094. }
  24095. });
  24096. return list;
  24097. }
  24098. /**
  24099. * Adds a quality level to the list.
  24100. *
  24101. * @param {Representation|Object} representation The representation of the quality level
  24102. * @param {string} representation.id Unique id of the QualityLevel
  24103. * @param {number=} representation.width Resolution width of the QualityLevel
  24104. * @param {number=} representation.height Resolution height of the QualityLevel
  24105. * @param {number} representation.bandwidth Bitrate of the QualityLevel
  24106. * @param {number=} representation.frameRate Frame-rate of the QualityLevel
  24107. * @param {Function} representation.enabled Callback to enable/disable QualityLevel
  24108. * @return {QualityLevel} the QualityLevel added to the list
  24109. * @method addQualityLevel
  24110. */
  24111. addQualityLevel(representation) {
  24112. let qualityLevel = this.getQualityLevelById(representation.id); // Do not add duplicate quality levels
  24113. if (qualityLevel) {
  24114. return qualityLevel;
  24115. }
  24116. const index = this.levels_.length;
  24117. qualityLevel = new QualityLevel(representation);
  24118. if (!('' + index in this)) {
  24119. Object.defineProperty(this, index, {
  24120. get() {
  24121. return this.levels_[index];
  24122. }
  24123. });
  24124. }
  24125. this.levels_.push(qualityLevel);
  24126. this.trigger({
  24127. qualityLevel,
  24128. type: 'addqualitylevel'
  24129. });
  24130. return qualityLevel;
  24131. }
  24132. /**
  24133. * Removes a quality level from the list.
  24134. *
  24135. * @param {QualityLevel} remove QualityLevel to remove to the list.
  24136. * @return {QualityLevel|null} the QualityLevel removed or null if nothing removed
  24137. * @method removeQualityLevel
  24138. */
  24139. removeQualityLevel(qualityLevel) {
  24140. let removed = null;
  24141. for (let i = 0, l = this.length; i < l; i++) {
  24142. if (this[i] === qualityLevel) {
  24143. removed = this.levels_.splice(i, 1)[0];
  24144. if (this.selectedIndex_ === i) {
  24145. this.selectedIndex_ = -1;
  24146. } else if (this.selectedIndex_ > i) {
  24147. this.selectedIndex_--;
  24148. }
  24149. break;
  24150. }
  24151. }
  24152. if (removed) {
  24153. this.trigger({
  24154. qualityLevel,
  24155. type: 'removequalitylevel'
  24156. });
  24157. }
  24158. return removed;
  24159. }
  24160. /**
  24161. * Searches for a QualityLevel with the given id.
  24162. *
  24163. * @param {string} id The id of the QualityLevel to find.
  24164. * @return {QualityLevel|null} The QualityLevel with id, or null if not found.
  24165. * @method getQualityLevelById
  24166. */
  24167. getQualityLevelById(id) {
  24168. for (let i = 0, l = this.length; i < l; i++) {
  24169. const level = this[i];
  24170. if (level.id === id) {
  24171. return level;
  24172. }
  24173. }
  24174. return null;
  24175. }
  24176. /**
  24177. * Resets the list of QualityLevels to empty
  24178. *
  24179. * @method dispose
  24180. */
  24181. dispose() {
  24182. this.selectedIndex_ = -1;
  24183. this.levels_.length = 0;
  24184. }
  24185. }
  24186. /**
  24187. * change - The selected QualityLevel has changed.
  24188. * addqualitylevel - A QualityLevel has been added to the QualityLevelList.
  24189. * removequalitylevel - A QualityLevel has been removed from the QualityLevelList.
  24190. */
  24191. QualityLevelList.prototype.allowedEvents_ = {
  24192. change: 'change',
  24193. addqualitylevel: 'addqualitylevel',
  24194. removequalitylevel: 'removequalitylevel'
  24195. }; // emulate attribute EventHandler support to allow for feature detection
  24196. for (const event in QualityLevelList.prototype.allowedEvents_) {
  24197. QualityLevelList.prototype['on' + event] = null;
  24198. }
  24199. var version$5 = "3.0.0";
  24200. const registerPlugin = videojs.registerPlugin || videojs.plugin;
  24201. /**
  24202. * Initialization function for the qualityLevels plugin. Sets up the QualityLevelList and
  24203. * event handlers.
  24204. *
  24205. * @param {Player} player Player object.
  24206. * @param {Object} options Plugin options object.
  24207. * @function initPlugin
  24208. */
  24209. const initPlugin$1 = function (player, options) {
  24210. const originalPluginFn = player.qualityLevels;
  24211. const qualityLevelList = new QualityLevelList();
  24212. const disposeHandler = function () {
  24213. qualityLevelList.dispose();
  24214. player.qualityLevels = originalPluginFn;
  24215. player.off('dispose', disposeHandler);
  24216. };
  24217. player.on('dispose', disposeHandler);
  24218. player.qualityLevels = () => qualityLevelList;
  24219. player.qualityLevels.VERSION = version$5;
  24220. return qualityLevelList;
  24221. };
  24222. /**
  24223. * A video.js plugin.
  24224. *
  24225. * In the plugin function, the value of `this` is a video.js `Player`
  24226. * instance. You cannot rely on the player being in a "ready" state here,
  24227. * depending on how the plugin is invoked. This may or may not be important
  24228. * to you; if not, remove the wait for "ready"!
  24229. *
  24230. * @param {Object} options Plugin options object
  24231. * @function qualityLevels
  24232. */
  24233. const qualityLevels = function (options) {
  24234. return initPlugin$1(this, videojs.mergeOptions({}, options));
  24235. }; // Register the plugin with video.js.
  24236. registerPlugin('qualityLevels', qualityLevels); // Include the version number.
  24237. qualityLevels.VERSION = version$5;
  24238. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  24239. /**
  24240. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  24241. */
  24242. const resolveUrl = _resolveUrl__default["default"];
  24243. /**
  24244. * If the xhr request was redirected, return the responseURL, otherwise,
  24245. * return the original url.
  24246. *
  24247. * @api private
  24248. *
  24249. * @param {string} url - an url being requested
  24250. * @param {XMLHttpRequest} req - xhr request result
  24251. *
  24252. * @return {string}
  24253. */
  24254. const resolveManifestRedirect = (url, req) => {
  24255. // To understand how the responseURL below is set and generated:
  24256. // - https://fetch.spec.whatwg.org/#concept-response-url
  24257. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  24258. if (req && req.responseURL && url !== req.responseURL) {
  24259. return req.responseURL;
  24260. }
  24261. return url;
  24262. };
  24263. const logger = source => {
  24264. if (videojs.log.debug) {
  24265. return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
  24266. }
  24267. return function () {};
  24268. };
  24269. /**
  24270. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  24271. */
  24272. /**
  24273. * Delegates to videojs.obj.merge (Video.js 8) or
  24274. * videojs.mergeOptions (Video.js 7).
  24275. */
  24276. function merge(...args) {
  24277. const context = videojs.obj || videojs;
  24278. const fn = context.merge || context.mergeOptions;
  24279. return fn.apply(context, args);
  24280. }
  24281. /**
  24282. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  24283. * videojs.createTimeRanges (Video.js 7).
  24284. */
  24285. function createTimeRanges(...args) {
  24286. const context = videojs.time || videojs;
  24287. const fn = context.createTimeRanges || context.createTimeRanges;
  24288. return fn.apply(context, args);
  24289. }
  24290. /**
  24291. * ranges
  24292. *
  24293. * Utilities for working with TimeRanges.
  24294. *
  24295. */
  24296. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  24297. // can be misleading because of precision differences or when the current media has poorly
  24298. // aligned audio and video, which can cause values to be slightly off from what you would
  24299. // expect. This value is what we consider to be safe to use in such comparisons to account
  24300. // for these scenarios.
  24301. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  24302. const filterRanges = function (timeRanges, predicate) {
  24303. const results = [];
  24304. let i;
  24305. if (timeRanges && timeRanges.length) {
  24306. // Search for ranges that match the predicate
  24307. for (i = 0; i < timeRanges.length; i++) {
  24308. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  24309. results.push([timeRanges.start(i), timeRanges.end(i)]);
  24310. }
  24311. }
  24312. }
  24313. return createTimeRanges(results);
  24314. };
  24315. /**
  24316. * Attempts to find the buffered TimeRange that contains the specified
  24317. * time.
  24318. *
  24319. * @param {TimeRanges} buffered - the TimeRanges object to query
  24320. * @param {number} time - the time to filter on.
  24321. * @return {TimeRanges} a new TimeRanges object
  24322. */
  24323. const findRange = function (buffered, time) {
  24324. return filterRanges(buffered, function (start, end) {
  24325. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  24326. });
  24327. };
  24328. /**
  24329. * Returns the TimeRanges that begin later than the specified time.
  24330. *
  24331. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  24332. * @param {number} time - the time to filter on.
  24333. * @return {TimeRanges} a new TimeRanges object.
  24334. */
  24335. const findNextRange = function (timeRanges, time) {
  24336. return filterRanges(timeRanges, function (start) {
  24337. return start - TIME_FUDGE_FACTOR >= time;
  24338. });
  24339. };
  24340. /**
  24341. * Returns gaps within a list of TimeRanges
  24342. *
  24343. * @param {TimeRanges} buffered - the TimeRanges object
  24344. * @return {TimeRanges} a TimeRanges object of gaps
  24345. */
  24346. const findGaps = function (buffered) {
  24347. if (buffered.length < 2) {
  24348. return createTimeRanges();
  24349. }
  24350. const ranges = [];
  24351. for (let i = 1; i < buffered.length; i++) {
  24352. const start = buffered.end(i - 1);
  24353. const end = buffered.start(i);
  24354. ranges.push([start, end]);
  24355. }
  24356. return createTimeRanges(ranges);
  24357. };
  24358. /**
  24359. * Calculate the intersection of two TimeRanges
  24360. *
  24361. * @param {TimeRanges} bufferA
  24362. * @param {TimeRanges} bufferB
  24363. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  24364. */
  24365. const bufferIntersection = function (bufferA, bufferB) {
  24366. let start = null;
  24367. let end = null;
  24368. let arity = 0;
  24369. const extents = [];
  24370. const ranges = [];
  24371. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  24372. return createTimeRanges();
  24373. } // Handle the case where we have both buffers and create an
  24374. // intersection of the two
  24375. let count = bufferA.length; // A) Gather up all start and end times
  24376. while (count--) {
  24377. extents.push({
  24378. time: bufferA.start(count),
  24379. type: 'start'
  24380. });
  24381. extents.push({
  24382. time: bufferA.end(count),
  24383. type: 'end'
  24384. });
  24385. }
  24386. count = bufferB.length;
  24387. while (count--) {
  24388. extents.push({
  24389. time: bufferB.start(count),
  24390. type: 'start'
  24391. });
  24392. extents.push({
  24393. time: bufferB.end(count),
  24394. type: 'end'
  24395. });
  24396. } // B) Sort them by time
  24397. extents.sort(function (a, b) {
  24398. return a.time - b.time;
  24399. }); // C) Go along one by one incrementing arity for start and decrementing
  24400. // arity for ends
  24401. for (count = 0; count < extents.length; count++) {
  24402. if (extents[count].type === 'start') {
  24403. arity++; // D) If arity is ever incremented to 2 we are entering an
  24404. // overlapping range
  24405. if (arity === 2) {
  24406. start = extents[count].time;
  24407. }
  24408. } else if (extents[count].type === 'end') {
  24409. arity--; // E) If arity is ever decremented to 1 we leaving an
  24410. // overlapping range
  24411. if (arity === 1) {
  24412. end = extents[count].time;
  24413. }
  24414. } // F) Record overlapping ranges
  24415. if (start !== null && end !== null) {
  24416. ranges.push([start, end]);
  24417. start = null;
  24418. end = null;
  24419. }
  24420. }
  24421. return createTimeRanges(ranges);
  24422. };
  24423. /**
  24424. * Gets a human readable string for a TimeRange
  24425. *
  24426. * @param {TimeRange} range
  24427. * @return {string} a human readable string
  24428. */
  24429. const printableRange = range => {
  24430. const strArr = [];
  24431. if (!range || !range.length) {
  24432. return '';
  24433. }
  24434. for (let i = 0; i < range.length; i++) {
  24435. strArr.push(range.start(i) + ' => ' + range.end(i));
  24436. }
  24437. return strArr.join(', ');
  24438. };
  24439. /**
  24440. * Calculates the amount of time left in seconds until the player hits the end of the
  24441. * buffer and causes a rebuffer
  24442. *
  24443. * @param {TimeRange} buffered
  24444. * The state of the buffer
  24445. * @param {Numnber} currentTime
  24446. * The current time of the player
  24447. * @param {number} playbackRate
  24448. * The current playback rate of the player. Defaults to 1.
  24449. * @return {number}
  24450. * Time until the player has to start rebuffering in seconds.
  24451. * @function timeUntilRebuffer
  24452. */
  24453. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  24454. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  24455. return (bufferedEnd - currentTime) / playbackRate;
  24456. };
  24457. /**
  24458. * Converts a TimeRanges object into an array representation
  24459. *
  24460. * @param {TimeRanges} timeRanges
  24461. * @return {Array}
  24462. */
  24463. const timeRangesToArray = timeRanges => {
  24464. const timeRangesList = [];
  24465. for (let i = 0; i < timeRanges.length; i++) {
  24466. timeRangesList.push({
  24467. start: timeRanges.start(i),
  24468. end: timeRanges.end(i)
  24469. });
  24470. }
  24471. return timeRangesList;
  24472. };
  24473. /**
  24474. * Determines if two time range objects are different.
  24475. *
  24476. * @param {TimeRange} a
  24477. * the first time range object to check
  24478. *
  24479. * @param {TimeRange} b
  24480. * the second time range object to check
  24481. *
  24482. * @return {Boolean}
  24483. * Whether the time range objects differ
  24484. */
  24485. const isRangeDifferent = function (a, b) {
  24486. // same object
  24487. if (a === b) {
  24488. return false;
  24489. } // one or the other is undefined
  24490. if (!a && b || !b && a) {
  24491. return true;
  24492. } // length is different
  24493. if (a.length !== b.length) {
  24494. return true;
  24495. } // see if any start/end pair is different
  24496. for (let i = 0; i < a.length; i++) {
  24497. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  24498. return true;
  24499. }
  24500. } // if the length and every pair is the same
  24501. // this is the same time range
  24502. return false;
  24503. };
  24504. const lastBufferedEnd = function (a) {
  24505. if (!a || !a.length || !a.end) {
  24506. return;
  24507. }
  24508. return a.end(a.length - 1);
  24509. };
  24510. /**
  24511. * A utility function to add up the amount of time in a timeRange
  24512. * after a specified startTime.
  24513. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  24514. * would return 40 as there are 40s seconds after 0 in the timeRange
  24515. *
  24516. * @param {TimeRange} range
  24517. * The range to check against
  24518. * @param {number} startTime
  24519. * The time in the time range that you should start counting from
  24520. *
  24521. * @return {number}
  24522. * The number of seconds in the buffer passed the specified time.
  24523. */
  24524. const timeAheadOf = function (range, startTime) {
  24525. let time = 0;
  24526. if (!range || !range.length) {
  24527. return time;
  24528. }
  24529. for (let i = 0; i < range.length; i++) {
  24530. const start = range.start(i);
  24531. const end = range.end(i); // startTime is after this range entirely
  24532. if (startTime > end) {
  24533. continue;
  24534. } // startTime is within this range
  24535. if (startTime > start && startTime <= end) {
  24536. time += end - startTime;
  24537. continue;
  24538. } // startTime is before this range.
  24539. time += end - start;
  24540. }
  24541. return time;
  24542. };
  24543. /**
  24544. * @file playlist.js
  24545. *
  24546. * Playlist related utilities.
  24547. */
  24548. /**
  24549. * Get the duration of a segment, with special cases for
  24550. * llhls segments that do not have a duration yet.
  24551. *
  24552. * @param {Object} playlist
  24553. * the playlist that the segment belongs to.
  24554. * @param {Object} segment
  24555. * the segment to get a duration for.
  24556. *
  24557. * @return {number}
  24558. * the segment duration
  24559. */
  24560. const segmentDurationWithParts = (playlist, segment) => {
  24561. // if this isn't a preload segment
  24562. // then we will have a segment duration that is accurate.
  24563. if (!segment.preload) {
  24564. return segment.duration;
  24565. } // otherwise we have to add up parts and preload hints
  24566. // to get an up to date duration.
  24567. let result = 0;
  24568. (segment.parts || []).forEach(function (p) {
  24569. result += p.duration;
  24570. }); // for preload hints we have to use partTargetDuration
  24571. // as they won't even have a duration yet.
  24572. (segment.preloadHints || []).forEach(function (p) {
  24573. if (p.type === 'PART') {
  24574. result += playlist.partTargetDuration;
  24575. }
  24576. });
  24577. return result;
  24578. };
  24579. /**
  24580. * A function to get a combined list of parts and segments with durations
  24581. * and indexes.
  24582. *
  24583. * @param {Playlist} playlist the playlist to get the list for.
  24584. *
  24585. * @return {Array} The part/segment list.
  24586. */
  24587. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  24588. if (segment.parts) {
  24589. segment.parts.forEach(function (part, pi) {
  24590. acc.push({
  24591. duration: part.duration,
  24592. segmentIndex: si,
  24593. partIndex: pi,
  24594. part,
  24595. segment
  24596. });
  24597. });
  24598. } else {
  24599. acc.push({
  24600. duration: segment.duration,
  24601. segmentIndex: si,
  24602. partIndex: null,
  24603. segment,
  24604. part: null
  24605. });
  24606. }
  24607. return acc;
  24608. }, []);
  24609. const getLastParts = media => {
  24610. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  24611. return lastSegment && lastSegment.parts || [];
  24612. };
  24613. const getKnownPartCount = ({
  24614. preloadSegment
  24615. }) => {
  24616. if (!preloadSegment) {
  24617. return;
  24618. }
  24619. const {
  24620. parts,
  24621. preloadHints
  24622. } = preloadSegment;
  24623. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  24624. partCount += parts && parts.length ? parts.length : 0;
  24625. return partCount;
  24626. };
  24627. /**
  24628. * Get the number of seconds to delay from the end of a
  24629. * live playlist.
  24630. *
  24631. * @param {Playlist} main the main playlist
  24632. * @param {Playlist} media the media playlist
  24633. * @return {number} the hold back in seconds.
  24634. */
  24635. const liveEdgeDelay = (main, media) => {
  24636. if (media.endList) {
  24637. return 0;
  24638. } // dash suggestedPresentationDelay trumps everything
  24639. if (main && main.suggestedPresentationDelay) {
  24640. return main.suggestedPresentationDelay;
  24641. }
  24642. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  24643. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  24644. return media.serverControl.partHoldBack;
  24645. } else if (hasParts && media.partTargetDuration) {
  24646. return media.partTargetDuration * 3; // finally look for full segment delays
  24647. } else if (media.serverControl && media.serverControl.holdBack) {
  24648. return media.serverControl.holdBack;
  24649. } else if (media.targetDuration) {
  24650. return media.targetDuration * 3;
  24651. }
  24652. return 0;
  24653. };
  24654. /**
  24655. * walk backward until we find a duration we can use
  24656. * or return a failure
  24657. *
  24658. * @param {Playlist} playlist the playlist to walk through
  24659. * @param {Number} endSequence the mediaSequence to stop walking on
  24660. */
  24661. const backwardDuration = function (playlist, endSequence) {
  24662. let result = 0;
  24663. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  24664. // the interval, use it
  24665. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  24666. // information that is earlier than endSequence
  24667. if (segment) {
  24668. if (typeof segment.start !== 'undefined') {
  24669. return {
  24670. result: segment.start,
  24671. precise: true
  24672. };
  24673. }
  24674. if (typeof segment.end !== 'undefined') {
  24675. return {
  24676. result: segment.end - segment.duration,
  24677. precise: true
  24678. };
  24679. }
  24680. }
  24681. while (i--) {
  24682. segment = playlist.segments[i];
  24683. if (typeof segment.end !== 'undefined') {
  24684. return {
  24685. result: result + segment.end,
  24686. precise: true
  24687. };
  24688. }
  24689. result += segmentDurationWithParts(playlist, segment);
  24690. if (typeof segment.start !== 'undefined') {
  24691. return {
  24692. result: result + segment.start,
  24693. precise: true
  24694. };
  24695. }
  24696. }
  24697. return {
  24698. result,
  24699. precise: false
  24700. };
  24701. };
  24702. /**
  24703. * walk forward until we find a duration we can use
  24704. * or return a failure
  24705. *
  24706. * @param {Playlist} playlist the playlist to walk through
  24707. * @param {number} endSequence the mediaSequence to stop walking on
  24708. */
  24709. const forwardDuration = function (playlist, endSequence) {
  24710. let result = 0;
  24711. let segment;
  24712. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  24713. // information
  24714. for (; i < playlist.segments.length; i++) {
  24715. segment = playlist.segments[i];
  24716. if (typeof segment.start !== 'undefined') {
  24717. return {
  24718. result: segment.start - result,
  24719. precise: true
  24720. };
  24721. }
  24722. result += segmentDurationWithParts(playlist, segment);
  24723. if (typeof segment.end !== 'undefined') {
  24724. return {
  24725. result: segment.end - result,
  24726. precise: true
  24727. };
  24728. }
  24729. } // indicate we didn't find a useful duration estimate
  24730. return {
  24731. result: -1,
  24732. precise: false
  24733. };
  24734. };
  24735. /**
  24736. * Calculate the media duration from the segments associated with a
  24737. * playlist. The duration of a subinterval of the available segments
  24738. * may be calculated by specifying an end index.
  24739. *
  24740. * @param {Object} playlist a media playlist object
  24741. * @param {number=} endSequence an exclusive upper boundary
  24742. * for the playlist. Defaults to playlist length.
  24743. * @param {number} expired the amount of time that has dropped
  24744. * off the front of the playlist in a live scenario
  24745. * @return {number} the duration between the first available segment
  24746. * and end index.
  24747. */
  24748. const intervalDuration = function (playlist, endSequence, expired) {
  24749. if (typeof endSequence === 'undefined') {
  24750. endSequence = playlist.mediaSequence + playlist.segments.length;
  24751. }
  24752. if (endSequence < playlist.mediaSequence) {
  24753. return 0;
  24754. } // do a backward walk to estimate the duration
  24755. const backward = backwardDuration(playlist, endSequence);
  24756. if (backward.precise) {
  24757. // if we were able to base our duration estimate on timing
  24758. // information provided directly from the Media Source, return
  24759. // it
  24760. return backward.result;
  24761. } // walk forward to see if a precise duration estimate can be made
  24762. // that way
  24763. const forward = forwardDuration(playlist, endSequence);
  24764. if (forward.precise) {
  24765. // we found a segment that has been buffered and so it's
  24766. // position is known precisely
  24767. return forward.result;
  24768. } // return the less-precise, playlist-based duration estimate
  24769. return backward.result + expired;
  24770. };
  24771. /**
  24772. * Calculates the duration of a playlist. If a start and end index
  24773. * are specified, the duration will be for the subset of the media
  24774. * timeline between those two indices. The total duration for live
  24775. * playlists is always Infinity.
  24776. *
  24777. * @param {Object} playlist a media playlist object
  24778. * @param {number=} endSequence an exclusive upper
  24779. * boundary for the playlist. Defaults to the playlist media
  24780. * sequence number plus its length.
  24781. * @param {number=} expired the amount of time that has
  24782. * dropped off the front of the playlist in a live scenario
  24783. * @return {number} the duration between the start index and end
  24784. * index.
  24785. */
  24786. const duration = function (playlist, endSequence, expired) {
  24787. if (!playlist) {
  24788. return 0;
  24789. }
  24790. if (typeof expired !== 'number') {
  24791. expired = 0;
  24792. } // if a slice of the total duration is not requested, use
  24793. // playlist-level duration indicators when they're present
  24794. if (typeof endSequence === 'undefined') {
  24795. // if present, use the duration specified in the playlist
  24796. if (playlist.totalDuration) {
  24797. return playlist.totalDuration;
  24798. } // duration should be Infinity for live playlists
  24799. if (!playlist.endList) {
  24800. return window__default["default"].Infinity;
  24801. }
  24802. } // calculate the total duration based on the segment durations
  24803. return intervalDuration(playlist, endSequence, expired);
  24804. };
  24805. /**
  24806. * Calculate the time between two indexes in the current playlist
  24807. * neight the start- nor the end-index need to be within the current
  24808. * playlist in which case, the targetDuration of the playlist is used
  24809. * to approximate the durations of the segments
  24810. *
  24811. * @param {Array} options.durationList list to iterate over for durations.
  24812. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  24813. * @param {number} options.startIndex partsAndSegments index to start
  24814. * @param {number} options.endIndex partsAndSegments index to end.
  24815. * @return {number} the number of seconds between startIndex and endIndex
  24816. */
  24817. const sumDurations = function ({
  24818. defaultDuration,
  24819. durationList,
  24820. startIndex,
  24821. endIndex
  24822. }) {
  24823. let durations = 0;
  24824. if (startIndex > endIndex) {
  24825. [startIndex, endIndex] = [endIndex, startIndex];
  24826. }
  24827. if (startIndex < 0) {
  24828. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  24829. durations += defaultDuration;
  24830. }
  24831. startIndex = 0;
  24832. }
  24833. for (let i = startIndex; i < endIndex; i++) {
  24834. durations += durationList[i].duration;
  24835. }
  24836. return durations;
  24837. };
  24838. /**
  24839. * Calculates the playlist end time
  24840. *
  24841. * @param {Object} playlist a media playlist object
  24842. * @param {number=} expired the amount of time that has
  24843. * dropped off the front of the playlist in a live scenario
  24844. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  24845. * playlist end calculation should consider the safe live end
  24846. * (truncate the playlist end by three segments). This is normally
  24847. * used for calculating the end of the playlist's seekable range.
  24848. * This takes into account the value of liveEdgePadding.
  24849. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  24850. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  24851. * If this is provided, it is used in the safe live end calculation.
  24852. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  24853. * Corresponds to suggestedPresentationDelay in DASH manifests.
  24854. * @return {number} the end time of playlist
  24855. * @function playlistEnd
  24856. */
  24857. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  24858. if (!playlist || !playlist.segments) {
  24859. return null;
  24860. }
  24861. if (playlist.endList) {
  24862. return duration(playlist);
  24863. }
  24864. if (expired === null) {
  24865. return null;
  24866. }
  24867. expired = expired || 0;
  24868. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  24869. if (useSafeLiveEnd) {
  24870. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  24871. lastSegmentEndTime -= liveEdgePadding;
  24872. } // don't return a time less than zero
  24873. return Math.max(0, lastSegmentEndTime);
  24874. };
  24875. /**
  24876. * Calculates the interval of time that is currently seekable in a
  24877. * playlist. The returned time ranges are relative to the earliest
  24878. * moment in the specified playlist that is still available. A full
  24879. * seekable implementation for live streams would need to offset
  24880. * these values by the duration of content that has expired from the
  24881. * stream.
  24882. *
  24883. * @param {Object} playlist a media playlist object
  24884. * dropped off the front of the playlist in a live scenario
  24885. * @param {number=} expired the amount of time that has
  24886. * dropped off the front of the playlist in a live scenario
  24887. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  24888. * Corresponds to suggestedPresentationDelay in DASH manifests.
  24889. * @return {TimeRanges} the periods of time that are valid targets
  24890. * for seeking
  24891. */
  24892. const seekable = function (playlist, expired, liveEdgePadding) {
  24893. const useSafeLiveEnd = true;
  24894. const seekableStart = expired || 0;
  24895. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  24896. if (seekableEnd === null) {
  24897. return createTimeRanges();
  24898. }
  24899. return createTimeRanges(seekableStart, seekableEnd);
  24900. };
  24901. /**
  24902. * Determine the index and estimated starting time of the segment that
  24903. * contains a specified playback position in a media playlist.
  24904. *
  24905. * @param {Object} options.playlist the media playlist to query
  24906. * @param {number} options.currentTime The number of seconds since the earliest
  24907. * possible position to determine the containing segment for
  24908. * @param {number} options.startTime the time when the segment/part starts
  24909. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  24910. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  24911. *
  24912. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  24913. */
  24914. const getMediaInfoForTime = function ({
  24915. playlist,
  24916. currentTime,
  24917. startingSegmentIndex,
  24918. startingPartIndex,
  24919. startTime,
  24920. exactManifestTimings
  24921. }) {
  24922. let time = currentTime - startTime;
  24923. const partsAndSegments = getPartsAndSegments(playlist);
  24924. let startIndex = 0;
  24925. for (let i = 0; i < partsAndSegments.length; i++) {
  24926. const partAndSegment = partsAndSegments[i];
  24927. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  24928. continue;
  24929. } // skip this if part index does not match.
  24930. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  24931. continue;
  24932. }
  24933. startIndex = i;
  24934. break;
  24935. }
  24936. if (time < 0) {
  24937. // Walk backward from startIndex in the playlist, adding durations
  24938. // until we find a segment that contains `time` and return it
  24939. if (startIndex > 0) {
  24940. for (let i = startIndex - 1; i >= 0; i--) {
  24941. const partAndSegment = partsAndSegments[i];
  24942. time += partAndSegment.duration;
  24943. if (exactManifestTimings) {
  24944. if (time < 0) {
  24945. continue;
  24946. }
  24947. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  24948. continue;
  24949. }
  24950. return {
  24951. partIndex: partAndSegment.partIndex,
  24952. segmentIndex: partAndSegment.segmentIndex,
  24953. startTime: startTime - sumDurations({
  24954. defaultDuration: playlist.targetDuration,
  24955. durationList: partsAndSegments,
  24956. startIndex,
  24957. endIndex: i
  24958. })
  24959. };
  24960. }
  24961. } // We were unable to find a good segment within the playlist
  24962. // so select the first segment
  24963. return {
  24964. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  24965. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  24966. startTime: currentTime
  24967. };
  24968. } // When startIndex is negative, we first walk forward to first segment
  24969. // adding target durations. If we "run out of time" before getting to
  24970. // the first segment, return the first segment
  24971. if (startIndex < 0) {
  24972. for (let i = startIndex; i < 0; i++) {
  24973. time -= playlist.targetDuration;
  24974. if (time < 0) {
  24975. return {
  24976. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  24977. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  24978. startTime: currentTime
  24979. };
  24980. }
  24981. }
  24982. startIndex = 0;
  24983. } // Walk forward from startIndex in the playlist, subtracting durations
  24984. // until we find a segment that contains `time` and return it
  24985. for (let i = startIndex; i < partsAndSegments.length; i++) {
  24986. const partAndSegment = partsAndSegments[i];
  24987. time -= partAndSegment.duration;
  24988. if (exactManifestTimings) {
  24989. if (time > 0) {
  24990. continue;
  24991. }
  24992. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  24993. continue;
  24994. }
  24995. return {
  24996. partIndex: partAndSegment.partIndex,
  24997. segmentIndex: partAndSegment.segmentIndex,
  24998. startTime: startTime + sumDurations({
  24999. defaultDuration: playlist.targetDuration,
  25000. durationList: partsAndSegments,
  25001. startIndex,
  25002. endIndex: i
  25003. })
  25004. };
  25005. } // We are out of possible candidates so load the last one...
  25006. return {
  25007. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  25008. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  25009. startTime: currentTime
  25010. };
  25011. };
  25012. /**
  25013. * Check whether the playlist is excluded or not.
  25014. *
  25015. * @param {Object} playlist the media playlist object
  25016. * @return {boolean} whether the playlist is excluded or not
  25017. * @function isExcluded
  25018. */
  25019. const isExcluded = function (playlist) {
  25020. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  25021. };
  25022. /**
  25023. * Check whether the playlist is compatible with current playback configuration or has
  25024. * been excluded permanently for being incompatible.
  25025. *
  25026. * @param {Object} playlist the media playlist object
  25027. * @return {boolean} whether the playlist is incompatible or not
  25028. * @function isIncompatible
  25029. */
  25030. const isIncompatible = function (playlist) {
  25031. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  25032. };
  25033. /**
  25034. * Check whether the playlist is enabled or not.
  25035. *
  25036. * @param {Object} playlist the media playlist object
  25037. * @return {boolean} whether the playlist is enabled or not
  25038. * @function isEnabled
  25039. */
  25040. const isEnabled = function (playlist) {
  25041. const excluded = isExcluded(playlist);
  25042. return !playlist.disabled && !excluded;
  25043. };
  25044. /**
  25045. * Check whether the playlist has been manually disabled through the representations api.
  25046. *
  25047. * @param {Object} playlist the media playlist object
  25048. * @return {boolean} whether the playlist is disabled manually or not
  25049. * @function isDisabled
  25050. */
  25051. const isDisabled = function (playlist) {
  25052. return playlist.disabled;
  25053. };
  25054. /**
  25055. * Returns whether the current playlist is an AES encrypted HLS stream
  25056. *
  25057. * @return {boolean} true if it's an AES encrypted HLS stream
  25058. */
  25059. const isAes = function (media) {
  25060. for (let i = 0; i < media.segments.length; i++) {
  25061. if (media.segments[i].key) {
  25062. return true;
  25063. }
  25064. }
  25065. return false;
  25066. };
  25067. /**
  25068. * Checks if the playlist has a value for the specified attribute
  25069. *
  25070. * @param {string} attr
  25071. * Attribute to check for
  25072. * @param {Object} playlist
  25073. * The media playlist object
  25074. * @return {boolean}
  25075. * Whether the playlist contains a value for the attribute or not
  25076. * @function hasAttribute
  25077. */
  25078. const hasAttribute = function (attr, playlist) {
  25079. return playlist.attributes && playlist.attributes[attr];
  25080. };
  25081. /**
  25082. * Estimates the time required to complete a segment download from the specified playlist
  25083. *
  25084. * @param {number} segmentDuration
  25085. * Duration of requested segment
  25086. * @param {number} bandwidth
  25087. * Current measured bandwidth of the player
  25088. * @param {Object} playlist
  25089. * The media playlist object
  25090. * @param {number=} bytesReceived
  25091. * Number of bytes already received for the request. Defaults to 0
  25092. * @return {number|NaN}
  25093. * The estimated time to request the segment. NaN if bandwidth information for
  25094. * the given playlist is unavailable
  25095. * @function estimateSegmentRequestTime
  25096. */
  25097. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  25098. if (!hasAttribute('BANDWIDTH', playlist)) {
  25099. return NaN;
  25100. }
  25101. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  25102. return (size - bytesReceived * 8) / bandwidth;
  25103. };
  25104. /*
  25105. * Returns whether the current playlist is the lowest rendition
  25106. *
  25107. * @return {Boolean} true if on lowest rendition
  25108. */
  25109. const isLowestEnabledRendition = (main, media) => {
  25110. if (main.playlists.length === 1) {
  25111. return true;
  25112. }
  25113. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  25114. return main.playlists.filter(playlist => {
  25115. if (!isEnabled(playlist)) {
  25116. return false;
  25117. }
  25118. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  25119. }).length === 0;
  25120. };
  25121. const playlistMatch = (a, b) => {
  25122. // both playlits are null
  25123. // or only one playlist is non-null
  25124. // no match
  25125. if (!a && !b || !a && b || a && !b) {
  25126. return false;
  25127. } // playlist objects are the same, match
  25128. if (a === b) {
  25129. return true;
  25130. } // first try to use id as it should be the most
  25131. // accurate
  25132. if (a.id && b.id && a.id === b.id) {
  25133. return true;
  25134. } // next try to use reslovedUri as it should be the
  25135. // second most accurate.
  25136. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  25137. return true;
  25138. } // finally try to use uri as it should be accurate
  25139. // but might miss a few cases for relative uris
  25140. if (a.uri && b.uri && a.uri === b.uri) {
  25141. return true;
  25142. }
  25143. return false;
  25144. };
  25145. const someAudioVariant = function (main, callback) {
  25146. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  25147. let found = false;
  25148. for (const groupName in AUDIO) {
  25149. for (const label in AUDIO[groupName]) {
  25150. found = callback(AUDIO[groupName][label]);
  25151. if (found) {
  25152. break;
  25153. }
  25154. }
  25155. if (found) {
  25156. break;
  25157. }
  25158. }
  25159. return !!found;
  25160. };
  25161. const isAudioOnly = main => {
  25162. // we are audio only if we have no main playlists but do
  25163. // have media group playlists.
  25164. if (!main || !main.playlists || !main.playlists.length) {
  25165. // without audio variants or playlists this
  25166. // is not an audio only main.
  25167. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  25168. return found;
  25169. } // if every playlist has only an audio codec it is audio only
  25170. for (let i = 0; i < main.playlists.length; i++) {
  25171. const playlist = main.playlists[i];
  25172. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  25173. if (CODECS && CODECS.split(',').every(c => codecs_js.isAudioCodec(c))) {
  25174. continue;
  25175. } // playlist is in an audio group it is audio only
  25176. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  25177. if (found) {
  25178. continue;
  25179. } // if we make it here this playlist isn't audio and we
  25180. // are not audio only
  25181. return false;
  25182. } // if we make it past every playlist without returning, then
  25183. // this is an audio only playlist.
  25184. return true;
  25185. }; // exports
  25186. var Playlist = {
  25187. liveEdgeDelay,
  25188. duration,
  25189. seekable,
  25190. getMediaInfoForTime,
  25191. isEnabled,
  25192. isDisabled,
  25193. isExcluded,
  25194. isIncompatible,
  25195. playlistEnd,
  25196. isAes,
  25197. hasAttribute,
  25198. estimateSegmentRequestTime,
  25199. isLowestEnabledRendition,
  25200. isAudioOnly,
  25201. playlistMatch,
  25202. segmentDurationWithParts
  25203. };
  25204. const {
  25205. log
  25206. } = videojs;
  25207. const createPlaylistID = (index, uri) => {
  25208. return `${index}-${uri}`;
  25209. }; // default function for creating a group id
  25210. const groupID = (type, group, label) => {
  25211. return `placeholder-uri-${type}-${group}-${label}`;
  25212. };
  25213. /**
  25214. * Parses a given m3u8 playlist
  25215. *
  25216. * @param {Function} [onwarn]
  25217. * a function to call when the parser triggers a warning event.
  25218. * @param {Function} [oninfo]
  25219. * a function to call when the parser triggers an info event.
  25220. * @param {string} manifestString
  25221. * The downloaded manifest string
  25222. * @param {Object[]} [customTagParsers]
  25223. * An array of custom tag parsers for the m3u8-parser instance
  25224. * @param {Object[]} [customTagMappers]
  25225. * An array of custom tag mappers for the m3u8-parser instance
  25226. * @param {boolean} [llhls]
  25227. * Whether to keep ll-hls features in the manifest after parsing.
  25228. * @return {Object}
  25229. * The manifest object
  25230. */
  25231. const parseManifest = ({
  25232. onwarn,
  25233. oninfo,
  25234. manifestString,
  25235. customTagParsers = [],
  25236. customTagMappers = [],
  25237. llhls
  25238. }) => {
  25239. const parser = new m3u8Parser.Parser();
  25240. if (onwarn) {
  25241. parser.on('warn', onwarn);
  25242. }
  25243. if (oninfo) {
  25244. parser.on('info', oninfo);
  25245. }
  25246. customTagParsers.forEach(customParser => parser.addParser(customParser));
  25247. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  25248. parser.push(manifestString);
  25249. parser.end();
  25250. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  25251. // if we don't want llhls support.
  25252. if (!llhls) {
  25253. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  25254. if (manifest.hasOwnProperty(k)) {
  25255. delete manifest[k];
  25256. }
  25257. });
  25258. if (manifest.segments) {
  25259. manifest.segments.forEach(function (segment) {
  25260. ['parts', 'preloadHints'].forEach(function (k) {
  25261. if (segment.hasOwnProperty(k)) {
  25262. delete segment[k];
  25263. }
  25264. });
  25265. });
  25266. }
  25267. }
  25268. if (!manifest.targetDuration) {
  25269. let targetDuration = 10;
  25270. if (manifest.segments && manifest.segments.length) {
  25271. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  25272. }
  25273. if (onwarn) {
  25274. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  25275. }
  25276. manifest.targetDuration = targetDuration;
  25277. }
  25278. const parts = getLastParts(manifest);
  25279. if (parts.length && !manifest.partTargetDuration) {
  25280. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  25281. if (onwarn) {
  25282. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  25283. log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
  25284. }
  25285. manifest.partTargetDuration = partTargetDuration;
  25286. }
  25287. return manifest;
  25288. };
  25289. /**
  25290. * Loops through all supported media groups in main and calls the provided
  25291. * callback for each group
  25292. *
  25293. * @param {Object} main
  25294. * The parsed main manifest object
  25295. * @param {Function} callback
  25296. * Callback to call for each media group
  25297. */
  25298. const forEachMediaGroup = (main, callback) => {
  25299. if (!main.mediaGroups) {
  25300. return;
  25301. }
  25302. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  25303. if (!main.mediaGroups[mediaType]) {
  25304. return;
  25305. }
  25306. for (const groupKey in main.mediaGroups[mediaType]) {
  25307. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  25308. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  25309. callback(mediaProperties, mediaType, groupKey, labelKey);
  25310. }
  25311. }
  25312. });
  25313. };
  25314. /**
  25315. * Adds properties and attributes to the playlist to keep consistent functionality for
  25316. * playlists throughout VHS.
  25317. *
  25318. * @param {Object} config
  25319. * Arguments object
  25320. * @param {Object} config.playlist
  25321. * The media playlist
  25322. * @param {string} [config.uri]
  25323. * The uri to the media playlist (if media playlist is not from within a main
  25324. * playlist)
  25325. * @param {string} id
  25326. * ID to use for the playlist
  25327. */
  25328. const setupMediaPlaylist = ({
  25329. playlist,
  25330. uri,
  25331. id
  25332. }) => {
  25333. playlist.id = id;
  25334. playlist.playlistErrors_ = 0;
  25335. if (uri) {
  25336. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  25337. // playlists do not contain their own source URI, but one is needed for consistency in
  25338. // VHS.
  25339. playlist.uri = uri;
  25340. } // For HLS main playlists, even though certain attributes MUST be defined, the
  25341. // stream may still be played without them.
  25342. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  25343. // manifest.
  25344. //
  25345. // To avoid undefined reference errors through the project, and make the code easier
  25346. // to write/read, add an empty attributes object for these cases.
  25347. playlist.attributes = playlist.attributes || {};
  25348. };
  25349. /**
  25350. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  25351. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  25352. * playlist references to the playlists array.
  25353. *
  25354. * @param {Object} main
  25355. * The main playlist
  25356. */
  25357. const setupMediaPlaylists = main => {
  25358. let i = main.playlists.length;
  25359. while (i--) {
  25360. const playlist = main.playlists[i];
  25361. setupMediaPlaylist({
  25362. playlist,
  25363. id: createPlaylistID(i, playlist.uri)
  25364. });
  25365. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  25366. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  25367. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  25368. // the stream can be played without it. Although an attributes property may have been
  25369. // added to the playlist to prevent undefined references, issue a warning to fix the
  25370. // manifest.
  25371. if (!playlist.attributes.BANDWIDTH) {
  25372. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  25373. }
  25374. }
  25375. };
  25376. /**
  25377. * Adds resolvedUri properties to each media group.
  25378. *
  25379. * @param {Object} main
  25380. * The main playlist
  25381. */
  25382. const resolveMediaGroupUris = main => {
  25383. forEachMediaGroup(main, properties => {
  25384. if (properties.uri) {
  25385. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  25386. }
  25387. });
  25388. };
  25389. /**
  25390. * Creates a main playlist wrapper to insert a sole media playlist into.
  25391. *
  25392. * @param {Object} media
  25393. * Media playlist
  25394. * @param {string} uri
  25395. * The media URI
  25396. *
  25397. * @return {Object}
  25398. * main playlist
  25399. */
  25400. const mainForMedia = (media, uri) => {
  25401. const id = createPlaylistID(0, uri);
  25402. const main = {
  25403. mediaGroups: {
  25404. 'AUDIO': {},
  25405. 'VIDEO': {},
  25406. 'CLOSED-CAPTIONS': {},
  25407. 'SUBTITLES': {}
  25408. },
  25409. uri: window__default["default"].location.href,
  25410. resolvedUri: window__default["default"].location.href,
  25411. playlists: [{
  25412. uri,
  25413. id,
  25414. resolvedUri: uri,
  25415. // m3u8-parser does not attach an attributes property to media playlists so make
  25416. // sure that the property is attached to avoid undefined reference errors
  25417. attributes: {}
  25418. }]
  25419. }; // set up ID reference
  25420. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  25421. main.playlists[uri] = main.playlists[0];
  25422. return main;
  25423. };
  25424. /**
  25425. * Does an in-place update of the main manifest to add updated playlist URI references
  25426. * as well as other properties needed by VHS that aren't included by the parser.
  25427. *
  25428. * @param {Object} main
  25429. * main manifest object
  25430. * @param {string} uri
  25431. * The source URI
  25432. * @param {function} createGroupID
  25433. * A function to determine how to create the groupID for mediaGroups
  25434. */
  25435. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  25436. main.uri = uri;
  25437. for (let i = 0; i < main.playlists.length; i++) {
  25438. if (!main.playlists[i].uri) {
  25439. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  25440. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  25441. // TODO: consider adding dummy URIs in mpd-parser
  25442. const phonyUri = `placeholder-uri-${i}`;
  25443. main.playlists[i].uri = phonyUri;
  25444. }
  25445. }
  25446. const audioOnlyMain = isAudioOnly(main);
  25447. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  25448. // add a playlist array under properties
  25449. if (!properties.playlists || !properties.playlists.length) {
  25450. // If the manifest is audio only and this media group does not have a uri, check
  25451. // if the media group is located in the main list of playlists. If it is, don't add
  25452. // placeholder properties as it shouldn't be considered an alternate audio track.
  25453. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  25454. for (let i = 0; i < main.playlists.length; i++) {
  25455. const p = main.playlists[i];
  25456. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  25457. return;
  25458. }
  25459. }
  25460. }
  25461. properties.playlists = [_extends__default["default"]({}, properties)];
  25462. }
  25463. properties.playlists.forEach(function (p, i) {
  25464. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  25465. const id = createPlaylistID(i, groupId);
  25466. if (p.uri) {
  25467. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  25468. } else {
  25469. // DEPRECATED, this has been added to prevent a breaking change.
  25470. // previously we only ever had a single media group playlist, so
  25471. // we mark the first playlist uri without prepending the index as we used to
  25472. // ideally we would do all of the playlists the same way.
  25473. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  25474. // the placeholder again
  25475. p.resolvedUri = p.uri;
  25476. }
  25477. p.id = p.id || id; // add an empty attributes object, all playlists are
  25478. // expected to have this.
  25479. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  25480. main.playlists[p.id] = p;
  25481. main.playlists[p.uri] = p;
  25482. });
  25483. });
  25484. setupMediaPlaylists(main);
  25485. resolveMediaGroupUris(main);
  25486. };
  25487. /**
  25488. * @file playlist-loader.js
  25489. *
  25490. * A state machine that manages the loading, caching, and updating of
  25491. * M3U8 playlists.
  25492. *
  25493. */
  25494. const {
  25495. EventTarget: EventTarget$1
  25496. } = videojs;
  25497. const addLLHLSQueryDirectives = (uri, media) => {
  25498. if (media.endList || !media.serverControl) {
  25499. return uri;
  25500. }
  25501. const parameters = {};
  25502. if (media.serverControl.canBlockReload) {
  25503. const {
  25504. preloadSegment
  25505. } = media; // next msn is a zero based value, length is not.
  25506. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  25507. // that we are going to request a part of that preload segment.
  25508. // the logic below is used to determine that.
  25509. if (preloadSegment) {
  25510. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  25511. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  25512. // length of parts, then we know we had part preload hints
  25513. // and we need to add the _HLS_part= query
  25514. if (nextPart > -1 && nextPart !== parts.length - 1) {
  25515. // add existing parts to our preload hints
  25516. // eslint-disable-next-line
  25517. parameters._HLS_part = nextPart;
  25518. } // this if statement makes sure that we request the msn
  25519. // of the preload segment if:
  25520. // 1. the preload segment had parts (and was not yet a full segment)
  25521. // but was added to our segments array
  25522. // 2. the preload segment had preload hints for parts that are not in
  25523. // the manifest yet.
  25524. // in all other cases we want the segment after the preload segment
  25525. // which will be given by using media.segments.length because it is 1 based
  25526. // rather than 0 based.
  25527. if (nextPart > -1 || parts.length) {
  25528. nextMSN--;
  25529. }
  25530. } // add _HLS_msn= in front of any _HLS_part query
  25531. // eslint-disable-next-line
  25532. parameters._HLS_msn = nextMSN;
  25533. }
  25534. if (media.serverControl && media.serverControl.canSkipUntil) {
  25535. // add _HLS_skip= infront of all other queries.
  25536. // eslint-disable-next-line
  25537. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  25538. }
  25539. if (Object.keys(parameters).length) {
  25540. const parsedUri = new window__default["default"].URL(uri);
  25541. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  25542. if (!parameters.hasOwnProperty(name)) {
  25543. return;
  25544. }
  25545. parsedUri.searchParams.set(name, parameters[name]);
  25546. });
  25547. uri = parsedUri.toString();
  25548. }
  25549. return uri;
  25550. };
  25551. /**
  25552. * Returns a new segment object with properties and
  25553. * the parts array merged.
  25554. *
  25555. * @param {Object} a the old segment
  25556. * @param {Object} b the new segment
  25557. *
  25558. * @return {Object} the merged segment
  25559. */
  25560. const updateSegment = (a, b) => {
  25561. if (!a) {
  25562. return b;
  25563. }
  25564. const result = merge(a, b); // if only the old segment has preload hints
  25565. // and the new one does not, remove preload hints.
  25566. if (a.preloadHints && !b.preloadHints) {
  25567. delete result.preloadHints;
  25568. } // if only the old segment has parts
  25569. // then the parts are no longer valid
  25570. if (a.parts && !b.parts) {
  25571. delete result.parts; // if both segments have parts
  25572. // copy part propeties from the old segment
  25573. // to the new one.
  25574. } else if (a.parts && b.parts) {
  25575. for (let i = 0; i < b.parts.length; i++) {
  25576. if (a.parts && a.parts[i]) {
  25577. result.parts[i] = merge(a.parts[i], b.parts[i]);
  25578. }
  25579. }
  25580. } // set skipped to false for segments that have
  25581. // have had information merged from the old segment.
  25582. if (!a.skipped && b.skipped) {
  25583. result.skipped = false;
  25584. } // set preload to false for segments that have
  25585. // had information added in the new segment.
  25586. if (a.preload && !b.preload) {
  25587. result.preload = false;
  25588. }
  25589. return result;
  25590. };
  25591. /**
  25592. * Returns a new array of segments that is the result of merging
  25593. * properties from an older list of segments onto an updated
  25594. * list. No properties on the updated playlist will be ovewritten.
  25595. *
  25596. * @param {Array} original the outdated list of segments
  25597. * @param {Array} update the updated list of segments
  25598. * @param {number=} offset the index of the first update
  25599. * segment in the original segment list. For non-live playlists,
  25600. * this should always be zero and does not need to be
  25601. * specified. For live playlists, it should be the difference
  25602. * between the media sequence numbers in the original and updated
  25603. * playlists.
  25604. * @return {Array} a list of merged segment objects
  25605. */
  25606. const updateSegments = (original, update, offset) => {
  25607. const oldSegments = original.slice();
  25608. const newSegments = update.slice();
  25609. offset = offset || 0;
  25610. const result = [];
  25611. let currentMap;
  25612. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  25613. const oldSegment = oldSegments[newIndex + offset];
  25614. const newSegment = newSegments[newIndex];
  25615. if (oldSegment) {
  25616. currentMap = oldSegment.map || currentMap;
  25617. result.push(updateSegment(oldSegment, newSegment));
  25618. } else {
  25619. // carry over map to new segment if it is missing
  25620. if (currentMap && !newSegment.map) {
  25621. newSegment.map = currentMap;
  25622. }
  25623. result.push(newSegment);
  25624. }
  25625. }
  25626. return result;
  25627. };
  25628. const resolveSegmentUris = (segment, baseUri) => {
  25629. // preloadSegment will not have a uri at all
  25630. // as the segment isn't actually in the manifest yet, only parts
  25631. if (!segment.resolvedUri && segment.uri) {
  25632. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  25633. }
  25634. if (segment.key && !segment.key.resolvedUri) {
  25635. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  25636. }
  25637. if (segment.map && !segment.map.resolvedUri) {
  25638. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  25639. }
  25640. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  25641. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  25642. }
  25643. if (segment.parts && segment.parts.length) {
  25644. segment.parts.forEach(p => {
  25645. if (p.resolvedUri) {
  25646. return;
  25647. }
  25648. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25649. });
  25650. }
  25651. if (segment.preloadHints && segment.preloadHints.length) {
  25652. segment.preloadHints.forEach(p => {
  25653. if (p.resolvedUri) {
  25654. return;
  25655. }
  25656. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25657. });
  25658. }
  25659. };
  25660. const getAllSegments = function (media) {
  25661. const segments = media.segments || [];
  25662. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  25663. // a usable segment, only include a preloadSegment that has
  25664. // parts.
  25665. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  25666. // if preloadHints has a MAP that means that the
  25667. // init segment is going to change. We cannot use any of the parts
  25668. // from this preload segment.
  25669. if (preloadSegment.preloadHints) {
  25670. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  25671. if (preloadSegment.preloadHints[i].type === 'MAP') {
  25672. return segments;
  25673. }
  25674. }
  25675. } // set the duration for our preload segment to target duration.
  25676. preloadSegment.duration = media.targetDuration;
  25677. preloadSegment.preload = true;
  25678. segments.push(preloadSegment);
  25679. }
  25680. return segments;
  25681. }; // consider the playlist unchanged if the playlist object is the same or
  25682. // the number of segments is equal, the media sequence number is unchanged,
  25683. // and this playlist hasn't become the end of the playlist
  25684. const isPlaylistUnchanged = (a, b) => a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
  25685. /**
  25686. * Returns a new main playlist that is the result of merging an
  25687. * updated media playlist into the original version. If the
  25688. * updated media playlist does not match any of the playlist
  25689. * entries in the original main playlist, null is returned.
  25690. *
  25691. * @param {Object} main a parsed main M3U8 object
  25692. * @param {Object} media a parsed media M3U8 object
  25693. * @return {Object} a new object that represents the original
  25694. * main playlist with the updated media playlist merged in, or
  25695. * null if the merge produced no change.
  25696. */
  25697. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  25698. const result = merge(main, {});
  25699. const oldMedia = result.playlists[newMedia.id];
  25700. if (!oldMedia) {
  25701. return null;
  25702. }
  25703. if (unchangedCheck(oldMedia, newMedia)) {
  25704. return null;
  25705. }
  25706. newMedia.segments = getAllSegments(newMedia);
  25707. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  25708. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  25709. delete mergedPlaylist.preloadSegment;
  25710. } // if the update could overlap existing segment information, merge the two segment lists
  25711. if (oldMedia.segments) {
  25712. if (newMedia.skip) {
  25713. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  25714. // old properties into the new segments
  25715. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  25716. newMedia.segments.unshift({
  25717. skipped: true
  25718. });
  25719. }
  25720. }
  25721. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  25722. } // resolve any segment URIs to prevent us from having to do it later
  25723. mergedPlaylist.segments.forEach(segment => {
  25724. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  25725. }); // TODO Right now in the playlists array there are two references to each playlist, one
  25726. // that is referenced by index, and one by URI. The index reference may no longer be
  25727. // necessary.
  25728. for (let i = 0; i < result.playlists.length; i++) {
  25729. if (result.playlists[i].id === newMedia.id) {
  25730. result.playlists[i] = mergedPlaylist;
  25731. }
  25732. }
  25733. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  25734. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  25735. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  25736. if (!properties.playlists) {
  25737. return;
  25738. }
  25739. for (let i = 0; i < properties.playlists.length; i++) {
  25740. if (newMedia.id === properties.playlists[i].id) {
  25741. properties.playlists[i] = mergedPlaylist;
  25742. }
  25743. }
  25744. });
  25745. return result;
  25746. };
  25747. /**
  25748. * Calculates the time to wait before refreshing a live playlist
  25749. *
  25750. * @param {Object} media
  25751. * The current media
  25752. * @param {boolean} update
  25753. * True if there were any updates from the last refresh, false otherwise
  25754. * @return {number}
  25755. * The time in ms to wait before refreshing the live playlist
  25756. */
  25757. const refreshDelay = (media, update) => {
  25758. const segments = media.segments || [];
  25759. const lastSegment = segments[segments.length - 1];
  25760. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  25761. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  25762. if (update && lastDuration) {
  25763. return lastDuration * 1000;
  25764. } // if the playlist is unchanged since the last reload or last segment duration
  25765. // cannot be determined, try again after half the target duration
  25766. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  25767. };
  25768. /**
  25769. * Load a playlist from a remote location
  25770. *
  25771. * @class PlaylistLoader
  25772. * @extends Stream
  25773. * @param {string|Object} src url or object of manifest
  25774. * @param {boolean} withCredentials the withCredentials xhr option
  25775. * @class
  25776. */
  25777. class PlaylistLoader extends EventTarget$1 {
  25778. constructor(src, vhs, options = {}) {
  25779. super();
  25780. if (!src) {
  25781. throw new Error('A non-empty playlist URL or object is required');
  25782. }
  25783. this.logger_ = logger('PlaylistLoader');
  25784. const {
  25785. withCredentials = false
  25786. } = options;
  25787. this.src = src;
  25788. this.vhs_ = vhs;
  25789. this.withCredentials = withCredentials;
  25790. const vhsOptions = vhs.options_;
  25791. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  25792. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  25793. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  25794. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  25795. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  25796. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  25797. }
  25798. handleMediaupdatetimeout_() {
  25799. if (this.state !== 'HAVE_METADATA') {
  25800. // only refresh the media playlist if no other activity is going on
  25801. return;
  25802. }
  25803. const media = this.media();
  25804. let uri = resolveUrl(this.main.uri, media.uri);
  25805. if (this.llhls) {
  25806. uri = addLLHLSQueryDirectives(uri, media);
  25807. }
  25808. this.state = 'HAVE_CURRENT_METADATA';
  25809. this.request = this.vhs_.xhr({
  25810. uri,
  25811. withCredentials: this.withCredentials
  25812. }, (error, req) => {
  25813. // disposed
  25814. if (!this.request) {
  25815. return;
  25816. }
  25817. if (error) {
  25818. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  25819. }
  25820. this.haveMetadata({
  25821. playlistString: this.request.responseText,
  25822. url: this.media().uri,
  25823. id: this.media().id
  25824. });
  25825. });
  25826. }
  25827. playlistRequestError(xhr, playlist, startingState) {
  25828. const {
  25829. uri,
  25830. id
  25831. } = playlist; // any in-flight request is now finished
  25832. this.request = null;
  25833. if (startingState) {
  25834. this.state = startingState;
  25835. }
  25836. this.error = {
  25837. playlist: this.main.playlists[id],
  25838. status: xhr.status,
  25839. message: `HLS playlist request error at URL: ${uri}.`,
  25840. responseText: xhr.responseText,
  25841. code: xhr.status >= 500 ? 4 : 2
  25842. };
  25843. this.trigger('error');
  25844. }
  25845. parseManifest_({
  25846. url,
  25847. manifestString
  25848. }) {
  25849. return parseManifest({
  25850. onwarn: ({
  25851. message
  25852. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  25853. oninfo: ({
  25854. message
  25855. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  25856. manifestString,
  25857. customTagParsers: this.customTagParsers,
  25858. customTagMappers: this.customTagMappers,
  25859. llhls: this.llhls
  25860. });
  25861. }
  25862. /**
  25863. * Update the playlist loader's state in response to a new or updated playlist.
  25864. *
  25865. * @param {string} [playlistString]
  25866. * Playlist string (if playlistObject is not provided)
  25867. * @param {Object} [playlistObject]
  25868. * Playlist object (if playlistString is not provided)
  25869. * @param {string} url
  25870. * URL of playlist
  25871. * @param {string} id
  25872. * ID to use for playlist
  25873. */
  25874. haveMetadata({
  25875. playlistString,
  25876. playlistObject,
  25877. url,
  25878. id
  25879. }) {
  25880. // any in-flight request is now finished
  25881. this.request = null;
  25882. this.state = 'HAVE_METADATA';
  25883. const playlist = playlistObject || this.parseManifest_({
  25884. url,
  25885. manifestString: playlistString
  25886. });
  25887. playlist.lastRequest = Date.now();
  25888. setupMediaPlaylist({
  25889. playlist,
  25890. uri: url,
  25891. id
  25892. }); // merge this playlist into the main manifest
  25893. const update = updateMain$1(this.main, playlist);
  25894. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  25895. this.pendingMedia_ = null;
  25896. if (update) {
  25897. this.main = update;
  25898. this.media_ = this.main.playlists[id];
  25899. } else {
  25900. this.trigger('playlistunchanged');
  25901. }
  25902. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  25903. this.trigger('loadedplaylist');
  25904. }
  25905. /**
  25906. * Abort any outstanding work and clean up.
  25907. */
  25908. dispose() {
  25909. this.trigger('dispose');
  25910. this.stopRequest();
  25911. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  25912. window__default["default"].clearTimeout(this.finalRenditionTimeout);
  25913. this.off();
  25914. }
  25915. stopRequest() {
  25916. if (this.request) {
  25917. const oldRequest = this.request;
  25918. this.request = null;
  25919. oldRequest.onreadystatechange = null;
  25920. oldRequest.abort();
  25921. }
  25922. }
  25923. /**
  25924. * When called without any arguments, returns the currently
  25925. * active media playlist. When called with a single argument,
  25926. * triggers the playlist loader to asynchronously switch to the
  25927. * specified media playlist. Calling this method while the
  25928. * loader is in the HAVE_NOTHING causes an error to be emitted
  25929. * but otherwise has no effect.
  25930. *
  25931. * @param {Object=} playlist the parsed media playlist
  25932. * object to switch to
  25933. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  25934. *
  25935. * @return {Playlist} the current loaded media
  25936. */
  25937. media(playlist, shouldDelay) {
  25938. // getter
  25939. if (!playlist) {
  25940. return this.media_;
  25941. } // setter
  25942. if (this.state === 'HAVE_NOTHING') {
  25943. throw new Error('Cannot switch media playlist from ' + this.state);
  25944. } // find the playlist object if the target playlist has been
  25945. // specified by URI
  25946. if (typeof playlist === 'string') {
  25947. if (!this.main.playlists[playlist]) {
  25948. throw new Error('Unknown playlist URI: ' + playlist);
  25949. }
  25950. playlist = this.main.playlists[playlist];
  25951. }
  25952. window__default["default"].clearTimeout(this.finalRenditionTimeout);
  25953. if (shouldDelay) {
  25954. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  25955. this.finalRenditionTimeout = window__default["default"].setTimeout(this.media.bind(this, playlist, false), delay);
  25956. return;
  25957. }
  25958. const startingState = this.state;
  25959. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  25960. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  25961. if (mainPlaylistRef && mainPlaylistRef.endList ||
  25962. // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  25963. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  25964. playlist.endList && playlist.segments.length) {
  25965. // abort outstanding playlist requests
  25966. if (this.request) {
  25967. this.request.onreadystatechange = null;
  25968. this.request.abort();
  25969. this.request = null;
  25970. }
  25971. this.state = 'HAVE_METADATA';
  25972. this.media_ = playlist; // trigger media change if the active media has been updated
  25973. if (mediaChange) {
  25974. this.trigger('mediachanging');
  25975. if (startingState === 'HAVE_MAIN_MANIFEST') {
  25976. // The initial playlist was a main manifest, and the first media selected was
  25977. // also provided (in the form of a resolved playlist object) as part of the
  25978. // source object (rather than just a URL). Therefore, since the media playlist
  25979. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  25980. // normal flow, and needs an explicit trigger here.
  25981. this.trigger('loadedmetadata');
  25982. } else {
  25983. this.trigger('mediachange');
  25984. }
  25985. }
  25986. return;
  25987. } // We update/set the timeout here so that live playlists
  25988. // that are not a media change will "start" the loader as expected.
  25989. // We expect that this function will start the media update timeout
  25990. // cycle again. This also prevents a playlist switch failure from
  25991. // causing us to stall during live.
  25992. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  25993. if (!mediaChange) {
  25994. return;
  25995. }
  25996. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  25997. if (this.request) {
  25998. if (playlist.resolvedUri === this.request.url) {
  25999. // requesting to switch to the same playlist multiple times
  26000. // has no effect after the first
  26001. return;
  26002. }
  26003. this.request.onreadystatechange = null;
  26004. this.request.abort();
  26005. this.request = null;
  26006. } // request the new playlist
  26007. if (this.media_) {
  26008. this.trigger('mediachanging');
  26009. }
  26010. this.pendingMedia_ = playlist;
  26011. this.request = this.vhs_.xhr({
  26012. uri: playlist.resolvedUri,
  26013. withCredentials: this.withCredentials
  26014. }, (error, req) => {
  26015. // disposed
  26016. if (!this.request) {
  26017. return;
  26018. }
  26019. playlist.lastRequest = Date.now();
  26020. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  26021. if (error) {
  26022. return this.playlistRequestError(this.request, playlist, startingState);
  26023. }
  26024. this.haveMetadata({
  26025. playlistString: req.responseText,
  26026. url: playlist.uri,
  26027. id: playlist.id
  26028. }); // fire loadedmetadata the first time a media playlist is loaded
  26029. if (startingState === 'HAVE_MAIN_MANIFEST') {
  26030. this.trigger('loadedmetadata');
  26031. } else {
  26032. this.trigger('mediachange');
  26033. }
  26034. });
  26035. }
  26036. /**
  26037. * pause loading of the playlist
  26038. */
  26039. pause() {
  26040. if (this.mediaUpdateTimeout) {
  26041. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  26042. this.mediaUpdateTimeout = null;
  26043. }
  26044. this.stopRequest();
  26045. if (this.state === 'HAVE_NOTHING') {
  26046. // If we pause the loader before any data has been retrieved, its as if we never
  26047. // started, so reset to an unstarted state.
  26048. this.started = false;
  26049. } // Need to restore state now that no activity is happening
  26050. if (this.state === 'SWITCHING_MEDIA') {
  26051. // if the loader was in the process of switching media, it should either return to
  26052. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  26053. // playlist yet. This is determined by the existence of loader.media_
  26054. if (this.media_) {
  26055. this.state = 'HAVE_METADATA';
  26056. } else {
  26057. this.state = 'HAVE_MAIN_MANIFEST';
  26058. }
  26059. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  26060. this.state = 'HAVE_METADATA';
  26061. }
  26062. }
  26063. /**
  26064. * start loading of the playlist
  26065. */
  26066. load(shouldDelay) {
  26067. if (this.mediaUpdateTimeout) {
  26068. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  26069. this.mediaUpdateTimeout = null;
  26070. }
  26071. const media = this.media();
  26072. if (shouldDelay) {
  26073. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  26074. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  26075. this.mediaUpdateTimeout = null;
  26076. this.load();
  26077. }, delay);
  26078. return;
  26079. }
  26080. if (!this.started) {
  26081. this.start();
  26082. return;
  26083. }
  26084. if (media && !media.endList) {
  26085. this.trigger('mediaupdatetimeout');
  26086. } else {
  26087. this.trigger('loadedplaylist');
  26088. }
  26089. }
  26090. updateMediaUpdateTimeout_(delay) {
  26091. if (this.mediaUpdateTimeout) {
  26092. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  26093. this.mediaUpdateTimeout = null;
  26094. } // we only have use mediaupdatetimeout for live playlists.
  26095. if (!this.media() || this.media().endList) {
  26096. return;
  26097. }
  26098. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  26099. this.mediaUpdateTimeout = null;
  26100. this.trigger('mediaupdatetimeout');
  26101. this.updateMediaUpdateTimeout_(delay);
  26102. }, delay);
  26103. }
  26104. /**
  26105. * start loading of the playlist
  26106. */
  26107. start() {
  26108. this.started = true;
  26109. if (typeof this.src === 'object') {
  26110. // in the case of an entirely constructed manifest object (meaning there's no actual
  26111. // manifest on a server), default the uri to the page's href
  26112. if (!this.src.uri) {
  26113. this.src.uri = window__default["default"].location.href;
  26114. } // resolvedUri is added on internally after the initial request. Since there's no
  26115. // request for pre-resolved manifests, add on resolvedUri here.
  26116. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  26117. // request can be skipped (since the top level of the manifest, at a minimum, is
  26118. // already available as a parsed manifest object). However, if the manifest object
  26119. // represents a main playlist, some media playlists may need to be resolved before
  26120. // the starting segment list is available. Therefore, go directly to setup of the
  26121. // initial playlist, and let the normal flow continue from there.
  26122. //
  26123. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  26124. // that the first request is asynchronous.
  26125. setTimeout(() => {
  26126. this.setupInitialPlaylist(this.src);
  26127. }, 0);
  26128. return;
  26129. } // request the specified URL
  26130. this.request = this.vhs_.xhr({
  26131. uri: this.src,
  26132. withCredentials: this.withCredentials
  26133. }, (error, req) => {
  26134. // disposed
  26135. if (!this.request) {
  26136. return;
  26137. } // clear the loader's request reference
  26138. this.request = null;
  26139. if (error) {
  26140. this.error = {
  26141. status: req.status,
  26142. message: `HLS playlist request error at URL: ${this.src}.`,
  26143. responseText: req.responseText,
  26144. // MEDIA_ERR_NETWORK
  26145. code: 2
  26146. };
  26147. if (this.state === 'HAVE_NOTHING') {
  26148. this.started = false;
  26149. }
  26150. return this.trigger('error');
  26151. }
  26152. this.src = resolveManifestRedirect(this.src, req);
  26153. const manifest = this.parseManifest_({
  26154. manifestString: req.responseText,
  26155. url: this.src
  26156. });
  26157. this.setupInitialPlaylist(manifest);
  26158. });
  26159. }
  26160. srcUri() {
  26161. return typeof this.src === 'string' ? this.src : this.src.uri;
  26162. }
  26163. /**
  26164. * Given a manifest object that's either a main or media playlist, trigger the proper
  26165. * events and set the state of the playlist loader.
  26166. *
  26167. * If the manifest object represents a main playlist, `loadedplaylist` will be
  26168. * triggered to allow listeners to select a playlist. If none is selected, the loader
  26169. * will default to the first one in the playlists array.
  26170. *
  26171. * If the manifest object represents a media playlist, `loadedplaylist` will be
  26172. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  26173. *
  26174. * In the case of a media playlist, a main playlist object wrapper with one playlist
  26175. * will be created so that all logic can handle playlists in the same fashion (as an
  26176. * assumed manifest object schema).
  26177. *
  26178. * @param {Object} manifest
  26179. * The parsed manifest object
  26180. */
  26181. setupInitialPlaylist(manifest) {
  26182. this.state = 'HAVE_MAIN_MANIFEST';
  26183. if (manifest.playlists) {
  26184. this.main = manifest;
  26185. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  26186. // then resolve URIs in advance, as they are usually done after a playlist request,
  26187. // which may not happen if the playlist is resolved.
  26188. manifest.playlists.forEach(playlist => {
  26189. playlist.segments = getAllSegments(playlist);
  26190. playlist.segments.forEach(segment => {
  26191. resolveSegmentUris(segment, playlist.resolvedUri);
  26192. });
  26193. });
  26194. this.trigger('loadedplaylist');
  26195. if (!this.request) {
  26196. // no media playlist was specifically selected so start
  26197. // from the first listed one
  26198. this.media(this.main.playlists[0]);
  26199. }
  26200. return;
  26201. } // In order to support media playlists passed in as vhs-json, the case where the uri
  26202. // is not provided as part of the manifest should be considered, and an appropriate
  26203. // default used.
  26204. const uri = this.srcUri() || window__default["default"].location.href;
  26205. this.main = mainForMedia(manifest, uri);
  26206. this.haveMetadata({
  26207. playlistObject: manifest,
  26208. url: uri,
  26209. id: this.main.playlists[0].id
  26210. });
  26211. this.trigger('loadedmetadata');
  26212. }
  26213. }
  26214. /**
  26215. * @file xhr.js
  26216. */
  26217. const {
  26218. xhr: videojsXHR
  26219. } = videojs;
  26220. const callbackWrapper = function (request, error, response, callback) {
  26221. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  26222. if (!error && reqResponse) {
  26223. request.responseTime = Date.now();
  26224. request.roundTripTime = request.responseTime - request.requestTime;
  26225. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  26226. if (!request.bandwidth) {
  26227. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  26228. }
  26229. }
  26230. if (response.headers) {
  26231. request.responseHeaders = response.headers;
  26232. } // videojs.xhr now uses a specific code on the error
  26233. // object to signal that a request has timed out instead
  26234. // of setting a boolean on the request object
  26235. if (error && error.code === 'ETIMEDOUT') {
  26236. request.timedout = true;
  26237. } // videojs.xhr no longer considers status codes outside of 200 and 0
  26238. // (for file uris) to be errors, but the old XHR did, so emulate that
  26239. // behavior. Status 206 may be used in response to byterange requests.
  26240. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  26241. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  26242. }
  26243. callback(error, request);
  26244. };
  26245. const xhrFactory = function () {
  26246. const xhr = function XhrFunction(options, callback) {
  26247. // Add a default timeout
  26248. options = merge({
  26249. timeout: 45e3
  26250. }, options); // Allow an optional user-specified function to modify the option
  26251. // object before we construct the xhr request
  26252. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  26253. if (beforeRequest && typeof beforeRequest === 'function') {
  26254. const newOptions = beforeRequest(options);
  26255. if (newOptions) {
  26256. options = newOptions;
  26257. }
  26258. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  26259. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  26260. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  26261. const request = xhrMethod(options, function (error, response) {
  26262. return callbackWrapper(request, error, response, callback);
  26263. });
  26264. const originalAbort = request.abort;
  26265. request.abort = function () {
  26266. request.aborted = true;
  26267. return originalAbort.apply(request, arguments);
  26268. };
  26269. request.uri = options.uri;
  26270. request.requestTime = Date.now();
  26271. return request;
  26272. };
  26273. xhr.original = true;
  26274. return xhr;
  26275. };
  26276. /**
  26277. * Turns segment byterange into a string suitable for use in
  26278. * HTTP Range requests
  26279. *
  26280. * @param {Object} byterange - an object with two values defining the start and end
  26281. * of a byte-range
  26282. */
  26283. const byterangeStr = function (byterange) {
  26284. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  26285. // header uses inclusive ranges
  26286. let byterangeEnd;
  26287. const byterangeStart = byterange.offset;
  26288. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  26289. byterangeEnd = window__default["default"].BigInt(byterange.offset) + window__default["default"].BigInt(byterange.length) - window__default["default"].BigInt(1);
  26290. } else {
  26291. byterangeEnd = byterange.offset + byterange.length - 1;
  26292. }
  26293. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  26294. };
  26295. /**
  26296. * Defines headers for use in the xhr request for a particular segment.
  26297. *
  26298. * @param {Object} segment - a simplified copy of the segmentInfo object
  26299. * from SegmentLoader
  26300. */
  26301. const segmentXhrHeaders = function (segment) {
  26302. const headers = {};
  26303. if (segment.byterange) {
  26304. headers.Range = byterangeStr(segment.byterange);
  26305. }
  26306. return headers;
  26307. };
  26308. /**
  26309. * @file bin-utils.js
  26310. */
  26311. /**
  26312. * convert a TimeRange to text
  26313. *
  26314. * @param {TimeRange} range the timerange to use for conversion
  26315. * @param {number} i the iterator on the range to convert
  26316. * @return {string} the range in string format
  26317. */
  26318. const textRange = function (range, i) {
  26319. return range.start(i) + '-' + range.end(i);
  26320. };
  26321. /**
  26322. * format a number as hex string
  26323. *
  26324. * @param {number} e The number
  26325. * @param {number} i the iterator
  26326. * @return {string} the hex formatted number as a string
  26327. */
  26328. const formatHexString = function (e, i) {
  26329. const value = e.toString(16);
  26330. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  26331. };
  26332. const formatAsciiString = function (e) {
  26333. if (e >= 0x20 && e < 0x7e) {
  26334. return String.fromCharCode(e);
  26335. }
  26336. return '.';
  26337. };
  26338. /**
  26339. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  26340. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  26341. *
  26342. * @param {Object} message
  26343. * Object of properties and values to send to the web worker
  26344. * @return {Object}
  26345. * Modified message with TypedArray values expanded
  26346. * @function createTransferableMessage
  26347. */
  26348. const createTransferableMessage = function (message) {
  26349. const transferable = {};
  26350. Object.keys(message).forEach(key => {
  26351. const value = message[key];
  26352. if (byteHelpers.isArrayBufferView(value)) {
  26353. transferable[key] = {
  26354. bytes: value.buffer,
  26355. byteOffset: value.byteOffset,
  26356. byteLength: value.byteLength
  26357. };
  26358. } else {
  26359. transferable[key] = value;
  26360. }
  26361. });
  26362. return transferable;
  26363. };
  26364. /**
  26365. * Returns a unique string identifier for a media initialization
  26366. * segment.
  26367. *
  26368. * @param {Object} initSegment
  26369. * the init segment object.
  26370. *
  26371. * @return {string} the generated init segment id
  26372. */
  26373. const initSegmentId = function (initSegment) {
  26374. const byterange = initSegment.byterange || {
  26375. length: Infinity,
  26376. offset: 0
  26377. };
  26378. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  26379. };
  26380. /**
  26381. * Returns a unique string identifier for a media segment key.
  26382. *
  26383. * @param {Object} key the encryption key
  26384. * @return {string} the unique id for the media segment key.
  26385. */
  26386. const segmentKeyId = function (key) {
  26387. return key.resolvedUri;
  26388. };
  26389. /**
  26390. * utils to help dump binary data to the console
  26391. *
  26392. * @param {Array|TypedArray} data
  26393. * data to dump to a string
  26394. *
  26395. * @return {string} the data as a hex string.
  26396. */
  26397. const hexDump = data => {
  26398. const bytes = Array.prototype.slice.call(data);
  26399. const step = 16;
  26400. let result = '';
  26401. let hex;
  26402. let ascii;
  26403. for (let j = 0; j < bytes.length / step; j++) {
  26404. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  26405. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  26406. result += hex + ' ' + ascii + '\n';
  26407. }
  26408. return result;
  26409. };
  26410. const tagDump = ({
  26411. bytes
  26412. }) => hexDump(bytes);
  26413. const textRanges = ranges => {
  26414. let result = '';
  26415. let i;
  26416. for (i = 0; i < ranges.length; i++) {
  26417. result += textRange(ranges, i) + ' ';
  26418. }
  26419. return result;
  26420. };
  26421. var utils = /*#__PURE__*/Object.freeze({
  26422. __proto__: null,
  26423. createTransferableMessage: createTransferableMessage,
  26424. initSegmentId: initSegmentId,
  26425. segmentKeyId: segmentKeyId,
  26426. hexDump: hexDump,
  26427. tagDump: tagDump,
  26428. textRanges: textRanges
  26429. });
  26430. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  26431. // 25% was arbitrarily chosen, and may need to be refined over time.
  26432. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  26433. /**
  26434. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  26435. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  26436. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  26437. *
  26438. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  26439. * point" (a point where we have a mapping from program time to player time, with player
  26440. * time being the post transmux start of the segment).
  26441. *
  26442. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  26443. *
  26444. * @param {number} playerTime the player time
  26445. * @param {Object} segment the segment which contains the player time
  26446. * @return {Date} program time
  26447. */
  26448. const playerTimeToProgramTime = (playerTime, segment) => {
  26449. if (!segment.dateTimeObject) {
  26450. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  26451. // be used to map the start of a segment with a real world time).
  26452. return null;
  26453. }
  26454. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  26455. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  26456. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  26457. const offsetFromSegmentStart = playerTime - startOfSegment;
  26458. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  26459. };
  26460. const originalSegmentVideoDuration = videoTimingInfo => {
  26461. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  26462. };
  26463. /**
  26464. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  26465. * returned segment might be an estimate or an accurate match.
  26466. *
  26467. * @param {string} programTime The ISO-8601 programTime to find a match for
  26468. * @param {Object} playlist A playlist object to search within
  26469. */
  26470. const findSegmentForProgramTime = (programTime, playlist) => {
  26471. // Assumptions:
  26472. // - verifyProgramDateTimeTags has already been run
  26473. // - live streams have been started
  26474. let dateTimeObject;
  26475. try {
  26476. dateTimeObject = new Date(programTime);
  26477. } catch (e) {
  26478. return null;
  26479. }
  26480. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26481. return null;
  26482. }
  26483. let segment = playlist.segments[0];
  26484. if (dateTimeObject < segment.dateTimeObject) {
  26485. // Requested time is before stream start.
  26486. return null;
  26487. }
  26488. for (let i = 0; i < playlist.segments.length - 1; i++) {
  26489. segment = playlist.segments[i];
  26490. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  26491. if (dateTimeObject < nextSegmentStart) {
  26492. break;
  26493. }
  26494. }
  26495. const lastSegment = playlist.segments[playlist.segments.length - 1];
  26496. const lastSegmentStart = lastSegment.dateTimeObject;
  26497. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  26498. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  26499. if (dateTimeObject > lastSegmentEnd) {
  26500. // Beyond the end of the stream, or our best guess of the end of the stream.
  26501. return null;
  26502. }
  26503. if (dateTimeObject > lastSegmentStart) {
  26504. segment = lastSegment;
  26505. }
  26506. return {
  26507. segment,
  26508. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  26509. // Although, given that all segments have accurate date time objects, the segment
  26510. // selected should be accurate, unless the video has been transmuxed at some point
  26511. // (determined by the presence of the videoTimingInfo object), the segment's "player
  26512. // time" (the start time in the player) can't be considered accurate.
  26513. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26514. };
  26515. };
  26516. /**
  26517. * Finds a segment that contains the given player time(in seconds).
  26518. *
  26519. * @param {number} time The player time to find a match for
  26520. * @param {Object} playlist A playlist object to search within
  26521. */
  26522. const findSegmentForPlayerTime = (time, playlist) => {
  26523. // Assumptions:
  26524. // - there will always be a segment.duration
  26525. // - we can start from zero
  26526. // - segments are in time order
  26527. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26528. return null;
  26529. }
  26530. let segmentEnd = 0;
  26531. let segment;
  26532. for (let i = 0; i < playlist.segments.length; i++) {
  26533. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  26534. // should contain the most accurate values we have for the segment's player times.
  26535. //
  26536. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  26537. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  26538. // calculate an end value.
  26539. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  26540. if (time <= segmentEnd) {
  26541. break;
  26542. }
  26543. }
  26544. const lastSegment = playlist.segments[playlist.segments.length - 1];
  26545. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  26546. // The time requested is beyond the stream end.
  26547. return null;
  26548. }
  26549. if (time > segmentEnd) {
  26550. // The time is within or beyond the last segment.
  26551. //
  26552. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  26553. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  26554. // Technically, because the duration value is only an estimate, the time may still
  26555. // exist in the last segment, however, there isn't enough information to make even
  26556. // a reasonable estimate.
  26557. return null;
  26558. }
  26559. segment = lastSegment;
  26560. }
  26561. return {
  26562. segment,
  26563. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  26564. // Because videoTimingInfo is only set after transmux, it is the only way to get
  26565. // accurate timing values.
  26566. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26567. };
  26568. };
  26569. /**
  26570. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  26571. * If the offset returned is positive, the programTime occurs after the
  26572. * comparisonTimestamp.
  26573. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  26574. *
  26575. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  26576. * @param {string} programTime The programTime as an ISO-8601 string
  26577. * @return {number} offset
  26578. */
  26579. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  26580. let segmentDateTime;
  26581. let programDateTime;
  26582. try {
  26583. segmentDateTime = new Date(comparisonTimeStamp);
  26584. programDateTime = new Date(programTime);
  26585. } catch (e) {// TODO handle error
  26586. }
  26587. const segmentTimeEpoch = segmentDateTime.getTime();
  26588. const programTimeEpoch = programDateTime.getTime();
  26589. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  26590. };
  26591. /**
  26592. * Checks that all segments in this playlist have programDateTime tags.
  26593. *
  26594. * @param {Object} playlist A playlist object
  26595. */
  26596. const verifyProgramDateTimeTags = playlist => {
  26597. if (!playlist.segments || playlist.segments.length === 0) {
  26598. return false;
  26599. }
  26600. for (let i = 0; i < playlist.segments.length; i++) {
  26601. const segment = playlist.segments[i];
  26602. if (!segment.dateTimeObject) {
  26603. return false;
  26604. }
  26605. }
  26606. return true;
  26607. };
  26608. /**
  26609. * Returns the programTime of the media given a playlist and a playerTime.
  26610. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  26611. * If the segments containing the time requested have not been buffered yet, an estimate
  26612. * may be returned to the callback.
  26613. *
  26614. * @param {Object} args
  26615. * @param {Object} args.playlist A playlist object to search within
  26616. * @param {number} time A playerTime in seconds
  26617. * @param {Function} callback(err, programTime)
  26618. * @return {string} err.message A detailed error message
  26619. * @return {Object} programTime
  26620. * @return {number} programTime.mediaSeconds The streamTime in seconds
  26621. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  26622. */
  26623. const getProgramTime = ({
  26624. playlist,
  26625. time = undefined,
  26626. callback
  26627. }) => {
  26628. if (!callback) {
  26629. throw new Error('getProgramTime: callback must be provided');
  26630. }
  26631. if (!playlist || time === undefined) {
  26632. return callback({
  26633. message: 'getProgramTime: playlist and time must be provided'
  26634. });
  26635. }
  26636. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  26637. if (!matchedSegment) {
  26638. return callback({
  26639. message: 'valid programTime was not found'
  26640. });
  26641. }
  26642. if (matchedSegment.type === 'estimate') {
  26643. return callback({
  26644. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  26645. seekTime: matchedSegment.estimatedStart
  26646. });
  26647. }
  26648. const programTimeObject = {
  26649. mediaSeconds: time
  26650. };
  26651. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  26652. if (programTime) {
  26653. programTimeObject.programDateTime = programTime.toISOString();
  26654. }
  26655. return callback(null, programTimeObject);
  26656. };
  26657. /**
  26658. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  26659. *
  26660. * @param {Object} args
  26661. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  26662. * @param {Object} args.playlist A playlist to look within
  26663. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  26664. * @param {Function} args.seekTo A method to perform a seek
  26665. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  26666. * @param {Object} args.tech The tech to seek on
  26667. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  26668. * @return {string} err.message A detailed error message
  26669. * @return {number} newTime The exact time that was seeked to in seconds
  26670. */
  26671. const seekToProgramTime = ({
  26672. programTime,
  26673. playlist,
  26674. retryCount = 2,
  26675. seekTo,
  26676. pauseAfterSeek = true,
  26677. tech,
  26678. callback
  26679. }) => {
  26680. if (!callback) {
  26681. throw new Error('seekToProgramTime: callback must be provided');
  26682. }
  26683. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  26684. return callback({
  26685. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  26686. });
  26687. }
  26688. if (!playlist.endList && !tech.hasStarted_) {
  26689. return callback({
  26690. message: 'player must be playing a live stream to start buffering'
  26691. });
  26692. }
  26693. if (!verifyProgramDateTimeTags(playlist)) {
  26694. return callback({
  26695. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  26696. });
  26697. }
  26698. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  26699. if (!matchedSegment) {
  26700. return callback({
  26701. message: `${programTime} was not found in the stream`
  26702. });
  26703. }
  26704. const segment = matchedSegment.segment;
  26705. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  26706. if (matchedSegment.type === 'estimate') {
  26707. // we've run out of retries
  26708. if (retryCount === 0) {
  26709. return callback({
  26710. message: `${programTime} is not buffered yet. Try again`
  26711. });
  26712. }
  26713. seekTo(matchedSegment.estimatedStart + mediaOffset);
  26714. tech.one('seeked', () => {
  26715. seekToProgramTime({
  26716. programTime,
  26717. playlist,
  26718. retryCount: retryCount - 1,
  26719. seekTo,
  26720. pauseAfterSeek,
  26721. tech,
  26722. callback
  26723. });
  26724. });
  26725. return;
  26726. } // Since the segment.start value is determined from the buffered end or ending time
  26727. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  26728. // modifications.
  26729. const seekToTime = segment.start + mediaOffset;
  26730. const seekedCallback = () => {
  26731. return callback(null, tech.currentTime());
  26732. }; // listen for seeked event
  26733. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  26734. if (pauseAfterSeek) {
  26735. tech.pause();
  26736. }
  26737. seekTo(seekToTime);
  26738. };
  26739. // which will only happen if the request is complete.
  26740. const callbackOnCompleted = (request, cb) => {
  26741. if (request.readyState === 4) {
  26742. return cb();
  26743. }
  26744. return;
  26745. };
  26746. const containerRequest = (uri, xhr, cb) => {
  26747. let bytes = [];
  26748. let id3Offset;
  26749. let finished = false;
  26750. const endRequestAndCallback = function (err, req, type, _bytes) {
  26751. req.abort();
  26752. finished = true;
  26753. return cb(err, req, type, _bytes);
  26754. };
  26755. const progressListener = function (error, request) {
  26756. if (finished) {
  26757. return;
  26758. }
  26759. if (error) {
  26760. return endRequestAndCallback(error, request, '', bytes);
  26761. } // grap the new part of content that was just downloaded
  26762. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  26763. bytes = byteHelpers.concatTypedArrays(bytes, byteHelpers.stringToBytes(newPart, true));
  26764. id3Offset = id3Offset || id3Helpers.getId3Offset(bytes); // we need at least 10 bytes to determine a type
  26765. // or we need at least two bytes after an id3Offset
  26766. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  26767. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26768. }
  26769. const type = containers.detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  26770. // to see the second sync byte, wait until we have enough data
  26771. // before declaring it ts
  26772. if (type === 'ts' && bytes.length < 188) {
  26773. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26774. } // this may be an unsynced ts segment
  26775. // wait for 376 bytes before detecting no container
  26776. if (!type && bytes.length < 376) {
  26777. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  26778. }
  26779. return endRequestAndCallback(null, request, type, bytes);
  26780. };
  26781. const options = {
  26782. uri,
  26783. beforeSend(request) {
  26784. // this forces the browser to pass the bytes to us unprocessed
  26785. request.overrideMimeType('text/plain; charset=x-user-defined');
  26786. request.addEventListener('progress', function ({
  26787. total,
  26788. loaded
  26789. }) {
  26790. return callbackWrapper(request, null, {
  26791. statusCode: request.status
  26792. }, progressListener);
  26793. });
  26794. }
  26795. };
  26796. const request = xhr(options, function (error, response) {
  26797. return callbackWrapper(request, error, response, progressListener);
  26798. });
  26799. return request;
  26800. };
  26801. const {
  26802. EventTarget
  26803. } = videojs;
  26804. const dashPlaylistUnchanged = function (a, b) {
  26805. if (!isPlaylistUnchanged(a, b)) {
  26806. return false;
  26807. } // for dash the above check will often return true in scenarios where
  26808. // the playlist actually has changed because mediaSequence isn't a
  26809. // dash thing, and we often set it to 1. So if the playlists have the same amount
  26810. // of segments we return true.
  26811. // So for dash we need to make sure that the underlying segments are different.
  26812. // if sidx changed then the playlists are different.
  26813. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  26814. return false;
  26815. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  26816. return false;
  26817. } // one or the other does not have segments
  26818. // there was a change.
  26819. if (a.segments && !b.segments || !a.segments && b.segments) {
  26820. return false;
  26821. } // neither has segments nothing changed
  26822. if (!a.segments && !b.segments) {
  26823. return true;
  26824. } // check segments themselves
  26825. for (let i = 0; i < a.segments.length; i++) {
  26826. const aSegment = a.segments[i];
  26827. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  26828. if (aSegment.uri !== bSegment.uri) {
  26829. return false;
  26830. } // neither segment has a byterange, there will be no byterange change.
  26831. if (!aSegment.byterange && !bSegment.byterange) {
  26832. continue;
  26833. }
  26834. const aByterange = aSegment.byterange;
  26835. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  26836. if (aByterange && !bByterange || !aByterange && bByterange) {
  26837. return false;
  26838. } // if both segments have byterange with different offsets, there was a change.
  26839. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  26840. return false;
  26841. }
  26842. } // if everything was the same with segments, this is the same playlist.
  26843. return true;
  26844. };
  26845. /**
  26846. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  26847. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  26848. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  26849. * periods without continuous playback this function may need modification as well as the parser.
  26850. */
  26851. const dashGroupId = (type, group, label, playlist) => {
  26852. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  26853. const playlistId = playlist.attributes.NAME || label;
  26854. return `placeholder-uri-${type}-${group}-${playlistId}`;
  26855. };
  26856. /**
  26857. * Parses the main XML string and updates playlist URI references.
  26858. *
  26859. * @param {Object} config
  26860. * Object of arguments
  26861. * @param {string} config.mainXml
  26862. * The mpd XML
  26863. * @param {string} config.srcUrl
  26864. * The mpd URL
  26865. * @param {Date} config.clientOffset
  26866. * A time difference between server and client
  26867. * @param {Object} config.sidxMapping
  26868. * SIDX mappings for moof/mdat URIs and byte ranges
  26869. * @return {Object}
  26870. * The parsed mpd manifest object
  26871. */
  26872. const parseMainXml = ({
  26873. mainXml,
  26874. srcUrl,
  26875. clientOffset,
  26876. sidxMapping,
  26877. previousManifest
  26878. }) => {
  26879. const manifest = mpdParser.parse(mainXml, {
  26880. manifestUri: srcUrl,
  26881. clientOffset,
  26882. sidxMapping,
  26883. previousManifest
  26884. });
  26885. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  26886. return manifest;
  26887. };
  26888. /**
  26889. * Removes any mediaGroup labels that no longer exist in the newMain
  26890. *
  26891. * @param {Object} update
  26892. * The previous mpd object being updated
  26893. * @param {Object} newMain
  26894. * The new mpd object
  26895. */
  26896. const removeOldMediaGroupLabels = (update, newMain) => {
  26897. forEachMediaGroup(update, (properties, type, group, label) => {
  26898. if (!(label in newMain.mediaGroups[type][group])) {
  26899. delete update.mediaGroups[type][group][label];
  26900. }
  26901. });
  26902. };
  26903. /**
  26904. * Returns a new main manifest that is the result of merging an updated main manifest
  26905. * into the original version.
  26906. *
  26907. * @param {Object} oldMain
  26908. * The old parsed mpd object
  26909. * @param {Object} newMain
  26910. * The updated parsed mpd object
  26911. * @return {Object}
  26912. * A new object representing the original main manifest with the updated media
  26913. * playlists merged in
  26914. */
  26915. const updateMain = (oldMain, newMain, sidxMapping) => {
  26916. let noChanges = true;
  26917. let update = merge(oldMain, {
  26918. // These are top level properties that can be updated
  26919. duration: newMain.duration,
  26920. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  26921. timelineStarts: newMain.timelineStarts
  26922. }); // First update the playlists in playlist list
  26923. for (let i = 0; i < newMain.playlists.length; i++) {
  26924. const playlist = newMain.playlists[i];
  26925. if (playlist.sidx) {
  26926. const sidxKey = mpdParser.generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  26927. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  26928. mpdParser.addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  26929. }
  26930. }
  26931. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  26932. if (playlistUpdate) {
  26933. update = playlistUpdate;
  26934. noChanges = false;
  26935. }
  26936. } // Then update media group playlists
  26937. forEachMediaGroup(newMain, (properties, type, group, label) => {
  26938. if (properties.playlists && properties.playlists.length) {
  26939. const id = properties.playlists[0].id;
  26940. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  26941. if (playlistUpdate) {
  26942. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  26943. if (!(label in update.mediaGroups[type][group])) {
  26944. update.mediaGroups[type][group][label] = properties;
  26945. } // update the playlist reference within media groups
  26946. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  26947. noChanges = false;
  26948. }
  26949. }
  26950. }); // remove mediaGroup labels and references that no longer exist in the newMain
  26951. removeOldMediaGroupLabels(update, newMain);
  26952. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  26953. noChanges = false;
  26954. }
  26955. if (noChanges) {
  26956. return null;
  26957. }
  26958. return update;
  26959. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  26960. // If the SIDXs have maps, the two maps should match,
  26961. // both `a` and `b` missing SIDXs is considered matching.
  26962. // If `a` or `b` but not both have a map, they aren't matching.
  26963. const equivalentSidx = (a, b) => {
  26964. const neitherMap = Boolean(!a.map && !b.map);
  26965. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  26966. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  26967. }; // exported for testing
  26968. const compareSidxEntry = (playlists, oldSidxMapping) => {
  26969. const newSidxMapping = {};
  26970. for (const id in playlists) {
  26971. const playlist = playlists[id];
  26972. const currentSidxInfo = playlist.sidx;
  26973. if (currentSidxInfo) {
  26974. const key = mpdParser.generateSidxKey(currentSidxInfo);
  26975. if (!oldSidxMapping[key]) {
  26976. break;
  26977. }
  26978. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  26979. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  26980. newSidxMapping[key] = oldSidxMapping[key];
  26981. }
  26982. }
  26983. }
  26984. return newSidxMapping;
  26985. };
  26986. /**
  26987. * A function that filters out changed items as they need to be requested separately.
  26988. *
  26989. * The method is exported for testing
  26990. *
  26991. * @param {Object} main the parsed mpd XML returned via mpd-parser
  26992. * @param {Object} oldSidxMapping the SIDX to compare against
  26993. */
  26994. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  26995. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  26996. let mediaGroupSidx = videoSidx;
  26997. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  26998. if (properties.playlists && properties.playlists.length) {
  26999. const playlists = properties.playlists;
  27000. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  27001. }
  27002. });
  27003. return mediaGroupSidx;
  27004. };
  27005. class DashPlaylistLoader extends EventTarget {
  27006. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  27007. // playlist loader setups from media groups will expect to be able to pass a playlist
  27008. // (since there aren't external URLs to media playlists with DASH)
  27009. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  27010. super();
  27011. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  27012. if (!mainPlaylistLoader) {
  27013. this.isMain_ = true;
  27014. }
  27015. const {
  27016. withCredentials = false
  27017. } = options;
  27018. this.vhs_ = vhs;
  27019. this.withCredentials = withCredentials;
  27020. if (!srcUrlOrPlaylist) {
  27021. throw new Error('A non-empty playlist URL or object is required');
  27022. } // event naming?
  27023. this.on('minimumUpdatePeriod', () => {
  27024. this.refreshXml_();
  27025. }); // live playlist staleness timeout
  27026. this.on('mediaupdatetimeout', () => {
  27027. this.refreshMedia_(this.media().id);
  27028. });
  27029. this.state = 'HAVE_NOTHING';
  27030. this.loadedPlaylists_ = {};
  27031. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  27032. // The mainPlaylistLoader will be created with a string
  27033. if (this.isMain_) {
  27034. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  27035. // once multi-period is refactored
  27036. this.mainPlaylistLoader_.sidxMapping_ = {};
  27037. } else {
  27038. this.childPlaylist_ = srcUrlOrPlaylist;
  27039. }
  27040. }
  27041. requestErrored_(err, request, startingState) {
  27042. // disposed
  27043. if (!this.request) {
  27044. return true;
  27045. } // pending request is cleared
  27046. this.request = null;
  27047. if (err) {
  27048. // use the provided error object or create one
  27049. // based on the request/response
  27050. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  27051. status: request.status,
  27052. message: 'DASH request error at URL: ' + request.uri,
  27053. response: request.response,
  27054. // MEDIA_ERR_NETWORK
  27055. code: 2
  27056. };
  27057. if (startingState) {
  27058. this.state = startingState;
  27059. }
  27060. this.trigger('error');
  27061. return true;
  27062. }
  27063. }
  27064. /**
  27065. * Verify that the container of the sidx segment can be parsed
  27066. * and if it can, get and parse that segment.
  27067. */
  27068. addSidxSegments_(playlist, startingState, cb) {
  27069. const sidxKey = playlist.sidx && mpdParser.generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  27070. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  27071. // keep this function async
  27072. this.mediaRequest_ = window__default["default"].setTimeout(() => cb(false), 0);
  27073. return;
  27074. } // resolve the segment URL relative to the playlist
  27075. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  27076. const fin = (err, request) => {
  27077. if (this.requestErrored_(err, request, startingState)) {
  27078. return;
  27079. }
  27080. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  27081. let sidx;
  27082. try {
  27083. sidx = parseSidx__default["default"](byteHelpers.toUint8(request.response).subarray(8));
  27084. } catch (e) {
  27085. // sidx parsing failed.
  27086. this.requestErrored_(e, request, startingState);
  27087. return;
  27088. }
  27089. sidxMapping[sidxKey] = {
  27090. sidxInfo: playlist.sidx,
  27091. sidx
  27092. };
  27093. mpdParser.addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  27094. return cb(true);
  27095. };
  27096. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  27097. if (err) {
  27098. return fin(err, request);
  27099. }
  27100. if (!container || container !== 'mp4') {
  27101. return fin({
  27102. status: request.status,
  27103. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  27104. // response is just bytes in this case
  27105. // but we really don't want to return that.
  27106. response: '',
  27107. playlist,
  27108. internal: true,
  27109. playlistExclusionDuration: Infinity,
  27110. // MEDIA_ERR_NETWORK
  27111. code: 2
  27112. }, request);
  27113. } // if we already downloaded the sidx bytes in the container request, use them
  27114. const {
  27115. offset,
  27116. length
  27117. } = playlist.sidx.byterange;
  27118. if (bytes.length >= length + offset) {
  27119. return fin(err, {
  27120. response: bytes.subarray(offset, offset + length),
  27121. status: request.status,
  27122. uri: request.uri
  27123. });
  27124. } // otherwise request sidx bytes
  27125. this.request = this.vhs_.xhr({
  27126. uri,
  27127. responseType: 'arraybuffer',
  27128. headers: segmentXhrHeaders({
  27129. byterange: playlist.sidx.byterange
  27130. })
  27131. }, fin);
  27132. });
  27133. }
  27134. dispose() {
  27135. this.trigger('dispose');
  27136. this.stopRequest();
  27137. this.loadedPlaylists_ = {};
  27138. window__default["default"].clearTimeout(this.minimumUpdatePeriodTimeout_);
  27139. window__default["default"].clearTimeout(this.mediaRequest_);
  27140. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  27141. this.mediaUpdateTimeout = null;
  27142. this.mediaRequest_ = null;
  27143. this.minimumUpdatePeriodTimeout_ = null;
  27144. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  27145. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  27146. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  27147. }
  27148. this.off();
  27149. }
  27150. hasPendingRequest() {
  27151. return this.request || this.mediaRequest_;
  27152. }
  27153. stopRequest() {
  27154. if (this.request) {
  27155. const oldRequest = this.request;
  27156. this.request = null;
  27157. oldRequest.onreadystatechange = null;
  27158. oldRequest.abort();
  27159. }
  27160. }
  27161. media(playlist) {
  27162. // getter
  27163. if (!playlist) {
  27164. return this.media_;
  27165. } // setter
  27166. if (this.state === 'HAVE_NOTHING') {
  27167. throw new Error('Cannot switch media playlist from ' + this.state);
  27168. }
  27169. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  27170. if (typeof playlist === 'string') {
  27171. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  27172. throw new Error('Unknown playlist URI: ' + playlist);
  27173. }
  27174. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  27175. }
  27176. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  27177. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  27178. this.state = 'HAVE_METADATA';
  27179. this.media_ = playlist; // trigger media change if the active media has been updated
  27180. if (mediaChange) {
  27181. this.trigger('mediachanging');
  27182. this.trigger('mediachange');
  27183. }
  27184. return;
  27185. } // switching to the active playlist is a no-op
  27186. if (!mediaChange) {
  27187. return;
  27188. } // switching from an already loaded playlist
  27189. if (this.media_) {
  27190. this.trigger('mediachanging');
  27191. }
  27192. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  27193. // everything is ready just continue to haveMetadata
  27194. this.haveMetadata({
  27195. startingState,
  27196. playlist
  27197. });
  27198. });
  27199. }
  27200. haveMetadata({
  27201. startingState,
  27202. playlist
  27203. }) {
  27204. this.state = 'HAVE_METADATA';
  27205. this.loadedPlaylists_[playlist.id] = playlist;
  27206. this.mediaRequest_ = null; // This will trigger loadedplaylist
  27207. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  27208. // to resolve setup of media groups
  27209. if (startingState === 'HAVE_MAIN_MANIFEST') {
  27210. this.trigger('loadedmetadata');
  27211. } else {
  27212. // trigger media change if the active media has been updated
  27213. this.trigger('mediachange');
  27214. }
  27215. }
  27216. pause() {
  27217. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  27218. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  27219. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  27220. }
  27221. this.stopRequest();
  27222. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  27223. this.mediaUpdateTimeout = null;
  27224. if (this.isMain_) {
  27225. window__default["default"].clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  27226. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  27227. }
  27228. if (this.state === 'HAVE_NOTHING') {
  27229. // If we pause the loader before any data has been retrieved, its as if we never
  27230. // started, so reset to an unstarted state.
  27231. this.started = false;
  27232. }
  27233. }
  27234. load(isFinalRendition) {
  27235. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  27236. this.mediaUpdateTimeout = null;
  27237. const media = this.media();
  27238. if (isFinalRendition) {
  27239. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  27240. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => this.load(), delay);
  27241. return;
  27242. } // because the playlists are internal to the manifest, load should either load the
  27243. // main manifest, or do nothing but trigger an event
  27244. if (!this.started) {
  27245. this.start();
  27246. return;
  27247. }
  27248. if (media && !media.endList) {
  27249. // Check to see if this is the main loader and the MUP was cleared (this happens
  27250. // when the loader was paused). `media` should be set at this point since one is always
  27251. // set during `start()`.
  27252. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  27253. // Trigger minimumUpdatePeriod to refresh the main manifest
  27254. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  27255. this.updateMinimumUpdatePeriodTimeout_();
  27256. }
  27257. this.trigger('mediaupdatetimeout');
  27258. } else {
  27259. this.trigger('loadedplaylist');
  27260. }
  27261. }
  27262. start() {
  27263. this.started = true; // We don't need to request the main manifest again
  27264. // Call this asynchronously to match the xhr request behavior below
  27265. if (!this.isMain_) {
  27266. this.mediaRequest_ = window__default["default"].setTimeout(() => this.haveMain_(), 0);
  27267. return;
  27268. }
  27269. this.requestMain_((req, mainChanged) => {
  27270. this.haveMain_();
  27271. if (!this.hasPendingRequest() && !this.media_) {
  27272. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  27273. }
  27274. });
  27275. }
  27276. requestMain_(cb) {
  27277. this.request = this.vhs_.xhr({
  27278. uri: this.mainPlaylistLoader_.srcUrl,
  27279. withCredentials: this.withCredentials
  27280. }, (error, req) => {
  27281. if (this.requestErrored_(error, req)) {
  27282. if (this.state === 'HAVE_NOTHING') {
  27283. this.started = false;
  27284. }
  27285. return;
  27286. }
  27287. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  27288. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  27289. if (req.responseHeaders && req.responseHeaders.date) {
  27290. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  27291. } else {
  27292. this.mainLoaded_ = Date.now();
  27293. }
  27294. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  27295. if (mainChanged) {
  27296. this.handleMain_();
  27297. this.syncClientServerClock_(() => {
  27298. return cb(req, mainChanged);
  27299. });
  27300. return;
  27301. }
  27302. return cb(req, mainChanged);
  27303. });
  27304. }
  27305. /**
  27306. * Parses the main xml for UTCTiming node to sync the client clock to the server
  27307. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  27308. *
  27309. * @param {Function} done
  27310. * Function to call when clock sync has completed
  27311. */
  27312. syncClientServerClock_(done) {
  27313. const utcTiming = mpdParser.parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  27314. // server clock
  27315. if (utcTiming === null) {
  27316. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  27317. return done();
  27318. }
  27319. if (utcTiming.method === 'DIRECT') {
  27320. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  27321. return done();
  27322. }
  27323. this.request = this.vhs_.xhr({
  27324. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  27325. method: utcTiming.method,
  27326. withCredentials: this.withCredentials
  27327. }, (error, req) => {
  27328. // disposed
  27329. if (!this.request) {
  27330. return;
  27331. }
  27332. if (error) {
  27333. // sync request failed, fall back to using date header from mpd
  27334. // TODO: log warning
  27335. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  27336. return done();
  27337. }
  27338. let serverTime;
  27339. if (utcTiming.method === 'HEAD') {
  27340. if (!req.responseHeaders || !req.responseHeaders.date) {
  27341. // expected date header not preset, fall back to using date header from mpd
  27342. // TODO: log warning
  27343. serverTime = this.mainLoaded_;
  27344. } else {
  27345. serverTime = Date.parse(req.responseHeaders.date);
  27346. }
  27347. } else {
  27348. serverTime = Date.parse(req.responseText);
  27349. }
  27350. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  27351. done();
  27352. });
  27353. }
  27354. haveMain_() {
  27355. this.state = 'HAVE_MAIN_MANIFEST';
  27356. if (this.isMain_) {
  27357. // We have the main playlist at this point, so
  27358. // trigger this to allow PlaylistController
  27359. // to make an initial playlist selection
  27360. this.trigger('loadedplaylist');
  27361. } else if (!this.media_) {
  27362. // no media playlist was specifically selected so select
  27363. // the one the child playlist loader was created with
  27364. this.media(this.childPlaylist_);
  27365. }
  27366. }
  27367. handleMain_() {
  27368. // clear media request
  27369. this.mediaRequest_ = null;
  27370. const oldMain = this.mainPlaylistLoader_.main;
  27371. let newMain = parseMainXml({
  27372. mainXml: this.mainPlaylistLoader_.mainXml_,
  27373. srcUrl: this.mainPlaylistLoader_.srcUrl,
  27374. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  27375. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  27376. previousManifest: oldMain
  27377. }); // if we have an old main to compare the new main against
  27378. if (oldMain) {
  27379. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  27380. } // only update main if we have a new main
  27381. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  27382. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  27383. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  27384. this.mainPlaylistLoader_.srcUrl = location;
  27385. }
  27386. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  27387. this.updateMinimumUpdatePeriodTimeout_();
  27388. }
  27389. return Boolean(newMain);
  27390. }
  27391. updateMinimumUpdatePeriodTimeout_() {
  27392. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  27393. // a new one will be added if needed.
  27394. if (mpl.createMupOnMedia_) {
  27395. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  27396. mpl.createMupOnMedia_ = null;
  27397. } // clear any pending timeouts
  27398. if (mpl.minimumUpdatePeriodTimeout_) {
  27399. window__default["default"].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  27400. mpl.minimumUpdatePeriodTimeout_ = null;
  27401. }
  27402. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  27403. // MPD has no future validity, so a new one will need to be acquired when new
  27404. // media segments are to be made available. Thus, we use the target duration
  27405. // in this case
  27406. if (mup === 0) {
  27407. if (mpl.media()) {
  27408. mup = mpl.media().targetDuration * 1000;
  27409. } else {
  27410. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  27411. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  27412. }
  27413. } // if minimumUpdatePeriod is invalid or <= zero, which
  27414. // can happen when a live video becomes VOD. skip timeout
  27415. // creation.
  27416. if (typeof mup !== 'number' || mup <= 0) {
  27417. if (mup < 0) {
  27418. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  27419. }
  27420. return;
  27421. }
  27422. this.createMUPTimeout_(mup);
  27423. }
  27424. createMUPTimeout_(mup) {
  27425. const mpl = this.mainPlaylistLoader_;
  27426. mpl.minimumUpdatePeriodTimeout_ = window__default["default"].setTimeout(() => {
  27427. mpl.minimumUpdatePeriodTimeout_ = null;
  27428. mpl.trigger('minimumUpdatePeriod');
  27429. mpl.createMUPTimeout_(mup);
  27430. }, mup);
  27431. }
  27432. /**
  27433. * Sends request to refresh the main xml and updates the parsed main manifest
  27434. */
  27435. refreshXml_() {
  27436. this.requestMain_((req, mainChanged) => {
  27437. if (!mainChanged) {
  27438. return;
  27439. }
  27440. if (this.media_) {
  27441. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  27442. } // This will filter out updated sidx info from the mapping
  27443. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  27444. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  27445. // TODO: do we need to reload the current playlist?
  27446. this.refreshMedia_(this.media().id);
  27447. });
  27448. });
  27449. }
  27450. /**
  27451. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  27452. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  27453. * from the main loader.
  27454. */
  27455. refreshMedia_(mediaID) {
  27456. if (!mediaID) {
  27457. throw new Error('refreshMedia_ must take a media id');
  27458. } // for main we have to reparse the main xml
  27459. // to re-create segments based on current timing values
  27460. // which may change media. We only skip updating the main manifest
  27461. // if this is the first time this.media_ is being set.
  27462. // as main was just parsed in that case.
  27463. if (this.media_ && this.isMain_) {
  27464. this.handleMain_();
  27465. }
  27466. const playlists = this.mainPlaylistLoader_.main.playlists;
  27467. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  27468. if (mediaChanged) {
  27469. this.media_ = playlists[mediaID];
  27470. } else {
  27471. this.trigger('playlistunchanged');
  27472. }
  27473. if (!this.mediaUpdateTimeout) {
  27474. const createMediaUpdateTimeout = () => {
  27475. if (this.media().endList) {
  27476. return;
  27477. }
  27478. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  27479. this.trigger('mediaupdatetimeout');
  27480. createMediaUpdateTimeout();
  27481. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  27482. };
  27483. createMediaUpdateTimeout();
  27484. }
  27485. this.trigger('loadedplaylist');
  27486. }
  27487. }
  27488. var Config = {
  27489. GOAL_BUFFER_LENGTH: 30,
  27490. MAX_GOAL_BUFFER_LENGTH: 60,
  27491. BACK_BUFFER_LENGTH: 30,
  27492. GOAL_BUFFER_LENGTH_RATE: 1,
  27493. // 0.5 MB/s
  27494. INITIAL_BANDWIDTH: 4194304,
  27495. // A fudge factor to apply to advertised playlist bitrates to account for
  27496. // temporary flucations in client bandwidth
  27497. BANDWIDTH_VARIANCE: 1.2,
  27498. // How much of the buffer must be filled before we consider upswitching
  27499. BUFFER_LOW_WATER_LINE: 0,
  27500. MAX_BUFFER_LOW_WATER_LINE: 30,
  27501. // TODO: Remove this when experimentalBufferBasedABR is removed
  27502. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  27503. BUFFER_LOW_WATER_LINE_RATE: 1,
  27504. // If the buffer is greater than the high water line, we won't switch down
  27505. BUFFER_HIGH_WATER_LINE: 30
  27506. };
  27507. const stringToArrayBuffer = string => {
  27508. const view = new Uint8Array(new ArrayBuffer(string.length));
  27509. for (let i = 0; i < string.length; i++) {
  27510. view[i] = string.charCodeAt(i);
  27511. }
  27512. return view.buffer;
  27513. };
  27514. /* global Blob, BlobBuilder, Worker */
  27515. // unify worker interface
  27516. const browserWorkerPolyFill = function (workerObj) {
  27517. // node only supports on/off
  27518. workerObj.on = workerObj.addEventListener;
  27519. workerObj.off = workerObj.removeEventListener;
  27520. return workerObj;
  27521. };
  27522. const createObjectURL = function (str) {
  27523. try {
  27524. return URL.createObjectURL(new Blob([str], {
  27525. type: 'application/javascript'
  27526. }));
  27527. } catch (e) {
  27528. const blob = new BlobBuilder();
  27529. blob.append(str);
  27530. return URL.createObjectURL(blob.getBlob());
  27531. }
  27532. };
  27533. const factory = function (code) {
  27534. return function () {
  27535. const objectUrl = createObjectURL(code);
  27536. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  27537. worker.objURL = objectUrl;
  27538. const terminate = worker.terminate;
  27539. worker.on = worker.addEventListener;
  27540. worker.off = worker.removeEventListener;
  27541. worker.terminate = function () {
  27542. URL.revokeObjectURL(objectUrl);
  27543. return terminate.call(this);
  27544. };
  27545. return worker;
  27546. };
  27547. };
  27548. const transform = function (code) {
  27549. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  27550. };
  27551. const getWorkerString = function (fn) {
  27552. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  27553. };
  27554. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  27555. const workerCode$1 = transform(getWorkerString(function () {
  27556. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  27557. /**
  27558. * mux.js
  27559. *
  27560. * Copyright (c) Brightcove
  27561. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  27562. *
  27563. * A lightweight readable stream implemention that handles event dispatching.
  27564. * Objects that inherit from streams should call init in their constructors.
  27565. */
  27566. var Stream$8 = function () {
  27567. this.init = function () {
  27568. var listeners = {};
  27569. /**
  27570. * Add a listener for a specified event type.
  27571. * @param type {string} the event name
  27572. * @param listener {function} the callback to be invoked when an event of
  27573. * the specified type occurs
  27574. */
  27575. this.on = function (type, listener) {
  27576. if (!listeners[type]) {
  27577. listeners[type] = [];
  27578. }
  27579. listeners[type] = listeners[type].concat(listener);
  27580. };
  27581. /**
  27582. * Remove a listener for a specified event type.
  27583. * @param type {string} the event name
  27584. * @param listener {function} a function previously registered for this
  27585. * type of event through `on`
  27586. */
  27587. this.off = function (type, listener) {
  27588. var index;
  27589. if (!listeners[type]) {
  27590. return false;
  27591. }
  27592. index = listeners[type].indexOf(listener);
  27593. listeners[type] = listeners[type].slice();
  27594. listeners[type].splice(index, 1);
  27595. return index > -1;
  27596. };
  27597. /**
  27598. * Trigger an event of the specified type on this stream. Any additional
  27599. * arguments to this function are passed as parameters to event listeners.
  27600. * @param type {string} the event name
  27601. */
  27602. this.trigger = function (type) {
  27603. var callbacks, i, length, args;
  27604. callbacks = listeners[type];
  27605. if (!callbacks) {
  27606. return;
  27607. } // Slicing the arguments on every invocation of this method
  27608. // can add a significant amount of overhead. Avoid the
  27609. // intermediate object creation for the common case of a
  27610. // single callback argument
  27611. if (arguments.length === 2) {
  27612. length = callbacks.length;
  27613. for (i = 0; i < length; ++i) {
  27614. callbacks[i].call(this, arguments[1]);
  27615. }
  27616. } else {
  27617. args = [];
  27618. i = arguments.length;
  27619. for (i = 1; i < arguments.length; ++i) {
  27620. args.push(arguments[i]);
  27621. }
  27622. length = callbacks.length;
  27623. for (i = 0; i < length; ++i) {
  27624. callbacks[i].apply(this, args);
  27625. }
  27626. }
  27627. };
  27628. /**
  27629. * Destroys the stream and cleans up.
  27630. */
  27631. this.dispose = function () {
  27632. listeners = {};
  27633. };
  27634. };
  27635. };
  27636. /**
  27637. * Forwards all `data` events on this stream to the destination stream. The
  27638. * destination stream should provide a method `push` to receive the data
  27639. * events as they arrive.
  27640. * @param destination {stream} the stream that will receive all `data` events
  27641. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  27642. * when the current stream emits a 'done' event
  27643. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  27644. */
  27645. Stream$8.prototype.pipe = function (destination) {
  27646. this.on('data', function (data) {
  27647. destination.push(data);
  27648. });
  27649. this.on('done', function (flushSource) {
  27650. destination.flush(flushSource);
  27651. });
  27652. this.on('partialdone', function (flushSource) {
  27653. destination.partialFlush(flushSource);
  27654. });
  27655. this.on('endedtimeline', function (flushSource) {
  27656. destination.endTimeline(flushSource);
  27657. });
  27658. this.on('reset', function (flushSource) {
  27659. destination.reset(flushSource);
  27660. });
  27661. return destination;
  27662. }; // Default stream functions that are expected to be overridden to perform
  27663. // actual work. These are provided by the prototype as a sort of no-op
  27664. // implementation so that we don't have to check for their existence in the
  27665. // `pipe` function above.
  27666. Stream$8.prototype.push = function (data) {
  27667. this.trigger('data', data);
  27668. };
  27669. Stream$8.prototype.flush = function (flushSource) {
  27670. this.trigger('done', flushSource);
  27671. };
  27672. Stream$8.prototype.partialFlush = function (flushSource) {
  27673. this.trigger('partialdone', flushSource);
  27674. };
  27675. Stream$8.prototype.endTimeline = function (flushSource) {
  27676. this.trigger('endedtimeline', flushSource);
  27677. };
  27678. Stream$8.prototype.reset = function (flushSource) {
  27679. this.trigger('reset', flushSource);
  27680. };
  27681. var stream = Stream$8;
  27682. var MAX_UINT32$1 = Math.pow(2, 32);
  27683. var getUint64$3 = function (uint8) {
  27684. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  27685. var value;
  27686. if (dv.getBigUint64) {
  27687. value = dv.getBigUint64(0);
  27688. if (value < Number.MAX_SAFE_INTEGER) {
  27689. return Number(value);
  27690. }
  27691. return value;
  27692. }
  27693. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  27694. };
  27695. var numbers = {
  27696. getUint64: getUint64$3,
  27697. MAX_UINT32: MAX_UINT32$1
  27698. };
  27699. /**
  27700. * mux.js
  27701. *
  27702. * Copyright (c) Brightcove
  27703. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  27704. *
  27705. * Functions that generate fragmented MP4s suitable for use with Media
  27706. * Source Extensions.
  27707. */
  27708. var MAX_UINT32 = numbers.MAX_UINT32;
  27709. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
  27710. (function () {
  27711. var i;
  27712. types = {
  27713. avc1: [],
  27714. // codingname
  27715. avcC: [],
  27716. btrt: [],
  27717. dinf: [],
  27718. dref: [],
  27719. esds: [],
  27720. ftyp: [],
  27721. hdlr: [],
  27722. mdat: [],
  27723. mdhd: [],
  27724. mdia: [],
  27725. mfhd: [],
  27726. minf: [],
  27727. moof: [],
  27728. moov: [],
  27729. mp4a: [],
  27730. // codingname
  27731. mvex: [],
  27732. mvhd: [],
  27733. pasp: [],
  27734. sdtp: [],
  27735. smhd: [],
  27736. stbl: [],
  27737. stco: [],
  27738. stsc: [],
  27739. stsd: [],
  27740. stsz: [],
  27741. stts: [],
  27742. styp: [],
  27743. tfdt: [],
  27744. tfhd: [],
  27745. traf: [],
  27746. trak: [],
  27747. trun: [],
  27748. trex: [],
  27749. tkhd: [],
  27750. vmhd: []
  27751. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  27752. // don't throw an error
  27753. if (typeof Uint8Array === 'undefined') {
  27754. return;
  27755. }
  27756. for (i in types) {
  27757. if (types.hasOwnProperty(i)) {
  27758. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  27759. }
  27760. }
  27761. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  27762. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  27763. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  27764. VIDEO_HDLR = new Uint8Array([0x00,
  27765. // version 0
  27766. 0x00, 0x00, 0x00,
  27767. // flags
  27768. 0x00, 0x00, 0x00, 0x00,
  27769. // pre_defined
  27770. 0x76, 0x69, 0x64, 0x65,
  27771. // handler_type: 'vide'
  27772. 0x00, 0x00, 0x00, 0x00,
  27773. // reserved
  27774. 0x00, 0x00, 0x00, 0x00,
  27775. // reserved
  27776. 0x00, 0x00, 0x00, 0x00,
  27777. // reserved
  27778. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  27779. ]);
  27780. AUDIO_HDLR = new Uint8Array([0x00,
  27781. // version 0
  27782. 0x00, 0x00, 0x00,
  27783. // flags
  27784. 0x00, 0x00, 0x00, 0x00,
  27785. // pre_defined
  27786. 0x73, 0x6f, 0x75, 0x6e,
  27787. // handler_type: 'soun'
  27788. 0x00, 0x00, 0x00, 0x00,
  27789. // reserved
  27790. 0x00, 0x00, 0x00, 0x00,
  27791. // reserved
  27792. 0x00, 0x00, 0x00, 0x00,
  27793. // reserved
  27794. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  27795. ]);
  27796. HDLR_TYPES = {
  27797. video: VIDEO_HDLR,
  27798. audio: AUDIO_HDLR
  27799. };
  27800. DREF = new Uint8Array([0x00,
  27801. // version 0
  27802. 0x00, 0x00, 0x00,
  27803. // flags
  27804. 0x00, 0x00, 0x00, 0x01,
  27805. // entry_count
  27806. 0x00, 0x00, 0x00, 0x0c,
  27807. // entry_size
  27808. 0x75, 0x72, 0x6c, 0x20,
  27809. // 'url' type
  27810. 0x00,
  27811. // version 0
  27812. 0x00, 0x00, 0x01 // entry_flags
  27813. ]);
  27814. SMHD = new Uint8Array([0x00,
  27815. // version
  27816. 0x00, 0x00, 0x00,
  27817. // flags
  27818. 0x00, 0x00,
  27819. // balance, 0 means centered
  27820. 0x00, 0x00 // reserved
  27821. ]);
  27822. STCO = new Uint8Array([0x00,
  27823. // version
  27824. 0x00, 0x00, 0x00,
  27825. // flags
  27826. 0x00, 0x00, 0x00, 0x00 // entry_count
  27827. ]);
  27828. STSC = STCO;
  27829. STSZ = new Uint8Array([0x00,
  27830. // version
  27831. 0x00, 0x00, 0x00,
  27832. // flags
  27833. 0x00, 0x00, 0x00, 0x00,
  27834. // sample_size
  27835. 0x00, 0x00, 0x00, 0x00 // sample_count
  27836. ]);
  27837. STTS = STCO;
  27838. VMHD = new Uint8Array([0x00,
  27839. // version
  27840. 0x00, 0x00, 0x01,
  27841. // flags
  27842. 0x00, 0x00,
  27843. // graphicsmode
  27844. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  27845. ]);
  27846. })();
  27847. box = function (type) {
  27848. var payload = [],
  27849. size = 0,
  27850. i,
  27851. result,
  27852. view;
  27853. for (i = 1; i < arguments.length; i++) {
  27854. payload.push(arguments[i]);
  27855. }
  27856. i = payload.length; // calculate the total size we need to allocate
  27857. while (i--) {
  27858. size += payload[i].byteLength;
  27859. }
  27860. result = new Uint8Array(size + 8);
  27861. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  27862. view.setUint32(0, result.byteLength);
  27863. result.set(type, 4); // copy the payload into the result
  27864. for (i = 0, size = 8; i < payload.length; i++) {
  27865. result.set(payload[i], size);
  27866. size += payload[i].byteLength;
  27867. }
  27868. return result;
  27869. };
  27870. dinf = function () {
  27871. return box(types.dinf, box(types.dref, DREF));
  27872. };
  27873. esds = function (track) {
  27874. return box(types.esds, new Uint8Array([0x00,
  27875. // version
  27876. 0x00, 0x00, 0x00,
  27877. // flags
  27878. // ES_Descriptor
  27879. 0x03,
  27880. // tag, ES_DescrTag
  27881. 0x19,
  27882. // length
  27883. 0x00, 0x00,
  27884. // ES_ID
  27885. 0x00,
  27886. // streamDependenceFlag, URL_flag, reserved, streamPriority
  27887. // DecoderConfigDescriptor
  27888. 0x04,
  27889. // tag, DecoderConfigDescrTag
  27890. 0x11,
  27891. // length
  27892. 0x40,
  27893. // object type
  27894. 0x15,
  27895. // streamType
  27896. 0x00, 0x06, 0x00,
  27897. // bufferSizeDB
  27898. 0x00, 0x00, 0xda, 0xc0,
  27899. // maxBitrate
  27900. 0x00, 0x00, 0xda, 0xc0,
  27901. // avgBitrate
  27902. // DecoderSpecificInfo
  27903. 0x05,
  27904. // tag, DecoderSpecificInfoTag
  27905. 0x02,
  27906. // length
  27907. // ISO/IEC 14496-3, AudioSpecificConfig
  27908. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  27909. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  27910. ]));
  27911. };
  27912. ftyp = function () {
  27913. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  27914. };
  27915. hdlr = function (type) {
  27916. return box(types.hdlr, HDLR_TYPES[type]);
  27917. };
  27918. mdat = function (data) {
  27919. return box(types.mdat, data);
  27920. };
  27921. mdhd = function (track) {
  27922. var result = new Uint8Array([0x00,
  27923. // version 0
  27924. 0x00, 0x00, 0x00,
  27925. // flags
  27926. 0x00, 0x00, 0x00, 0x02,
  27927. // creation_time
  27928. 0x00, 0x00, 0x00, 0x03,
  27929. // modification_time
  27930. 0x00, 0x01, 0x5f, 0x90,
  27931. // timescale, 90,000 "ticks" per second
  27932. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF,
  27933. // duration
  27934. 0x55, 0xc4,
  27935. // 'und' language (undetermined)
  27936. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  27937. // defined. The sample rate can be parsed out of an ADTS header, for
  27938. // instance.
  27939. if (track.samplerate) {
  27940. result[12] = track.samplerate >>> 24 & 0xFF;
  27941. result[13] = track.samplerate >>> 16 & 0xFF;
  27942. result[14] = track.samplerate >>> 8 & 0xFF;
  27943. result[15] = track.samplerate & 0xFF;
  27944. }
  27945. return box(types.mdhd, result);
  27946. };
  27947. mdia = function (track) {
  27948. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  27949. };
  27950. mfhd = function (sequenceNumber) {
  27951. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  27952. // flags
  27953. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  27954. ]));
  27955. };
  27956. minf = function (track) {
  27957. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  27958. };
  27959. moof = function (sequenceNumber, tracks) {
  27960. var trackFragments = [],
  27961. i = tracks.length; // build traf boxes for each track fragment
  27962. while (i--) {
  27963. trackFragments[i] = traf(tracks[i]);
  27964. }
  27965. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  27966. };
  27967. /**
  27968. * Returns a movie box.
  27969. * @param tracks {array} the tracks associated with this movie
  27970. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  27971. */
  27972. moov = function (tracks) {
  27973. var i = tracks.length,
  27974. boxes = [];
  27975. while (i--) {
  27976. boxes[i] = trak(tracks[i]);
  27977. }
  27978. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  27979. };
  27980. mvex = function (tracks) {
  27981. var i = tracks.length,
  27982. boxes = [];
  27983. while (i--) {
  27984. boxes[i] = trex(tracks[i]);
  27985. }
  27986. return box.apply(null, [types.mvex].concat(boxes));
  27987. };
  27988. mvhd = function (duration) {
  27989. var bytes = new Uint8Array([0x00,
  27990. // version 0
  27991. 0x00, 0x00, 0x00,
  27992. // flags
  27993. 0x00, 0x00, 0x00, 0x01,
  27994. // creation_time
  27995. 0x00, 0x00, 0x00, 0x02,
  27996. // modification_time
  27997. 0x00, 0x01, 0x5f, 0x90,
  27998. // timescale, 90,000 "ticks" per second
  27999. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF,
  28000. // duration
  28001. 0x00, 0x01, 0x00, 0x00,
  28002. // 1.0 rate
  28003. 0x01, 0x00,
  28004. // 1.0 volume
  28005. 0x00, 0x00,
  28006. // reserved
  28007. 0x00, 0x00, 0x00, 0x00,
  28008. // reserved
  28009. 0x00, 0x00, 0x00, 0x00,
  28010. // reserved
  28011. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  28012. // transformation: unity matrix
  28013. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28014. // pre_defined
  28015. 0xff, 0xff, 0xff, 0xff // next_track_ID
  28016. ]);
  28017. return box(types.mvhd, bytes);
  28018. };
  28019. sdtp = function (track) {
  28020. var samples = track.samples || [],
  28021. bytes = new Uint8Array(4 + samples.length),
  28022. flags,
  28023. i; // leave the full box header (4 bytes) all zero
  28024. // write the sample table
  28025. for (i = 0; i < samples.length; i++) {
  28026. flags = samples[i].flags;
  28027. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  28028. }
  28029. return box(types.sdtp, bytes);
  28030. };
  28031. stbl = function (track) {
  28032. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  28033. };
  28034. (function () {
  28035. var videoSample, audioSample;
  28036. stsd = function (track) {
  28037. return box(types.stsd, new Uint8Array([0x00,
  28038. // version 0
  28039. 0x00, 0x00, 0x00,
  28040. // flags
  28041. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  28042. };
  28043. videoSample = function (track) {
  28044. var sps = track.sps || [],
  28045. pps = track.pps || [],
  28046. sequenceParameterSets = [],
  28047. pictureParameterSets = [],
  28048. i,
  28049. avc1Box; // assemble the SPSs
  28050. for (i = 0; i < sps.length; i++) {
  28051. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  28052. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  28053. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  28054. } // assemble the PPSs
  28055. for (i = 0; i < pps.length; i++) {
  28056. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  28057. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  28058. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  28059. }
  28060. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28061. // reserved
  28062. 0x00, 0x01,
  28063. // data_reference_index
  28064. 0x00, 0x00,
  28065. // pre_defined
  28066. 0x00, 0x00,
  28067. // reserved
  28068. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28069. // pre_defined
  28070. (track.width & 0xff00) >> 8, track.width & 0xff,
  28071. // width
  28072. (track.height & 0xff00) >> 8, track.height & 0xff,
  28073. // height
  28074. 0x00, 0x48, 0x00, 0x00,
  28075. // horizresolution
  28076. 0x00, 0x48, 0x00, 0x00,
  28077. // vertresolution
  28078. 0x00, 0x00, 0x00, 0x00,
  28079. // reserved
  28080. 0x00, 0x01,
  28081. // frame_count
  28082. 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28083. // compressorname
  28084. 0x00, 0x18,
  28085. // depth = 24
  28086. 0x11, 0x11 // pre_defined = -1
  28087. ]), box(types.avcC, new Uint8Array([0x01,
  28088. // configurationVersion
  28089. track.profileIdc,
  28090. // AVCProfileIndication
  28091. track.profileCompatibility,
  28092. // profile_compatibility
  28093. track.levelIdc,
  28094. // AVCLevelIndication
  28095. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  28096. ].concat([sps.length],
  28097. // numOfSequenceParameterSets
  28098. sequenceParameterSets,
  28099. // "SPS"
  28100. [pps.length],
  28101. // numOfPictureParameterSets
  28102. pictureParameterSets // "PPS"
  28103. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  28104. // bufferSizeDB
  28105. 0x00, 0x2d, 0xc6, 0xc0,
  28106. // maxBitrate
  28107. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  28108. ]))];
  28109. if (track.sarRatio) {
  28110. var hSpacing = track.sarRatio[0],
  28111. vSpacing = track.sarRatio[1];
  28112. avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
  28113. }
  28114. return box.apply(null, avc1Box);
  28115. };
  28116. audioSample = function (track) {
  28117. return box(types.mp4a, new Uint8Array([
  28118. // SampleEntry, ISO/IEC 14496-12
  28119. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28120. // reserved
  28121. 0x00, 0x01,
  28122. // data_reference_index
  28123. // AudioSampleEntry, ISO/IEC 14496-12
  28124. 0x00, 0x00, 0x00, 0x00,
  28125. // reserved
  28126. 0x00, 0x00, 0x00, 0x00,
  28127. // reserved
  28128. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff,
  28129. // channelcount
  28130. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff,
  28131. // samplesize
  28132. 0x00, 0x00,
  28133. // pre_defined
  28134. 0x00, 0x00,
  28135. // reserved
  28136. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  28137. // MP4AudioSampleEntry, ISO/IEC 14496-14
  28138. ]), esds(track));
  28139. };
  28140. })();
  28141. tkhd = function (track) {
  28142. var result = new Uint8Array([0x00,
  28143. // version 0
  28144. 0x00, 0x00, 0x07,
  28145. // flags
  28146. 0x00, 0x00, 0x00, 0x00,
  28147. // creation_time
  28148. 0x00, 0x00, 0x00, 0x00,
  28149. // modification_time
  28150. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28151. // track_ID
  28152. 0x00, 0x00, 0x00, 0x00,
  28153. // reserved
  28154. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF,
  28155. // duration
  28156. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  28157. // reserved
  28158. 0x00, 0x00,
  28159. // layer
  28160. 0x00, 0x00,
  28161. // alternate_group
  28162. 0x01, 0x00,
  28163. // non-audio track volume
  28164. 0x00, 0x00,
  28165. // reserved
  28166. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  28167. // transformation: unity matrix
  28168. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00,
  28169. // width
  28170. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  28171. ]);
  28172. return box(types.tkhd, result);
  28173. };
  28174. /**
  28175. * Generate a track fragment (traf) box. A traf box collects metadata
  28176. * about tracks in a movie fragment (moof) box.
  28177. */
  28178. traf = function (track) {
  28179. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  28180. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00,
  28181. // version 0
  28182. 0x00, 0x00, 0x3a,
  28183. // flags
  28184. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28185. // track_ID
  28186. 0x00, 0x00, 0x00, 0x01,
  28187. // sample_description_index
  28188. 0x00, 0x00, 0x00, 0x00,
  28189. // default_sample_duration
  28190. 0x00, 0x00, 0x00, 0x00,
  28191. // default_sample_size
  28192. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  28193. ]));
  28194. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  28195. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  28196. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01,
  28197. // version 1
  28198. 0x00, 0x00, 0x00,
  28199. // flags
  28200. // baseMediaDecodeTime
  28201. upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
  28202. // the containing moof to the first payload byte of the associated
  28203. // mdat
  28204. dataOffset = 32 +
  28205. // tfhd
  28206. 20 +
  28207. // tfdt
  28208. 8 +
  28209. // traf header
  28210. 16 +
  28211. // mfhd
  28212. 8 +
  28213. // moof header
  28214. 8; // mdat header
  28215. // audio tracks require less metadata
  28216. if (track.type === 'audio') {
  28217. trackFragmentRun = trun$1(track, dataOffset);
  28218. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  28219. } // video tracks should contain an independent and disposable samples
  28220. // box (sdtp)
  28221. // generate one and adjust offsets to match
  28222. sampleDependencyTable = sdtp(track);
  28223. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  28224. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  28225. };
  28226. /**
  28227. * Generate a track box.
  28228. * @param track {object} a track definition
  28229. * @return {Uint8Array} the track box
  28230. */
  28231. trak = function (track) {
  28232. track.duration = track.duration || 0xffffffff;
  28233. return box(types.trak, tkhd(track), mdia(track));
  28234. };
  28235. trex = function (track) {
  28236. var result = new Uint8Array([0x00,
  28237. // version 0
  28238. 0x00, 0x00, 0x00,
  28239. // flags
  28240. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF,
  28241. // track_ID
  28242. 0x00, 0x00, 0x00, 0x01,
  28243. // default_sample_description_index
  28244. 0x00, 0x00, 0x00, 0x00,
  28245. // default_sample_duration
  28246. 0x00, 0x00, 0x00, 0x00,
  28247. // default_sample_size
  28248. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  28249. ]); // the last two bytes of default_sample_flags is the sample
  28250. // degradation priority, a hint about the importance of this sample
  28251. // relative to others. Lower the degradation priority for all sample
  28252. // types other than video.
  28253. if (track.type !== 'video') {
  28254. result[result.length - 1] = 0x00;
  28255. }
  28256. return box(types.trex, result);
  28257. };
  28258. (function () {
  28259. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  28260. // duration is present for the first sample, it will be present for
  28261. // all subsequent samples.
  28262. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  28263. trunHeader = function (samples, offset) {
  28264. var durationPresent = 0,
  28265. sizePresent = 0,
  28266. flagsPresent = 0,
  28267. compositionTimeOffset = 0; // trun flag constants
  28268. if (samples.length) {
  28269. if (samples[0].duration !== undefined) {
  28270. durationPresent = 0x1;
  28271. }
  28272. if (samples[0].size !== undefined) {
  28273. sizePresent = 0x2;
  28274. }
  28275. if (samples[0].flags !== undefined) {
  28276. flagsPresent = 0x4;
  28277. }
  28278. if (samples[0].compositionTimeOffset !== undefined) {
  28279. compositionTimeOffset = 0x8;
  28280. }
  28281. }
  28282. return [0x00,
  28283. // version 0
  28284. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01,
  28285. // flags
  28286. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF,
  28287. // sample_count
  28288. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  28289. ];
  28290. };
  28291. videoTrun = function (track, offset) {
  28292. var bytesOffest, bytes, header, samples, sample, i;
  28293. samples = track.samples || [];
  28294. offset += 8 + 12 + 16 * samples.length;
  28295. header = trunHeader(samples, offset);
  28296. bytes = new Uint8Array(header.length + samples.length * 16);
  28297. bytes.set(header);
  28298. bytesOffest = header.length;
  28299. for (i = 0; i < samples.length; i++) {
  28300. sample = samples[i];
  28301. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28302. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28303. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28304. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28305. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28306. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28307. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28308. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28309. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  28310. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  28311. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  28312. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  28313. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  28314. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  28315. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  28316. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  28317. }
  28318. return box(types.trun, bytes);
  28319. };
  28320. audioTrun = function (track, offset) {
  28321. var bytes, bytesOffest, header, samples, sample, i;
  28322. samples = track.samples || [];
  28323. offset += 8 + 12 + 8 * samples.length;
  28324. header = trunHeader(samples, offset);
  28325. bytes = new Uint8Array(header.length + samples.length * 8);
  28326. bytes.set(header);
  28327. bytesOffest = header.length;
  28328. for (i = 0; i < samples.length; i++) {
  28329. sample = samples[i];
  28330. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28331. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28332. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28333. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28334. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28335. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28336. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28337. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28338. }
  28339. return box(types.trun, bytes);
  28340. };
  28341. trun$1 = function (track, offset) {
  28342. if (track.type === 'audio') {
  28343. return audioTrun(track, offset);
  28344. }
  28345. return videoTrun(track, offset);
  28346. };
  28347. })();
  28348. var mp4Generator = {
  28349. ftyp: ftyp,
  28350. mdat: mdat,
  28351. moof: moof,
  28352. moov: moov,
  28353. initSegment: function (tracks) {
  28354. var fileType = ftyp(),
  28355. movie = moov(tracks),
  28356. result;
  28357. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  28358. result.set(fileType);
  28359. result.set(movie, fileType.byteLength);
  28360. return result;
  28361. }
  28362. };
  28363. /**
  28364. * mux.js
  28365. *
  28366. * Copyright (c) Brightcove
  28367. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28368. */
  28369. // composed of the nal units that make up that frame
  28370. // Also keep track of cummulative data about the frame from the nal units such
  28371. // as the frame duration, starting pts, etc.
  28372. var groupNalsIntoFrames = function (nalUnits) {
  28373. var i,
  28374. currentNal,
  28375. currentFrame = [],
  28376. frames = []; // TODO added for LHLS, make sure this is OK
  28377. frames.byteLength = 0;
  28378. frames.nalCount = 0;
  28379. frames.duration = 0;
  28380. currentFrame.byteLength = 0;
  28381. for (i = 0; i < nalUnits.length; i++) {
  28382. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  28383. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  28384. // Since the very first nal unit is expected to be an AUD
  28385. // only push to the frames array when currentFrame is not empty
  28386. if (currentFrame.length) {
  28387. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  28388. frames.byteLength += currentFrame.byteLength;
  28389. frames.nalCount += currentFrame.length;
  28390. frames.duration += currentFrame.duration;
  28391. frames.push(currentFrame);
  28392. }
  28393. currentFrame = [currentNal];
  28394. currentFrame.byteLength = currentNal.data.byteLength;
  28395. currentFrame.pts = currentNal.pts;
  28396. currentFrame.dts = currentNal.dts;
  28397. } else {
  28398. // Specifically flag key frames for ease of use later
  28399. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  28400. currentFrame.keyFrame = true;
  28401. }
  28402. currentFrame.duration = currentNal.dts - currentFrame.dts;
  28403. currentFrame.byteLength += currentNal.data.byteLength;
  28404. currentFrame.push(currentNal);
  28405. }
  28406. } // For the last frame, use the duration of the previous frame if we
  28407. // have nothing better to go on
  28408. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  28409. currentFrame.duration = frames[frames.length - 1].duration;
  28410. } // Push the final frame
  28411. // TODO added for LHLS, make sure this is OK
  28412. frames.byteLength += currentFrame.byteLength;
  28413. frames.nalCount += currentFrame.length;
  28414. frames.duration += currentFrame.duration;
  28415. frames.push(currentFrame);
  28416. return frames;
  28417. }; // Convert an array of frames into an array of Gop with each Gop being composed
  28418. // of the frames that make up that Gop
  28419. // Also keep track of cummulative data about the Gop from the frames such as the
  28420. // Gop duration, starting pts, etc.
  28421. var groupFramesIntoGops = function (frames) {
  28422. var i,
  28423. currentFrame,
  28424. currentGop = [],
  28425. gops = []; // We must pre-set some of the values on the Gop since we
  28426. // keep running totals of these values
  28427. currentGop.byteLength = 0;
  28428. currentGop.nalCount = 0;
  28429. currentGop.duration = 0;
  28430. currentGop.pts = frames[0].pts;
  28431. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  28432. gops.byteLength = 0;
  28433. gops.nalCount = 0;
  28434. gops.duration = 0;
  28435. gops.pts = frames[0].pts;
  28436. gops.dts = frames[0].dts;
  28437. for (i = 0; i < frames.length; i++) {
  28438. currentFrame = frames[i];
  28439. if (currentFrame.keyFrame) {
  28440. // Since the very first frame is expected to be an keyframe
  28441. // only push to the gops array when currentGop is not empty
  28442. if (currentGop.length) {
  28443. gops.push(currentGop);
  28444. gops.byteLength += currentGop.byteLength;
  28445. gops.nalCount += currentGop.nalCount;
  28446. gops.duration += currentGop.duration;
  28447. }
  28448. currentGop = [currentFrame];
  28449. currentGop.nalCount = currentFrame.length;
  28450. currentGop.byteLength = currentFrame.byteLength;
  28451. currentGop.pts = currentFrame.pts;
  28452. currentGop.dts = currentFrame.dts;
  28453. currentGop.duration = currentFrame.duration;
  28454. } else {
  28455. currentGop.duration += currentFrame.duration;
  28456. currentGop.nalCount += currentFrame.length;
  28457. currentGop.byteLength += currentFrame.byteLength;
  28458. currentGop.push(currentFrame);
  28459. }
  28460. }
  28461. if (gops.length && currentGop.duration <= 0) {
  28462. currentGop.duration = gops[gops.length - 1].duration;
  28463. }
  28464. gops.byteLength += currentGop.byteLength;
  28465. gops.nalCount += currentGop.nalCount;
  28466. gops.duration += currentGop.duration; // push the final Gop
  28467. gops.push(currentGop);
  28468. return gops;
  28469. };
  28470. /*
  28471. * Search for the first keyframe in the GOPs and throw away all frames
  28472. * until that keyframe. Then extend the duration of the pulled keyframe
  28473. * and pull the PTS and DTS of the keyframe so that it covers the time
  28474. * range of the frames that were disposed.
  28475. *
  28476. * @param {Array} gops video GOPs
  28477. * @returns {Array} modified video GOPs
  28478. */
  28479. var extendFirstKeyFrame = function (gops) {
  28480. var currentGop;
  28481. if (!gops[0][0].keyFrame && gops.length > 1) {
  28482. // Remove the first GOP
  28483. currentGop = gops.shift();
  28484. gops.byteLength -= currentGop.byteLength;
  28485. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  28486. // first gop to cover the time period of the
  28487. // frames we just removed
  28488. gops[0][0].dts = currentGop.dts;
  28489. gops[0][0].pts = currentGop.pts;
  28490. gops[0][0].duration += currentGop.duration;
  28491. }
  28492. return gops;
  28493. };
  28494. /**
  28495. * Default sample object
  28496. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  28497. */
  28498. var createDefaultSample = function () {
  28499. return {
  28500. size: 0,
  28501. flags: {
  28502. isLeading: 0,
  28503. dependsOn: 1,
  28504. isDependedOn: 0,
  28505. hasRedundancy: 0,
  28506. degradationPriority: 0,
  28507. isNonSyncSample: 1
  28508. }
  28509. };
  28510. };
  28511. /*
  28512. * Collates information from a video frame into an object for eventual
  28513. * entry into an MP4 sample table.
  28514. *
  28515. * @param {Object} frame the video frame
  28516. * @param {Number} dataOffset the byte offset to position the sample
  28517. * @return {Object} object containing sample table info for a frame
  28518. */
  28519. var sampleForFrame = function (frame, dataOffset) {
  28520. var sample = createDefaultSample();
  28521. sample.dataOffset = dataOffset;
  28522. sample.compositionTimeOffset = frame.pts - frame.dts;
  28523. sample.duration = frame.duration;
  28524. sample.size = 4 * frame.length; // Space for nal unit size
  28525. sample.size += frame.byteLength;
  28526. if (frame.keyFrame) {
  28527. sample.flags.dependsOn = 2;
  28528. sample.flags.isNonSyncSample = 0;
  28529. }
  28530. return sample;
  28531. }; // generate the track's sample table from an array of gops
  28532. var generateSampleTable$1 = function (gops, baseDataOffset) {
  28533. var h,
  28534. i,
  28535. sample,
  28536. currentGop,
  28537. currentFrame,
  28538. dataOffset = baseDataOffset || 0,
  28539. samples = [];
  28540. for (h = 0; h < gops.length; h++) {
  28541. currentGop = gops[h];
  28542. for (i = 0; i < currentGop.length; i++) {
  28543. currentFrame = currentGop[i];
  28544. sample = sampleForFrame(currentFrame, dataOffset);
  28545. dataOffset += sample.size;
  28546. samples.push(sample);
  28547. }
  28548. }
  28549. return samples;
  28550. }; // generate the track's raw mdat data from an array of gops
  28551. var concatenateNalData = function (gops) {
  28552. var h,
  28553. i,
  28554. j,
  28555. currentGop,
  28556. currentFrame,
  28557. currentNal,
  28558. dataOffset = 0,
  28559. nalsByteLength = gops.byteLength,
  28560. numberOfNals = gops.nalCount,
  28561. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28562. data = new Uint8Array(totalByteLength),
  28563. view = new DataView(data.buffer); // For each Gop..
  28564. for (h = 0; h < gops.length; h++) {
  28565. currentGop = gops[h]; // For each Frame..
  28566. for (i = 0; i < currentGop.length; i++) {
  28567. currentFrame = currentGop[i]; // For each NAL..
  28568. for (j = 0; j < currentFrame.length; j++) {
  28569. currentNal = currentFrame[j];
  28570. view.setUint32(dataOffset, currentNal.data.byteLength);
  28571. dataOffset += 4;
  28572. data.set(currentNal.data, dataOffset);
  28573. dataOffset += currentNal.data.byteLength;
  28574. }
  28575. }
  28576. }
  28577. return data;
  28578. }; // generate the track's sample table from a frame
  28579. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  28580. var sample,
  28581. dataOffset = baseDataOffset || 0,
  28582. samples = [];
  28583. sample = sampleForFrame(frame, dataOffset);
  28584. samples.push(sample);
  28585. return samples;
  28586. }; // generate the track's raw mdat data from a frame
  28587. var concatenateNalDataForFrame = function (frame) {
  28588. var i,
  28589. currentNal,
  28590. dataOffset = 0,
  28591. nalsByteLength = frame.byteLength,
  28592. numberOfNals = frame.length,
  28593. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28594. data = new Uint8Array(totalByteLength),
  28595. view = new DataView(data.buffer); // For each NAL..
  28596. for (i = 0; i < frame.length; i++) {
  28597. currentNal = frame[i];
  28598. view.setUint32(dataOffset, currentNal.data.byteLength);
  28599. dataOffset += 4;
  28600. data.set(currentNal.data, dataOffset);
  28601. dataOffset += currentNal.data.byteLength;
  28602. }
  28603. return data;
  28604. };
  28605. var frameUtils$1 = {
  28606. groupNalsIntoFrames: groupNalsIntoFrames,
  28607. groupFramesIntoGops: groupFramesIntoGops,
  28608. extendFirstKeyFrame: extendFirstKeyFrame,
  28609. generateSampleTable: generateSampleTable$1,
  28610. concatenateNalData: concatenateNalData,
  28611. generateSampleTableForFrame: generateSampleTableForFrame,
  28612. concatenateNalDataForFrame: concatenateNalDataForFrame
  28613. };
  28614. /**
  28615. * mux.js
  28616. *
  28617. * Copyright (c) Brightcove
  28618. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28619. */
  28620. var highPrefix = [33, 16, 5, 32, 164, 27];
  28621. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  28622. var zeroFill = function (count) {
  28623. var a = [];
  28624. while (count--) {
  28625. a.push(0);
  28626. }
  28627. return a;
  28628. };
  28629. var makeTable = function (metaTable) {
  28630. return Object.keys(metaTable).reduce(function (obj, key) {
  28631. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  28632. return arr.concat(part);
  28633. }, []));
  28634. return obj;
  28635. }, {});
  28636. };
  28637. var silence;
  28638. var silence_1 = function () {
  28639. if (!silence) {
  28640. // Frames-of-silence to use for filling in missing AAC frames
  28641. var coneOfSilence = {
  28642. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  28643. 88200: [highPrefix, [231], zeroFill(170), [56]],
  28644. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  28645. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  28646. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  28647. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  28648. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  28649. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  28650. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  28651. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  28652. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  28653. };
  28654. silence = makeTable(coneOfSilence);
  28655. }
  28656. return silence;
  28657. };
  28658. /**
  28659. * mux.js
  28660. *
  28661. * Copyright (c) Brightcove
  28662. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28663. */
  28664. var ONE_SECOND_IN_TS$4 = 90000,
  28665. // 90kHz clock
  28666. secondsToVideoTs,
  28667. secondsToAudioTs,
  28668. videoTsToSeconds,
  28669. audioTsToSeconds,
  28670. audioTsToVideoTs,
  28671. videoTsToAudioTs,
  28672. metadataTsToSeconds;
  28673. secondsToVideoTs = function (seconds) {
  28674. return seconds * ONE_SECOND_IN_TS$4;
  28675. };
  28676. secondsToAudioTs = function (seconds, sampleRate) {
  28677. return seconds * sampleRate;
  28678. };
  28679. videoTsToSeconds = function (timestamp) {
  28680. return timestamp / ONE_SECOND_IN_TS$4;
  28681. };
  28682. audioTsToSeconds = function (timestamp, sampleRate) {
  28683. return timestamp / sampleRate;
  28684. };
  28685. audioTsToVideoTs = function (timestamp, sampleRate) {
  28686. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  28687. };
  28688. videoTsToAudioTs = function (timestamp, sampleRate) {
  28689. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  28690. };
  28691. /**
  28692. * Adjust ID3 tag or caption timing information by the timeline pts values
  28693. * (if keepOriginalTimestamps is false) and convert to seconds
  28694. */
  28695. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  28696. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  28697. };
  28698. var clock$2 = {
  28699. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  28700. secondsToVideoTs: secondsToVideoTs,
  28701. secondsToAudioTs: secondsToAudioTs,
  28702. videoTsToSeconds: videoTsToSeconds,
  28703. audioTsToSeconds: audioTsToSeconds,
  28704. audioTsToVideoTs: audioTsToVideoTs,
  28705. videoTsToAudioTs: videoTsToAudioTs,
  28706. metadataTsToSeconds: metadataTsToSeconds
  28707. };
  28708. /**
  28709. * mux.js
  28710. *
  28711. * Copyright (c) Brightcove
  28712. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28713. */
  28714. var coneOfSilence = silence_1;
  28715. var clock$1 = clock$2;
  28716. /**
  28717. * Sum the `byteLength` properties of the data in each AAC frame
  28718. */
  28719. var sumFrameByteLengths = function (array) {
  28720. var i,
  28721. currentObj,
  28722. sum = 0; // sum the byteLength's all each nal unit in the frame
  28723. for (i = 0; i < array.length; i++) {
  28724. currentObj = array[i];
  28725. sum += currentObj.data.byteLength;
  28726. }
  28727. return sum;
  28728. }; // Possibly pad (prefix) the audio track with silence if appending this track
  28729. // would lead to the introduction of a gap in the audio buffer
  28730. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  28731. var baseMediaDecodeTimeTs,
  28732. frameDuration = 0,
  28733. audioGapDuration = 0,
  28734. audioFillFrameCount = 0,
  28735. audioFillDuration = 0,
  28736. silentFrame,
  28737. i,
  28738. firstFrame;
  28739. if (!frames.length) {
  28740. return;
  28741. }
  28742. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  28743. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  28744. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  28745. // insert the shortest possible amount (audio gap or audio to video gap)
  28746. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  28747. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  28748. audioFillDuration = audioFillFrameCount * frameDuration;
  28749. } // don't attempt to fill gaps smaller than a single frame or larger
  28750. // than a half second
  28751. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  28752. return;
  28753. }
  28754. silentFrame = coneOfSilence()[track.samplerate];
  28755. if (!silentFrame) {
  28756. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  28757. // from the content instead
  28758. silentFrame = frames[0].data;
  28759. }
  28760. for (i = 0; i < audioFillFrameCount; i++) {
  28761. firstFrame = frames[0];
  28762. frames.splice(0, 0, {
  28763. data: silentFrame,
  28764. dts: firstFrame.dts - frameDuration,
  28765. pts: firstFrame.pts - frameDuration
  28766. });
  28767. }
  28768. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  28769. return audioFillDuration;
  28770. }; // If the audio segment extends before the earliest allowed dts
  28771. // value, remove AAC frames until starts at or after the earliest
  28772. // allowed DTS so that we don't end up with a negative baseMedia-
  28773. // DecodeTime for the audio track
  28774. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  28775. if (track.minSegmentDts >= earliestAllowedDts) {
  28776. return adtsFrames;
  28777. } // We will need to recalculate the earliest segment Dts
  28778. track.minSegmentDts = Infinity;
  28779. return adtsFrames.filter(function (currentFrame) {
  28780. // If this is an allowed frame, keep it and record it's Dts
  28781. if (currentFrame.dts >= earliestAllowedDts) {
  28782. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  28783. track.minSegmentPts = track.minSegmentDts;
  28784. return true;
  28785. } // Otherwise, discard it
  28786. return false;
  28787. });
  28788. }; // generate the track's raw mdat data from an array of frames
  28789. var generateSampleTable = function (frames) {
  28790. var i,
  28791. currentFrame,
  28792. samples = [];
  28793. for (i = 0; i < frames.length; i++) {
  28794. currentFrame = frames[i];
  28795. samples.push({
  28796. size: currentFrame.data.byteLength,
  28797. duration: 1024 // For AAC audio, all samples contain 1024 samples
  28798. });
  28799. }
  28800. return samples;
  28801. }; // generate the track's sample table from an array of frames
  28802. var concatenateFrameData = function (frames) {
  28803. var i,
  28804. currentFrame,
  28805. dataOffset = 0,
  28806. data = new Uint8Array(sumFrameByteLengths(frames));
  28807. for (i = 0; i < frames.length; i++) {
  28808. currentFrame = frames[i];
  28809. data.set(currentFrame.data, dataOffset);
  28810. dataOffset += currentFrame.data.byteLength;
  28811. }
  28812. return data;
  28813. };
  28814. var audioFrameUtils$1 = {
  28815. prefixWithSilence: prefixWithSilence,
  28816. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  28817. generateSampleTable: generateSampleTable,
  28818. concatenateFrameData: concatenateFrameData
  28819. };
  28820. /**
  28821. * mux.js
  28822. *
  28823. * Copyright (c) Brightcove
  28824. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28825. */
  28826. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  28827. /**
  28828. * Store information about the start and end of the track and the
  28829. * duration for each frame/sample we process in order to calculate
  28830. * the baseMediaDecodeTime
  28831. */
  28832. var collectDtsInfo = function (track, data) {
  28833. if (typeof data.pts === 'number') {
  28834. if (track.timelineStartInfo.pts === undefined) {
  28835. track.timelineStartInfo.pts = data.pts;
  28836. }
  28837. if (track.minSegmentPts === undefined) {
  28838. track.minSegmentPts = data.pts;
  28839. } else {
  28840. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  28841. }
  28842. if (track.maxSegmentPts === undefined) {
  28843. track.maxSegmentPts = data.pts;
  28844. } else {
  28845. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  28846. }
  28847. }
  28848. if (typeof data.dts === 'number') {
  28849. if (track.timelineStartInfo.dts === undefined) {
  28850. track.timelineStartInfo.dts = data.dts;
  28851. }
  28852. if (track.minSegmentDts === undefined) {
  28853. track.minSegmentDts = data.dts;
  28854. } else {
  28855. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  28856. }
  28857. if (track.maxSegmentDts === undefined) {
  28858. track.maxSegmentDts = data.dts;
  28859. } else {
  28860. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  28861. }
  28862. }
  28863. };
  28864. /**
  28865. * Clear values used to calculate the baseMediaDecodeTime between
  28866. * tracks
  28867. */
  28868. var clearDtsInfo = function (track) {
  28869. delete track.minSegmentDts;
  28870. delete track.maxSegmentDts;
  28871. delete track.minSegmentPts;
  28872. delete track.maxSegmentPts;
  28873. };
  28874. /**
  28875. * Calculate the track's baseMediaDecodeTime based on the earliest
  28876. * DTS the transmuxer has ever seen and the minimum DTS for the
  28877. * current track
  28878. * @param track {object} track metadata configuration
  28879. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  28880. * in the source; false to adjust the first segment to start at 0.
  28881. */
  28882. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  28883. var baseMediaDecodeTime,
  28884. scale,
  28885. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  28886. if (!keepOriginalTimestamps) {
  28887. minSegmentDts -= track.timelineStartInfo.dts;
  28888. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  28889. // we want the start of the first segment to be placed
  28890. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  28891. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  28892. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  28893. if (track.type === 'audio') {
  28894. // Audio has a different clock equal to the sampling_rate so we need to
  28895. // scale the PTS values into the clock rate of the track
  28896. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  28897. baseMediaDecodeTime *= scale;
  28898. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  28899. }
  28900. return baseMediaDecodeTime;
  28901. };
  28902. var trackDecodeInfo$1 = {
  28903. clearDtsInfo: clearDtsInfo,
  28904. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  28905. collectDtsInfo: collectDtsInfo
  28906. };
  28907. /**
  28908. * mux.js
  28909. *
  28910. * Copyright (c) Brightcove
  28911. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28912. *
  28913. * Reads in-band caption information from a video elementary
  28914. * stream. Captions must follow the CEA-708 standard for injection
  28915. * into an MPEG-2 transport streams.
  28916. * @see https://en.wikipedia.org/wiki/CEA-708
  28917. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  28918. */
  28919. // payload type field to indicate how they are to be
  28920. // interpreted. CEAS-708 caption content is always transmitted with
  28921. // payload type 0x04.
  28922. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  28923. RBSP_TRAILING_BITS = 128;
  28924. /**
  28925. * Parse a supplemental enhancement information (SEI) NAL unit.
  28926. * Stops parsing once a message of type ITU T T35 has been found.
  28927. *
  28928. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  28929. * @return {object} the parsed SEI payload
  28930. * @see Rec. ITU-T H.264, 7.3.2.3.1
  28931. */
  28932. var parseSei = function (bytes) {
  28933. var i = 0,
  28934. result = {
  28935. payloadType: -1,
  28936. payloadSize: 0
  28937. },
  28938. payloadType = 0,
  28939. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  28940. while (i < bytes.byteLength) {
  28941. // stop once we have hit the end of the sei_rbsp
  28942. if (bytes[i] === RBSP_TRAILING_BITS) {
  28943. break;
  28944. } // Parse payload type
  28945. while (bytes[i] === 0xFF) {
  28946. payloadType += 255;
  28947. i++;
  28948. }
  28949. payloadType += bytes[i++]; // Parse payload size
  28950. while (bytes[i] === 0xFF) {
  28951. payloadSize += 255;
  28952. i++;
  28953. }
  28954. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  28955. // there can only ever be one caption message in a frame's sei
  28956. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  28957. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  28958. if (userIdentifier === 'GA94') {
  28959. result.payloadType = payloadType;
  28960. result.payloadSize = payloadSize;
  28961. result.payload = bytes.subarray(i, i + payloadSize);
  28962. break;
  28963. } else {
  28964. result.payload = void 0;
  28965. }
  28966. } // skip the payload and parse the next message
  28967. i += payloadSize;
  28968. payloadType = 0;
  28969. payloadSize = 0;
  28970. }
  28971. return result;
  28972. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  28973. var parseUserData = function (sei) {
  28974. // itu_t_t35_contry_code must be 181 (United States) for
  28975. // captions
  28976. if (sei.payload[0] !== 181) {
  28977. return null;
  28978. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  28979. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  28980. return null;
  28981. } // the user_identifier should be "GA94" to indicate ATSC1 data
  28982. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  28983. return null;
  28984. } // finally, user_data_type_code should be 0x03 for caption data
  28985. if (sei.payload[7] !== 0x03) {
  28986. return null;
  28987. } // return the user_data_type_structure and strip the trailing
  28988. // marker bits
  28989. return sei.payload.subarray(8, sei.payload.length - 1);
  28990. }; // see CEA-708-D, section 4.4
  28991. var parseCaptionPackets = function (pts, userData) {
  28992. var results = [],
  28993. i,
  28994. count,
  28995. offset,
  28996. data; // if this is just filler, return immediately
  28997. if (!(userData[0] & 0x40)) {
  28998. return results;
  28999. } // parse out the cc_data_1 and cc_data_2 fields
  29000. count = userData[0] & 0x1f;
  29001. for (i = 0; i < count; i++) {
  29002. offset = i * 3;
  29003. data = {
  29004. type: userData[offset + 2] & 0x03,
  29005. pts: pts
  29006. }; // capture cc data when cc_valid is 1
  29007. if (userData[offset + 2] & 0x04) {
  29008. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  29009. results.push(data);
  29010. }
  29011. }
  29012. return results;
  29013. };
  29014. var discardEmulationPreventionBytes$1 = function (data) {
  29015. var length = data.byteLength,
  29016. emulationPreventionBytesPositions = [],
  29017. i = 1,
  29018. newLength,
  29019. newData; // Find all `Emulation Prevention Bytes`
  29020. while (i < length - 2) {
  29021. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  29022. emulationPreventionBytesPositions.push(i + 2);
  29023. i += 2;
  29024. } else {
  29025. i++;
  29026. }
  29027. } // If no Emulation Prevention Bytes were found just return the original
  29028. // array
  29029. if (emulationPreventionBytesPositions.length === 0) {
  29030. return data;
  29031. } // Create a new array to hold the NAL unit data
  29032. newLength = length - emulationPreventionBytesPositions.length;
  29033. newData = new Uint8Array(newLength);
  29034. var sourceIndex = 0;
  29035. for (i = 0; i < newLength; sourceIndex++, i++) {
  29036. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  29037. // Skip this byte
  29038. sourceIndex++; // Remove this position index
  29039. emulationPreventionBytesPositions.shift();
  29040. }
  29041. newData[i] = data[sourceIndex];
  29042. }
  29043. return newData;
  29044. }; // exports
  29045. var captionPacketParser = {
  29046. parseSei: parseSei,
  29047. parseUserData: parseUserData,
  29048. parseCaptionPackets: parseCaptionPackets,
  29049. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  29050. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  29051. };
  29052. /**
  29053. * mux.js
  29054. *
  29055. * Copyright (c) Brightcove
  29056. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  29057. *
  29058. * Reads in-band caption information from a video elementary
  29059. * stream. Captions must follow the CEA-708 standard for injection
  29060. * into an MPEG-2 transport streams.
  29061. * @see https://en.wikipedia.org/wiki/CEA-708
  29062. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  29063. */
  29064. // Link To Transport
  29065. // -----------------
  29066. var Stream$7 = stream;
  29067. var cea708Parser = captionPacketParser;
  29068. var CaptionStream$2 = function (options) {
  29069. options = options || {};
  29070. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  29071. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  29072. this.captionPackets_ = [];
  29073. this.ccStreams_ = [new Cea608Stream(0, 0),
  29074. // eslint-disable-line no-use-before-define
  29075. new Cea608Stream(0, 1),
  29076. // eslint-disable-line no-use-before-define
  29077. new Cea608Stream(1, 0),
  29078. // eslint-disable-line no-use-before-define
  29079. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  29080. ];
  29081. if (this.parse708captions_) {
  29082. this.cc708Stream_ = new Cea708Stream({
  29083. captionServices: options.captionServices
  29084. }); // eslint-disable-line no-use-before-define
  29085. }
  29086. this.reset(); // forward data and done events from CCs to this CaptionStream
  29087. this.ccStreams_.forEach(function (cc) {
  29088. cc.on('data', this.trigger.bind(this, 'data'));
  29089. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29090. cc.on('done', this.trigger.bind(this, 'done'));
  29091. }, this);
  29092. if (this.parse708captions_) {
  29093. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  29094. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29095. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  29096. }
  29097. };
  29098. CaptionStream$2.prototype = new Stream$7();
  29099. CaptionStream$2.prototype.push = function (event) {
  29100. var sei, userData, newCaptionPackets; // only examine SEI NALs
  29101. if (event.nalUnitType !== 'sei_rbsp') {
  29102. return;
  29103. } // parse the sei
  29104. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  29105. if (!sei.payload) {
  29106. return;
  29107. } // ignore everything but user_data_registered_itu_t_t35
  29108. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  29109. return;
  29110. } // parse out the user data payload
  29111. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  29112. if (!userData) {
  29113. return;
  29114. } // Sometimes, the same segment # will be downloaded twice. To stop the
  29115. // caption data from being processed twice, we track the latest dts we've
  29116. // received and ignore everything with a dts before that. However, since
  29117. // data for a specific dts can be split across packets on either side of
  29118. // a segment boundary, we need to make sure we *don't* ignore the packets
  29119. // from the *next* segment that have dts === this.latestDts_. By constantly
  29120. // tracking the number of packets received with dts === this.latestDts_, we
  29121. // know how many should be ignored once we start receiving duplicates.
  29122. if (event.dts < this.latestDts_) {
  29123. // We've started getting older data, so set the flag.
  29124. this.ignoreNextEqualDts_ = true;
  29125. return;
  29126. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  29127. this.numSameDts_--;
  29128. if (!this.numSameDts_) {
  29129. // We've received the last duplicate packet, time to start processing again
  29130. this.ignoreNextEqualDts_ = false;
  29131. }
  29132. return;
  29133. } // parse out CC data packets and save them for later
  29134. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  29135. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  29136. if (this.latestDts_ !== event.dts) {
  29137. this.numSameDts_ = 0;
  29138. }
  29139. this.numSameDts_++;
  29140. this.latestDts_ = event.dts;
  29141. };
  29142. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  29143. this.ccStreams_.forEach(function (cc) {
  29144. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  29145. }, this);
  29146. };
  29147. CaptionStream$2.prototype.flushStream = function (flushType) {
  29148. // make sure we actually parsed captions before proceeding
  29149. if (!this.captionPackets_.length) {
  29150. this.flushCCStreams(flushType);
  29151. return;
  29152. } // In Chrome, the Array#sort function is not stable so add a
  29153. // presortIndex that we can use to ensure we get a stable-sort
  29154. this.captionPackets_.forEach(function (elem, idx) {
  29155. elem.presortIndex = idx;
  29156. }); // sort caption byte-pairs based on their PTS values
  29157. this.captionPackets_.sort(function (a, b) {
  29158. if (a.pts === b.pts) {
  29159. return a.presortIndex - b.presortIndex;
  29160. }
  29161. return a.pts - b.pts;
  29162. });
  29163. this.captionPackets_.forEach(function (packet) {
  29164. if (packet.type < 2) {
  29165. // Dispatch packet to the right Cea608Stream
  29166. this.dispatchCea608Packet(packet);
  29167. } else {
  29168. // Dispatch packet to the Cea708Stream
  29169. this.dispatchCea708Packet(packet);
  29170. }
  29171. }, this);
  29172. this.captionPackets_.length = 0;
  29173. this.flushCCStreams(flushType);
  29174. };
  29175. CaptionStream$2.prototype.flush = function () {
  29176. return this.flushStream('flush');
  29177. }; // Only called if handling partial data
  29178. CaptionStream$2.prototype.partialFlush = function () {
  29179. return this.flushStream('partialFlush');
  29180. };
  29181. CaptionStream$2.prototype.reset = function () {
  29182. this.latestDts_ = null;
  29183. this.ignoreNextEqualDts_ = false;
  29184. this.numSameDts_ = 0;
  29185. this.activeCea608Channel_ = [null, null];
  29186. this.ccStreams_.forEach(function (ccStream) {
  29187. ccStream.reset();
  29188. });
  29189. }; // From the CEA-608 spec:
  29190. /*
  29191. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  29192. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  29193. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  29194. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  29195. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  29196. * to switch to captioning or Text.
  29197. */
  29198. // With that in mind, we ignore any data between an XDS control code and a
  29199. // subsequent closed-captioning control code.
  29200. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  29201. // NOTE: packet.type is the CEA608 field
  29202. if (this.setsTextOrXDSActive(packet)) {
  29203. this.activeCea608Channel_[packet.type] = null;
  29204. } else if (this.setsChannel1Active(packet)) {
  29205. this.activeCea608Channel_[packet.type] = 0;
  29206. } else if (this.setsChannel2Active(packet)) {
  29207. this.activeCea608Channel_[packet.type] = 1;
  29208. }
  29209. if (this.activeCea608Channel_[packet.type] === null) {
  29210. // If we haven't received anything to set the active channel, or the
  29211. // packets are Text/XDS data, discard the data; we don't want jumbled
  29212. // captions
  29213. return;
  29214. }
  29215. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  29216. };
  29217. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  29218. return (packet.ccData & 0x7800) === 0x1000;
  29219. };
  29220. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  29221. return (packet.ccData & 0x7800) === 0x1800;
  29222. };
  29223. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  29224. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  29225. };
  29226. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  29227. if (this.parse708captions_) {
  29228. this.cc708Stream_.push(packet);
  29229. }
  29230. }; // ----------------------
  29231. // Session to Application
  29232. // ----------------------
  29233. // This hash maps special and extended character codes to their
  29234. // proper Unicode equivalent. The first one-byte key is just a
  29235. // non-standard character code. The two-byte keys that follow are
  29236. // the extended CEA708 character codes, along with the preceding
  29237. // 0x10 extended character byte to distinguish these codes from
  29238. // non-extended character codes. Every CEA708 character code that
  29239. // is not in this object maps directly to a standard unicode
  29240. // character code.
  29241. // The transparent space and non-breaking transparent space are
  29242. // technically not fully supported since there is no code to
  29243. // make them transparent, so they have normal non-transparent
  29244. // stand-ins.
  29245. // The special closed caption (CC) character isn't a standard
  29246. // unicode character, so a fairly similar unicode character was
  29247. // chosen in it's place.
  29248. var CHARACTER_TRANSLATION_708 = {
  29249. 0x7f: 0x266a,
  29250. // ♪
  29251. 0x1020: 0x20,
  29252. // Transparent Space
  29253. 0x1021: 0xa0,
  29254. // Nob-breaking Transparent Space
  29255. 0x1025: 0x2026,
  29256. // …
  29257. 0x102a: 0x0160,
  29258. // Š
  29259. 0x102c: 0x0152,
  29260. // Œ
  29261. 0x1030: 0x2588,
  29262. // █
  29263. 0x1031: 0x2018,
  29264. // ‘
  29265. 0x1032: 0x2019,
  29266. // ’
  29267. 0x1033: 0x201c,
  29268. // “
  29269. 0x1034: 0x201d,
  29270. // ”
  29271. 0x1035: 0x2022,
  29272. // •
  29273. 0x1039: 0x2122,
  29274. // ™
  29275. 0x103a: 0x0161,
  29276. // š
  29277. 0x103c: 0x0153,
  29278. // œ
  29279. 0x103d: 0x2120,
  29280. // ℠
  29281. 0x103f: 0x0178,
  29282. // Ÿ
  29283. 0x1076: 0x215b,
  29284. // ⅛
  29285. 0x1077: 0x215c,
  29286. // ⅜
  29287. 0x1078: 0x215d,
  29288. // ⅝
  29289. 0x1079: 0x215e,
  29290. // ⅞
  29291. 0x107a: 0x23d0,
  29292. // ⏐
  29293. 0x107b: 0x23a4,
  29294. // ⎤
  29295. 0x107c: 0x23a3,
  29296. // ⎣
  29297. 0x107d: 0x23af,
  29298. // ⎯
  29299. 0x107e: 0x23a6,
  29300. // ⎦
  29301. 0x107f: 0x23a1,
  29302. // ⎡
  29303. 0x10a0: 0x3138 // ㄸ (CC char)
  29304. };
  29305. var get708CharFromCode = function (code) {
  29306. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  29307. if (code & 0x1000 && code === newCode) {
  29308. // Invalid extended code
  29309. return '';
  29310. }
  29311. return String.fromCharCode(newCode);
  29312. };
  29313. var within708TextBlock = function (b) {
  29314. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  29315. };
  29316. var Cea708Window = function (windowNum) {
  29317. this.windowNum = windowNum;
  29318. this.reset();
  29319. };
  29320. Cea708Window.prototype.reset = function () {
  29321. this.clearText();
  29322. this.pendingNewLine = false;
  29323. this.winAttr = {};
  29324. this.penAttr = {};
  29325. this.penLoc = {};
  29326. this.penColor = {}; // These default values are arbitrary,
  29327. // defineWindow will usually override them
  29328. this.visible = 0;
  29329. this.rowLock = 0;
  29330. this.columnLock = 0;
  29331. this.priority = 0;
  29332. this.relativePositioning = 0;
  29333. this.anchorVertical = 0;
  29334. this.anchorHorizontal = 0;
  29335. this.anchorPoint = 0;
  29336. this.rowCount = 1;
  29337. this.virtualRowCount = this.rowCount + 1;
  29338. this.columnCount = 41;
  29339. this.windowStyle = 0;
  29340. this.penStyle = 0;
  29341. };
  29342. Cea708Window.prototype.getText = function () {
  29343. return this.rows.join('\n');
  29344. };
  29345. Cea708Window.prototype.clearText = function () {
  29346. this.rows = [''];
  29347. this.rowIdx = 0;
  29348. };
  29349. Cea708Window.prototype.newLine = function (pts) {
  29350. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  29351. this.beforeRowOverflow(pts);
  29352. }
  29353. if (this.rows.length > 0) {
  29354. this.rows.push('');
  29355. this.rowIdx++;
  29356. } // Show all virtual rows since there's no visible scrolling
  29357. while (this.rows.length > this.virtualRowCount) {
  29358. this.rows.shift();
  29359. this.rowIdx--;
  29360. }
  29361. };
  29362. Cea708Window.prototype.isEmpty = function () {
  29363. if (this.rows.length === 0) {
  29364. return true;
  29365. } else if (this.rows.length === 1) {
  29366. return this.rows[0] === '';
  29367. }
  29368. return false;
  29369. };
  29370. Cea708Window.prototype.addText = function (text) {
  29371. this.rows[this.rowIdx] += text;
  29372. };
  29373. Cea708Window.prototype.backspace = function () {
  29374. if (!this.isEmpty()) {
  29375. var row = this.rows[this.rowIdx];
  29376. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  29377. }
  29378. };
  29379. var Cea708Service = function (serviceNum, encoding, stream) {
  29380. this.serviceNum = serviceNum;
  29381. this.text = '';
  29382. this.currentWindow = new Cea708Window(-1);
  29383. this.windows = [];
  29384. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  29385. if (typeof encoding === 'string') {
  29386. this.createTextDecoder(encoding);
  29387. }
  29388. };
  29389. /**
  29390. * Initialize service windows
  29391. * Must be run before service use
  29392. *
  29393. * @param {Integer} pts PTS value
  29394. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  29395. */
  29396. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  29397. this.startPts = pts;
  29398. for (var win = 0; win < 8; win++) {
  29399. this.windows[win] = new Cea708Window(win);
  29400. if (typeof beforeRowOverflow === 'function') {
  29401. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  29402. }
  29403. }
  29404. };
  29405. /**
  29406. * Set current window of service to be affected by commands
  29407. *
  29408. * @param {Integer} windowNum Window number
  29409. */
  29410. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  29411. this.currentWindow = this.windows[windowNum];
  29412. };
  29413. /**
  29414. * Try to create a TextDecoder if it is natively supported
  29415. */
  29416. Cea708Service.prototype.createTextDecoder = function (encoding) {
  29417. if (typeof TextDecoder === 'undefined') {
  29418. this.stream.trigger('log', {
  29419. level: 'warn',
  29420. message: 'The `encoding` option is unsupported without TextDecoder support'
  29421. });
  29422. } else {
  29423. try {
  29424. this.textDecoder_ = new TextDecoder(encoding);
  29425. } catch (error) {
  29426. this.stream.trigger('log', {
  29427. level: 'warn',
  29428. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  29429. });
  29430. }
  29431. }
  29432. };
  29433. var Cea708Stream = function (options) {
  29434. options = options || {};
  29435. Cea708Stream.prototype.init.call(this);
  29436. var self = this;
  29437. var captionServices = options.captionServices || {};
  29438. var captionServiceEncodings = {};
  29439. var serviceProps; // Get service encodings from captionServices option block
  29440. Object.keys(captionServices).forEach(serviceName => {
  29441. serviceProps = captionServices[serviceName];
  29442. if (/^SERVICE/.test(serviceName)) {
  29443. captionServiceEncodings[serviceName] = serviceProps.encoding;
  29444. }
  29445. });
  29446. this.serviceEncodings = captionServiceEncodings;
  29447. this.current708Packet = null;
  29448. this.services = {};
  29449. this.push = function (packet) {
  29450. if (packet.type === 3) {
  29451. // 708 packet start
  29452. self.new708Packet();
  29453. self.add708Bytes(packet);
  29454. } else {
  29455. if (self.current708Packet === null) {
  29456. // This should only happen at the start of a file if there's no packet start.
  29457. self.new708Packet();
  29458. }
  29459. self.add708Bytes(packet);
  29460. }
  29461. };
  29462. };
  29463. Cea708Stream.prototype = new Stream$7();
  29464. /**
  29465. * Push current 708 packet, create new 708 packet.
  29466. */
  29467. Cea708Stream.prototype.new708Packet = function () {
  29468. if (this.current708Packet !== null) {
  29469. this.push708Packet();
  29470. }
  29471. this.current708Packet = {
  29472. data: [],
  29473. ptsVals: []
  29474. };
  29475. };
  29476. /**
  29477. * Add pts and both bytes from packet into current 708 packet.
  29478. */
  29479. Cea708Stream.prototype.add708Bytes = function (packet) {
  29480. var data = packet.ccData;
  29481. var byte0 = data >>> 8;
  29482. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  29483. // that service blocks will always line up with byte pairs.
  29484. this.current708Packet.ptsVals.push(packet.pts);
  29485. this.current708Packet.data.push(byte0);
  29486. this.current708Packet.data.push(byte1);
  29487. };
  29488. /**
  29489. * Parse completed 708 packet into service blocks and push each service block.
  29490. */
  29491. Cea708Stream.prototype.push708Packet = function () {
  29492. var packet708 = this.current708Packet;
  29493. var packetData = packet708.data;
  29494. var serviceNum = null;
  29495. var blockSize = null;
  29496. var i = 0;
  29497. var b = packetData[i++];
  29498. packet708.seq = b >> 6;
  29499. packet708.sizeCode = b & 0x3f; // 0b00111111;
  29500. for (; i < packetData.length; i++) {
  29501. b = packetData[i++];
  29502. serviceNum = b >> 5;
  29503. blockSize = b & 0x1f; // 0b00011111
  29504. if (serviceNum === 7 && blockSize > 0) {
  29505. // Extended service num
  29506. b = packetData[i++];
  29507. serviceNum = b;
  29508. }
  29509. this.pushServiceBlock(serviceNum, i, blockSize);
  29510. if (blockSize > 0) {
  29511. i += blockSize - 1;
  29512. }
  29513. }
  29514. };
  29515. /**
  29516. * Parse service block, execute commands, read text.
  29517. *
  29518. * Note: While many of these commands serve important purposes,
  29519. * many others just parse out the parameters or attributes, but
  29520. * nothing is done with them because this is not a full and complete
  29521. * implementation of the entire 708 spec.
  29522. *
  29523. * @param {Integer} serviceNum Service number
  29524. * @param {Integer} start Start index of the 708 packet data
  29525. * @param {Integer} size Block size
  29526. */
  29527. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  29528. var b;
  29529. var i = start;
  29530. var packetData = this.current708Packet.data;
  29531. var service = this.services[serviceNum];
  29532. if (!service) {
  29533. service = this.initService(serviceNum, i);
  29534. }
  29535. for (; i < start + size && i < packetData.length; i++) {
  29536. b = packetData[i];
  29537. if (within708TextBlock(b)) {
  29538. i = this.handleText(i, service);
  29539. } else if (b === 0x18) {
  29540. i = this.multiByteCharacter(i, service);
  29541. } else if (b === 0x10) {
  29542. i = this.extendedCommands(i, service);
  29543. } else if (0x80 <= b && b <= 0x87) {
  29544. i = this.setCurrentWindow(i, service);
  29545. } else if (0x98 <= b && b <= 0x9f) {
  29546. i = this.defineWindow(i, service);
  29547. } else if (b === 0x88) {
  29548. i = this.clearWindows(i, service);
  29549. } else if (b === 0x8c) {
  29550. i = this.deleteWindows(i, service);
  29551. } else if (b === 0x89) {
  29552. i = this.displayWindows(i, service);
  29553. } else if (b === 0x8a) {
  29554. i = this.hideWindows(i, service);
  29555. } else if (b === 0x8b) {
  29556. i = this.toggleWindows(i, service);
  29557. } else if (b === 0x97) {
  29558. i = this.setWindowAttributes(i, service);
  29559. } else if (b === 0x90) {
  29560. i = this.setPenAttributes(i, service);
  29561. } else if (b === 0x91) {
  29562. i = this.setPenColor(i, service);
  29563. } else if (b === 0x92) {
  29564. i = this.setPenLocation(i, service);
  29565. } else if (b === 0x8f) {
  29566. service = this.reset(i, service);
  29567. } else if (b === 0x08) {
  29568. // BS: Backspace
  29569. service.currentWindow.backspace();
  29570. } else if (b === 0x0c) {
  29571. // FF: Form feed
  29572. service.currentWindow.clearText();
  29573. } else if (b === 0x0d) {
  29574. // CR: Carriage return
  29575. service.currentWindow.pendingNewLine = true;
  29576. } else if (b === 0x0e) {
  29577. // HCR: Horizontal carriage return
  29578. service.currentWindow.clearText();
  29579. } else if (b === 0x8d) {
  29580. // DLY: Delay, nothing to do
  29581. i++;
  29582. } else ;
  29583. }
  29584. };
  29585. /**
  29586. * Execute an extended command
  29587. *
  29588. * @param {Integer} i Current index in the 708 packet
  29589. * @param {Service} service The service object to be affected
  29590. * @return {Integer} New index after parsing
  29591. */
  29592. Cea708Stream.prototype.extendedCommands = function (i, service) {
  29593. var packetData = this.current708Packet.data;
  29594. var b = packetData[++i];
  29595. if (within708TextBlock(b)) {
  29596. i = this.handleText(i, service, {
  29597. isExtended: true
  29598. });
  29599. }
  29600. return i;
  29601. };
  29602. /**
  29603. * Get PTS value of a given byte index
  29604. *
  29605. * @param {Integer} byteIndex Index of the byte
  29606. * @return {Integer} PTS
  29607. */
  29608. Cea708Stream.prototype.getPts = function (byteIndex) {
  29609. // There's 1 pts value per 2 bytes
  29610. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  29611. };
  29612. /**
  29613. * Initializes a service
  29614. *
  29615. * @param {Integer} serviceNum Service number
  29616. * @return {Service} Initialized service object
  29617. */
  29618. Cea708Stream.prototype.initService = function (serviceNum, i) {
  29619. var serviceName = 'SERVICE' + serviceNum;
  29620. var self = this;
  29621. var serviceName;
  29622. var encoding;
  29623. if (serviceName in this.serviceEncodings) {
  29624. encoding = this.serviceEncodings[serviceName];
  29625. }
  29626. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  29627. this.services[serviceNum].init(this.getPts(i), function (pts) {
  29628. self.flushDisplayed(pts, self.services[serviceNum]);
  29629. });
  29630. return this.services[serviceNum];
  29631. };
  29632. /**
  29633. * Execute text writing to current window
  29634. *
  29635. * @param {Integer} i Current index in the 708 packet
  29636. * @param {Service} service The service object to be affected
  29637. * @return {Integer} New index after parsing
  29638. */
  29639. Cea708Stream.prototype.handleText = function (i, service, options) {
  29640. var isExtended = options && options.isExtended;
  29641. var isMultiByte = options && options.isMultiByte;
  29642. var packetData = this.current708Packet.data;
  29643. var extended = isExtended ? 0x1000 : 0x0000;
  29644. var currentByte = packetData[i];
  29645. var nextByte = packetData[i + 1];
  29646. var win = service.currentWindow;
  29647. var char;
  29648. var charCodeArray; // Use the TextDecoder if one was created for this service
  29649. if (service.textDecoder_ && !isExtended) {
  29650. if (isMultiByte) {
  29651. charCodeArray = [currentByte, nextByte];
  29652. i++;
  29653. } else {
  29654. charCodeArray = [currentByte];
  29655. }
  29656. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  29657. } else {
  29658. char = get708CharFromCode(extended | currentByte);
  29659. }
  29660. if (win.pendingNewLine && !win.isEmpty()) {
  29661. win.newLine(this.getPts(i));
  29662. }
  29663. win.pendingNewLine = false;
  29664. win.addText(char);
  29665. return i;
  29666. };
  29667. /**
  29668. * Handle decoding of multibyte character
  29669. *
  29670. * @param {Integer} i Current index in the 708 packet
  29671. * @param {Service} service The service object to be affected
  29672. * @return {Integer} New index after parsing
  29673. */
  29674. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  29675. var packetData = this.current708Packet.data;
  29676. var firstByte = packetData[i + 1];
  29677. var secondByte = packetData[i + 2];
  29678. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  29679. i = this.handleText(++i, service, {
  29680. isMultiByte: true
  29681. });
  29682. }
  29683. return i;
  29684. };
  29685. /**
  29686. * Parse and execute the CW# command.
  29687. *
  29688. * Set the current window.
  29689. *
  29690. * @param {Integer} i Current index in the 708 packet
  29691. * @param {Service} service The service object to be affected
  29692. * @return {Integer} New index after parsing
  29693. */
  29694. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  29695. var packetData = this.current708Packet.data;
  29696. var b = packetData[i];
  29697. var windowNum = b & 0x07;
  29698. service.setCurrentWindow(windowNum);
  29699. return i;
  29700. };
  29701. /**
  29702. * Parse and execute the DF# command.
  29703. *
  29704. * Define a window and set it as the current window.
  29705. *
  29706. * @param {Integer} i Current index in the 708 packet
  29707. * @param {Service} service The service object to be affected
  29708. * @return {Integer} New index after parsing
  29709. */
  29710. Cea708Stream.prototype.defineWindow = function (i, service) {
  29711. var packetData = this.current708Packet.data;
  29712. var b = packetData[i];
  29713. var windowNum = b & 0x07;
  29714. service.setCurrentWindow(windowNum);
  29715. var win = service.currentWindow;
  29716. b = packetData[++i];
  29717. win.visible = (b & 0x20) >> 5; // v
  29718. win.rowLock = (b & 0x10) >> 4; // rl
  29719. win.columnLock = (b & 0x08) >> 3; // cl
  29720. win.priority = b & 0x07; // p
  29721. b = packetData[++i];
  29722. win.relativePositioning = (b & 0x80) >> 7; // rp
  29723. win.anchorVertical = b & 0x7f; // av
  29724. b = packetData[++i];
  29725. win.anchorHorizontal = b; // ah
  29726. b = packetData[++i];
  29727. win.anchorPoint = (b & 0xf0) >> 4; // ap
  29728. win.rowCount = b & 0x0f; // rc
  29729. b = packetData[++i];
  29730. win.columnCount = b & 0x3f; // cc
  29731. b = packetData[++i];
  29732. win.windowStyle = (b & 0x38) >> 3; // ws
  29733. win.penStyle = b & 0x07; // ps
  29734. // The spec says there are (rowCount+1) "virtual rows"
  29735. win.virtualRowCount = win.rowCount + 1;
  29736. return i;
  29737. };
  29738. /**
  29739. * Parse and execute the SWA command.
  29740. *
  29741. * Set attributes of the current window.
  29742. *
  29743. * @param {Integer} i Current index in the 708 packet
  29744. * @param {Service} service The service object to be affected
  29745. * @return {Integer} New index after parsing
  29746. */
  29747. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  29748. var packetData = this.current708Packet.data;
  29749. var b = packetData[i];
  29750. var winAttr = service.currentWindow.winAttr;
  29751. b = packetData[++i];
  29752. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  29753. winAttr.fillRed = (b & 0x30) >> 4; // fr
  29754. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  29755. winAttr.fillBlue = b & 0x03; // fb
  29756. b = packetData[++i];
  29757. winAttr.borderType = (b & 0xc0) >> 6; // bt
  29758. winAttr.borderRed = (b & 0x30) >> 4; // br
  29759. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  29760. winAttr.borderBlue = b & 0x03; // bb
  29761. b = packetData[++i];
  29762. winAttr.borderType += (b & 0x80) >> 5; // bt
  29763. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  29764. winAttr.printDirection = (b & 0x30) >> 4; // pd
  29765. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  29766. winAttr.justify = b & 0x03; // j
  29767. b = packetData[++i];
  29768. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  29769. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  29770. winAttr.displayEffect = b & 0x03; // de
  29771. return i;
  29772. };
  29773. /**
  29774. * Gather text from all displayed windows and push a caption to output.
  29775. *
  29776. * @param {Integer} i Current index in the 708 packet
  29777. * @param {Service} service The service object to be affected
  29778. */
  29779. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  29780. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  29781. // display text in the correct order, but sample files so far have not shown any issue.
  29782. for (var winId = 0; winId < 8; winId++) {
  29783. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  29784. displayedText.push(service.windows[winId].getText());
  29785. }
  29786. }
  29787. service.endPts = pts;
  29788. service.text = displayedText.join('\n\n');
  29789. this.pushCaption(service);
  29790. service.startPts = pts;
  29791. };
  29792. /**
  29793. * Push a caption to output if the caption contains text.
  29794. *
  29795. * @param {Service} service The service object to be affected
  29796. */
  29797. Cea708Stream.prototype.pushCaption = function (service) {
  29798. if (service.text !== '') {
  29799. this.trigger('data', {
  29800. startPts: service.startPts,
  29801. endPts: service.endPts,
  29802. text: service.text,
  29803. stream: 'cc708_' + service.serviceNum
  29804. });
  29805. service.text = '';
  29806. service.startPts = service.endPts;
  29807. }
  29808. };
  29809. /**
  29810. * Parse and execute the DSW command.
  29811. *
  29812. * Set visible property of windows based on the parsed bitmask.
  29813. *
  29814. * @param {Integer} i Current index in the 708 packet
  29815. * @param {Service} service The service object to be affected
  29816. * @return {Integer} New index after parsing
  29817. */
  29818. Cea708Stream.prototype.displayWindows = function (i, service) {
  29819. var packetData = this.current708Packet.data;
  29820. var b = packetData[++i];
  29821. var pts = this.getPts(i);
  29822. this.flushDisplayed(pts, service);
  29823. for (var winId = 0; winId < 8; winId++) {
  29824. if (b & 0x01 << winId) {
  29825. service.windows[winId].visible = 1;
  29826. }
  29827. }
  29828. return i;
  29829. };
  29830. /**
  29831. * Parse and execute the HDW command.
  29832. *
  29833. * Set visible property of windows based on the parsed bitmask.
  29834. *
  29835. * @param {Integer} i Current index in the 708 packet
  29836. * @param {Service} service The service object to be affected
  29837. * @return {Integer} New index after parsing
  29838. */
  29839. Cea708Stream.prototype.hideWindows = function (i, service) {
  29840. var packetData = this.current708Packet.data;
  29841. var b = packetData[++i];
  29842. var pts = this.getPts(i);
  29843. this.flushDisplayed(pts, service);
  29844. for (var winId = 0; winId < 8; winId++) {
  29845. if (b & 0x01 << winId) {
  29846. service.windows[winId].visible = 0;
  29847. }
  29848. }
  29849. return i;
  29850. };
  29851. /**
  29852. * Parse and execute the TGW command.
  29853. *
  29854. * Set visible property of windows based on the parsed bitmask.
  29855. *
  29856. * @param {Integer} i Current index in the 708 packet
  29857. * @param {Service} service The service object to be affected
  29858. * @return {Integer} New index after parsing
  29859. */
  29860. Cea708Stream.prototype.toggleWindows = function (i, service) {
  29861. var packetData = this.current708Packet.data;
  29862. var b = packetData[++i];
  29863. var pts = this.getPts(i);
  29864. this.flushDisplayed(pts, service);
  29865. for (var winId = 0; winId < 8; winId++) {
  29866. if (b & 0x01 << winId) {
  29867. service.windows[winId].visible ^= 1;
  29868. }
  29869. }
  29870. return i;
  29871. };
  29872. /**
  29873. * Parse and execute the CLW command.
  29874. *
  29875. * Clear text of windows based on the parsed bitmask.
  29876. *
  29877. * @param {Integer} i Current index in the 708 packet
  29878. * @param {Service} service The service object to be affected
  29879. * @return {Integer} New index after parsing
  29880. */
  29881. Cea708Stream.prototype.clearWindows = function (i, service) {
  29882. var packetData = this.current708Packet.data;
  29883. var b = packetData[++i];
  29884. var pts = this.getPts(i);
  29885. this.flushDisplayed(pts, service);
  29886. for (var winId = 0; winId < 8; winId++) {
  29887. if (b & 0x01 << winId) {
  29888. service.windows[winId].clearText();
  29889. }
  29890. }
  29891. return i;
  29892. };
  29893. /**
  29894. * Parse and execute the DLW command.
  29895. *
  29896. * Re-initialize windows based on the parsed bitmask.
  29897. *
  29898. * @param {Integer} i Current index in the 708 packet
  29899. * @param {Service} service The service object to be affected
  29900. * @return {Integer} New index after parsing
  29901. */
  29902. Cea708Stream.prototype.deleteWindows = function (i, service) {
  29903. var packetData = this.current708Packet.data;
  29904. var b = packetData[++i];
  29905. var pts = this.getPts(i);
  29906. this.flushDisplayed(pts, service);
  29907. for (var winId = 0; winId < 8; winId++) {
  29908. if (b & 0x01 << winId) {
  29909. service.windows[winId].reset();
  29910. }
  29911. }
  29912. return i;
  29913. };
  29914. /**
  29915. * Parse and execute the SPA command.
  29916. *
  29917. * Set pen attributes of the current window.
  29918. *
  29919. * @param {Integer} i Current index in the 708 packet
  29920. * @param {Service} service The service object to be affected
  29921. * @return {Integer} New index after parsing
  29922. */
  29923. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  29924. var packetData = this.current708Packet.data;
  29925. var b = packetData[i];
  29926. var penAttr = service.currentWindow.penAttr;
  29927. b = packetData[++i];
  29928. penAttr.textTag = (b & 0xf0) >> 4; // tt
  29929. penAttr.offset = (b & 0x0c) >> 2; // o
  29930. penAttr.penSize = b & 0x03; // s
  29931. b = packetData[++i];
  29932. penAttr.italics = (b & 0x80) >> 7; // i
  29933. penAttr.underline = (b & 0x40) >> 6; // u
  29934. penAttr.edgeType = (b & 0x38) >> 3; // et
  29935. penAttr.fontStyle = b & 0x07; // fs
  29936. return i;
  29937. };
  29938. /**
  29939. * Parse and execute the SPC command.
  29940. *
  29941. * Set pen color of the current window.
  29942. *
  29943. * @param {Integer} i Current index in the 708 packet
  29944. * @param {Service} service The service object to be affected
  29945. * @return {Integer} New index after parsing
  29946. */
  29947. Cea708Stream.prototype.setPenColor = function (i, service) {
  29948. var packetData = this.current708Packet.data;
  29949. var b = packetData[i];
  29950. var penColor = service.currentWindow.penColor;
  29951. b = packetData[++i];
  29952. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  29953. penColor.fgRed = (b & 0x30) >> 4; // fr
  29954. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  29955. penColor.fgBlue = b & 0x03; // fb
  29956. b = packetData[++i];
  29957. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  29958. penColor.bgRed = (b & 0x30) >> 4; // br
  29959. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  29960. penColor.bgBlue = b & 0x03; // bb
  29961. b = packetData[++i];
  29962. penColor.edgeRed = (b & 0x30) >> 4; // er
  29963. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  29964. penColor.edgeBlue = b & 0x03; // eb
  29965. return i;
  29966. };
  29967. /**
  29968. * Parse and execute the SPL command.
  29969. *
  29970. * Set pen location of the current window.
  29971. *
  29972. * @param {Integer} i Current index in the 708 packet
  29973. * @param {Service} service The service object to be affected
  29974. * @return {Integer} New index after parsing
  29975. */
  29976. Cea708Stream.prototype.setPenLocation = function (i, service) {
  29977. var packetData = this.current708Packet.data;
  29978. var b = packetData[i];
  29979. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  29980. service.currentWindow.pendingNewLine = true;
  29981. b = packetData[++i];
  29982. penLoc.row = b & 0x0f; // r
  29983. b = packetData[++i];
  29984. penLoc.column = b & 0x3f; // c
  29985. return i;
  29986. };
  29987. /**
  29988. * Execute the RST command.
  29989. *
  29990. * Reset service to a clean slate. Re-initialize.
  29991. *
  29992. * @param {Integer} i Current index in the 708 packet
  29993. * @param {Service} service The service object to be affected
  29994. * @return {Service} Re-initialized service
  29995. */
  29996. Cea708Stream.prototype.reset = function (i, service) {
  29997. var pts = this.getPts(i);
  29998. this.flushDisplayed(pts, service);
  29999. return this.initService(service.serviceNum, i);
  30000. }; // This hash maps non-ASCII, special, and extended character codes to their
  30001. // proper Unicode equivalent. The first keys that are only a single byte
  30002. // are the non-standard ASCII characters, which simply map the CEA608 byte
  30003. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  30004. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  30005. // can be performed regardless of the field and data channel on which the
  30006. // character code was received.
  30007. var CHARACTER_TRANSLATION = {
  30008. 0x2a: 0xe1,
  30009. // á
  30010. 0x5c: 0xe9,
  30011. // é
  30012. 0x5e: 0xed,
  30013. // í
  30014. 0x5f: 0xf3,
  30015. // ó
  30016. 0x60: 0xfa,
  30017. // ú
  30018. 0x7b: 0xe7,
  30019. // ç
  30020. 0x7c: 0xf7,
  30021. // ÷
  30022. 0x7d: 0xd1,
  30023. // Ñ
  30024. 0x7e: 0xf1,
  30025. // ñ
  30026. 0x7f: 0x2588,
  30027. // █
  30028. 0x0130: 0xae,
  30029. // ®
  30030. 0x0131: 0xb0,
  30031. // °
  30032. 0x0132: 0xbd,
  30033. // ½
  30034. 0x0133: 0xbf,
  30035. // ¿
  30036. 0x0134: 0x2122,
  30037. // ™
  30038. 0x0135: 0xa2,
  30039. // ¢
  30040. 0x0136: 0xa3,
  30041. // £
  30042. 0x0137: 0x266a,
  30043. // ♪
  30044. 0x0138: 0xe0,
  30045. // à
  30046. 0x0139: 0xa0,
  30047. //
  30048. 0x013a: 0xe8,
  30049. // è
  30050. 0x013b: 0xe2,
  30051. // â
  30052. 0x013c: 0xea,
  30053. // ê
  30054. 0x013d: 0xee,
  30055. // î
  30056. 0x013e: 0xf4,
  30057. // ô
  30058. 0x013f: 0xfb,
  30059. // û
  30060. 0x0220: 0xc1,
  30061. // Á
  30062. 0x0221: 0xc9,
  30063. // É
  30064. 0x0222: 0xd3,
  30065. // Ó
  30066. 0x0223: 0xda,
  30067. // Ú
  30068. 0x0224: 0xdc,
  30069. // Ü
  30070. 0x0225: 0xfc,
  30071. // ü
  30072. 0x0226: 0x2018,
  30073. // ‘
  30074. 0x0227: 0xa1,
  30075. // ¡
  30076. 0x0228: 0x2a,
  30077. // *
  30078. 0x0229: 0x27,
  30079. // '
  30080. 0x022a: 0x2014,
  30081. // —
  30082. 0x022b: 0xa9,
  30083. // ©
  30084. 0x022c: 0x2120,
  30085. // ℠
  30086. 0x022d: 0x2022,
  30087. // •
  30088. 0x022e: 0x201c,
  30089. // “
  30090. 0x022f: 0x201d,
  30091. // ”
  30092. 0x0230: 0xc0,
  30093. // À
  30094. 0x0231: 0xc2,
  30095. // Â
  30096. 0x0232: 0xc7,
  30097. // Ç
  30098. 0x0233: 0xc8,
  30099. // È
  30100. 0x0234: 0xca,
  30101. // Ê
  30102. 0x0235: 0xcb,
  30103. // Ë
  30104. 0x0236: 0xeb,
  30105. // ë
  30106. 0x0237: 0xce,
  30107. // Î
  30108. 0x0238: 0xcf,
  30109. // Ï
  30110. 0x0239: 0xef,
  30111. // ï
  30112. 0x023a: 0xd4,
  30113. // Ô
  30114. 0x023b: 0xd9,
  30115. // Ù
  30116. 0x023c: 0xf9,
  30117. // ù
  30118. 0x023d: 0xdb,
  30119. // Û
  30120. 0x023e: 0xab,
  30121. // «
  30122. 0x023f: 0xbb,
  30123. // »
  30124. 0x0320: 0xc3,
  30125. // Ã
  30126. 0x0321: 0xe3,
  30127. // ã
  30128. 0x0322: 0xcd,
  30129. // Í
  30130. 0x0323: 0xcc,
  30131. // Ì
  30132. 0x0324: 0xec,
  30133. // ì
  30134. 0x0325: 0xd2,
  30135. // Ò
  30136. 0x0326: 0xf2,
  30137. // ò
  30138. 0x0327: 0xd5,
  30139. // Õ
  30140. 0x0328: 0xf5,
  30141. // õ
  30142. 0x0329: 0x7b,
  30143. // {
  30144. 0x032a: 0x7d,
  30145. // }
  30146. 0x032b: 0x5c,
  30147. // \
  30148. 0x032c: 0x5e,
  30149. // ^
  30150. 0x032d: 0x5f,
  30151. // _
  30152. 0x032e: 0x7c,
  30153. // |
  30154. 0x032f: 0x7e,
  30155. // ~
  30156. 0x0330: 0xc4,
  30157. // Ä
  30158. 0x0331: 0xe4,
  30159. // ä
  30160. 0x0332: 0xd6,
  30161. // Ö
  30162. 0x0333: 0xf6,
  30163. // ö
  30164. 0x0334: 0xdf,
  30165. // ß
  30166. 0x0335: 0xa5,
  30167. // ¥
  30168. 0x0336: 0xa4,
  30169. // ¤
  30170. 0x0337: 0x2502,
  30171. // │
  30172. 0x0338: 0xc5,
  30173. // Å
  30174. 0x0339: 0xe5,
  30175. // å
  30176. 0x033a: 0xd8,
  30177. // Ø
  30178. 0x033b: 0xf8,
  30179. // ø
  30180. 0x033c: 0x250c,
  30181. // ┌
  30182. 0x033d: 0x2510,
  30183. // ┐
  30184. 0x033e: 0x2514,
  30185. // └
  30186. 0x033f: 0x2518 // ┘
  30187. };
  30188. var getCharFromCode = function (code) {
  30189. if (code === null) {
  30190. return '';
  30191. }
  30192. code = CHARACTER_TRANSLATION[code] || code;
  30193. return String.fromCharCode(code);
  30194. }; // the index of the last row in a CEA-608 display buffer
  30195. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  30196. // getting it through bit logic.
  30197. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
  30198. // cells. The "bottom" row is the last element in the outer array.
  30199. var createDisplayBuffer = function () {
  30200. var result = [],
  30201. i = BOTTOM_ROW + 1;
  30202. while (i--) {
  30203. result.push('');
  30204. }
  30205. return result;
  30206. };
  30207. var Cea608Stream = function (field, dataChannel) {
  30208. Cea608Stream.prototype.init.call(this);
  30209. this.field_ = field || 0;
  30210. this.dataChannel_ = dataChannel || 0;
  30211. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  30212. this.setConstants();
  30213. this.reset();
  30214. this.push = function (packet) {
  30215. var data, swap, char0, char1, text; // remove the parity bits
  30216. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  30217. if (data === this.lastControlCode_) {
  30218. this.lastControlCode_ = null;
  30219. return;
  30220. } // Store control codes
  30221. if ((data & 0xf000) === 0x1000) {
  30222. this.lastControlCode_ = data;
  30223. } else if (data !== this.PADDING_) {
  30224. this.lastControlCode_ = null;
  30225. }
  30226. char0 = data >>> 8;
  30227. char1 = data & 0xff;
  30228. if (data === this.PADDING_) {
  30229. return;
  30230. } else if (data === this.RESUME_CAPTION_LOADING_) {
  30231. this.mode_ = 'popOn';
  30232. } else if (data === this.END_OF_CAPTION_) {
  30233. // If an EOC is received while in paint-on mode, the displayed caption
  30234. // text should be swapped to non-displayed memory as if it was a pop-on
  30235. // caption. Because of that, we should explicitly switch back to pop-on
  30236. // mode
  30237. this.mode_ = 'popOn';
  30238. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  30239. this.flushDisplayed(packet.pts); // flip memory
  30240. swap = this.displayed_;
  30241. this.displayed_ = this.nonDisplayed_;
  30242. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  30243. this.startPts_ = packet.pts;
  30244. } else if (data === this.ROLL_UP_2_ROWS_) {
  30245. this.rollUpRows_ = 2;
  30246. this.setRollUp(packet.pts);
  30247. } else if (data === this.ROLL_UP_3_ROWS_) {
  30248. this.rollUpRows_ = 3;
  30249. this.setRollUp(packet.pts);
  30250. } else if (data === this.ROLL_UP_4_ROWS_) {
  30251. this.rollUpRows_ = 4;
  30252. this.setRollUp(packet.pts);
  30253. } else if (data === this.CARRIAGE_RETURN_) {
  30254. this.clearFormatting(packet.pts);
  30255. this.flushDisplayed(packet.pts);
  30256. this.shiftRowsUp_();
  30257. this.startPts_ = packet.pts;
  30258. } else if (data === this.BACKSPACE_) {
  30259. if (this.mode_ === 'popOn') {
  30260. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30261. } else {
  30262. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30263. }
  30264. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  30265. this.flushDisplayed(packet.pts);
  30266. this.displayed_ = createDisplayBuffer();
  30267. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  30268. this.nonDisplayed_ = createDisplayBuffer();
  30269. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  30270. if (this.mode_ !== 'paintOn') {
  30271. // NOTE: This should be removed when proper caption positioning is
  30272. // implemented
  30273. this.flushDisplayed(packet.pts);
  30274. this.displayed_ = createDisplayBuffer();
  30275. }
  30276. this.mode_ = 'paintOn';
  30277. this.startPts_ = packet.pts; // Append special characters to caption text
  30278. } else if (this.isSpecialCharacter(char0, char1)) {
  30279. // Bitmask char0 so that we can apply character transformations
  30280. // regardless of field and data channel.
  30281. // Then byte-shift to the left and OR with char1 so we can pass the
  30282. // entire character code to `getCharFromCode`.
  30283. char0 = (char0 & 0x03) << 8;
  30284. text = getCharFromCode(char0 | char1);
  30285. this[this.mode_](packet.pts, text);
  30286. this.column_++; // Append extended characters to caption text
  30287. } else if (this.isExtCharacter(char0, char1)) {
  30288. // Extended characters always follow their "non-extended" equivalents.
  30289. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  30290. // decoders are supposed to drop the "è", while compliant decoders
  30291. // backspace the "e" and insert "è".
  30292. // Delete the previous character
  30293. if (this.mode_ === 'popOn') {
  30294. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30295. } else {
  30296. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30297. } // Bitmask char0 so that we can apply character transformations
  30298. // regardless of field and data channel.
  30299. // Then byte-shift to the left and OR with char1 so we can pass the
  30300. // entire character code to `getCharFromCode`.
  30301. char0 = (char0 & 0x03) << 8;
  30302. text = getCharFromCode(char0 | char1);
  30303. this[this.mode_](packet.pts, text);
  30304. this.column_++; // Process mid-row codes
  30305. } else if (this.isMidRowCode(char0, char1)) {
  30306. // Attributes are not additive, so clear all formatting
  30307. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  30308. // should be replaced with spaces, so add one now
  30309. this[this.mode_](packet.pts, ' ');
  30310. this.column_++;
  30311. if ((char1 & 0xe) === 0xe) {
  30312. this.addFormatting(packet.pts, ['i']);
  30313. }
  30314. if ((char1 & 0x1) === 0x1) {
  30315. this.addFormatting(packet.pts, ['u']);
  30316. } // Detect offset control codes and adjust cursor
  30317. } else if (this.isOffsetControlCode(char0, char1)) {
  30318. // Cursor position is set by indent PAC (see below) in 4-column
  30319. // increments, with an additional offset code of 1-3 to reach any
  30320. // of the 32 columns specified by CEA-608. So all we need to do
  30321. // here is increment the column cursor by the given offset.
  30322. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  30323. } else if (this.isPAC(char0, char1)) {
  30324. // There's no logic for PAC -> row mapping, so we have to just
  30325. // find the row code in an array and use its index :(
  30326. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  30327. if (this.mode_ === 'rollUp') {
  30328. // This implies that the base row is incorrectly set.
  30329. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  30330. // of roll-up rows set.
  30331. if (row - this.rollUpRows_ + 1 < 0) {
  30332. row = this.rollUpRows_ - 1;
  30333. }
  30334. this.setRollUp(packet.pts, row);
  30335. }
  30336. if (row !== this.row_) {
  30337. // formatting is only persistent for current row
  30338. this.clearFormatting(packet.pts);
  30339. this.row_ = row;
  30340. } // All PACs can apply underline, so detect and apply
  30341. // (All odd-numbered second bytes set underline)
  30342. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  30343. this.addFormatting(packet.pts, ['u']);
  30344. }
  30345. if ((data & 0x10) === 0x10) {
  30346. // We've got an indent level code. Each successive even number
  30347. // increments the column cursor by 4, so we can get the desired
  30348. // column position by bit-shifting to the right (to get n/2)
  30349. // and multiplying by 4.
  30350. this.column_ = ((data & 0xe) >> 1) * 4;
  30351. }
  30352. if (this.isColorPAC(char1)) {
  30353. // it's a color code, though we only support white, which
  30354. // can be either normal or italicized. white italics can be
  30355. // either 0x4e or 0x6e depending on the row, so we just
  30356. // bitwise-and with 0xe to see if italics should be turned on
  30357. if ((char1 & 0xe) === 0xe) {
  30358. this.addFormatting(packet.pts, ['i']);
  30359. }
  30360. } // We have a normal character in char0, and possibly one in char1
  30361. } else if (this.isNormalChar(char0)) {
  30362. if (char1 === 0x00) {
  30363. char1 = null;
  30364. }
  30365. text = getCharFromCode(char0);
  30366. text += getCharFromCode(char1);
  30367. this[this.mode_](packet.pts, text);
  30368. this.column_ += text.length;
  30369. } // finish data processing
  30370. };
  30371. };
  30372. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  30373. // display buffer
  30374. Cea608Stream.prototype.flushDisplayed = function (pts) {
  30375. var content = this.displayed_ // remove spaces from the start and end of the string
  30376. .map(function (row, index) {
  30377. try {
  30378. return row.trim();
  30379. } catch (e) {
  30380. // Ordinarily, this shouldn't happen. However, caption
  30381. // parsing errors should not throw exceptions and
  30382. // break playback.
  30383. this.trigger('log', {
  30384. level: 'warn',
  30385. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  30386. });
  30387. return '';
  30388. }
  30389. }, this) // combine all text rows to display in one cue
  30390. .join('\n') // and remove blank rows from the start and end, but not the middle
  30391. .replace(/^\n+|\n+$/g, '');
  30392. if (content.length) {
  30393. this.trigger('data', {
  30394. startPts: this.startPts_,
  30395. endPts: pts,
  30396. text: content,
  30397. stream: this.name_
  30398. });
  30399. }
  30400. };
  30401. /**
  30402. * Zero out the data, used for startup and on seek
  30403. */
  30404. Cea608Stream.prototype.reset = function () {
  30405. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  30406. // actually display captions. If a caption is shifted to a row
  30407. // with a lower index than this, it is cleared from the display
  30408. // buffer
  30409. this.topRow_ = 0;
  30410. this.startPts_ = 0;
  30411. this.displayed_ = createDisplayBuffer();
  30412. this.nonDisplayed_ = createDisplayBuffer();
  30413. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  30414. this.column_ = 0;
  30415. this.row_ = BOTTOM_ROW;
  30416. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  30417. this.formatting_ = [];
  30418. };
  30419. /**
  30420. * Sets up control code and related constants for this instance
  30421. */
  30422. Cea608Stream.prototype.setConstants = function () {
  30423. // The following attributes have these uses:
  30424. // ext_ : char0 for mid-row codes, and the base for extended
  30425. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  30426. // extended codes)
  30427. // control_: char0 for control codes, except byte-shifted to the
  30428. // left so that we can do this.control_ | CONTROL_CODE
  30429. // offset_: char0 for tab offset codes
  30430. //
  30431. // It's also worth noting that control codes, and _only_ control codes,
  30432. // differ between field 1 and field2. Field 2 control codes are always
  30433. // their field 1 value plus 1. That's why there's the "| field" on the
  30434. // control value.
  30435. if (this.dataChannel_ === 0) {
  30436. this.BASE_ = 0x10;
  30437. this.EXT_ = 0x11;
  30438. this.CONTROL_ = (0x14 | this.field_) << 8;
  30439. this.OFFSET_ = 0x17;
  30440. } else if (this.dataChannel_ === 1) {
  30441. this.BASE_ = 0x18;
  30442. this.EXT_ = 0x19;
  30443. this.CONTROL_ = (0x1c | this.field_) << 8;
  30444. this.OFFSET_ = 0x1f;
  30445. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  30446. // list is not exhaustive. For a more comprehensive listing and semantics see
  30447. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  30448. // Padding
  30449. this.PADDING_ = 0x0000; // Pop-on Mode
  30450. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  30451. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  30452. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  30453. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  30454. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  30455. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  30456. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  30457. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  30458. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  30459. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  30460. };
  30461. /**
  30462. * Detects if the 2-byte packet data is a special character
  30463. *
  30464. * Special characters have a second byte in the range 0x30 to 0x3f,
  30465. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  30466. * data channel 2).
  30467. *
  30468. * @param {Integer} char0 The first byte
  30469. * @param {Integer} char1 The second byte
  30470. * @return {Boolean} Whether the 2 bytes are an special character
  30471. */
  30472. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  30473. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  30474. };
  30475. /**
  30476. * Detects if the 2-byte packet data is an extended character
  30477. *
  30478. * Extended characters have a second byte in the range 0x20 to 0x3f,
  30479. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  30480. * 0x1a or 0x1b (for data channel 2).
  30481. *
  30482. * @param {Integer} char0 The first byte
  30483. * @param {Integer} char1 The second byte
  30484. * @return {Boolean} Whether the 2 bytes are an extended character
  30485. */
  30486. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  30487. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  30488. };
  30489. /**
  30490. * Detects if the 2-byte packet is a mid-row code
  30491. *
  30492. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  30493. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  30494. * channel 2).
  30495. *
  30496. * @param {Integer} char0 The first byte
  30497. * @param {Integer} char1 The second byte
  30498. * @return {Boolean} Whether the 2 bytes are a mid-row code
  30499. */
  30500. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  30501. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  30502. };
  30503. /**
  30504. * Detects if the 2-byte packet is an offset control code
  30505. *
  30506. * Offset control codes have a second byte in the range 0x21 to 0x23,
  30507. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  30508. * data channel 2).
  30509. *
  30510. * @param {Integer} char0 The first byte
  30511. * @param {Integer} char1 The second byte
  30512. * @return {Boolean} Whether the 2 bytes are an offset control code
  30513. */
  30514. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  30515. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  30516. };
  30517. /**
  30518. * Detects if the 2-byte packet is a Preamble Address Code
  30519. *
  30520. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  30521. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  30522. * range 0x40 to 0x7f.
  30523. *
  30524. * @param {Integer} char0 The first byte
  30525. * @param {Integer} char1 The second byte
  30526. * @return {Boolean} Whether the 2 bytes are a PAC
  30527. */
  30528. Cea608Stream.prototype.isPAC = function (char0, char1) {
  30529. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  30530. };
  30531. /**
  30532. * Detects if a packet's second byte is in the range of a PAC color code
  30533. *
  30534. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  30535. * 0x60 to 0x6f.
  30536. *
  30537. * @param {Integer} char1 The second byte
  30538. * @return {Boolean} Whether the byte is a color PAC
  30539. */
  30540. Cea608Stream.prototype.isColorPAC = function (char1) {
  30541. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  30542. };
  30543. /**
  30544. * Detects if a single byte is in the range of a normal character
  30545. *
  30546. * Normal text bytes are in the range 0x20 to 0x7f.
  30547. *
  30548. * @param {Integer} char The byte
  30549. * @return {Boolean} Whether the byte is a normal character
  30550. */
  30551. Cea608Stream.prototype.isNormalChar = function (char) {
  30552. return char >= 0x20 && char <= 0x7f;
  30553. };
  30554. /**
  30555. * Configures roll-up
  30556. *
  30557. * @param {Integer} pts Current PTS
  30558. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  30559. * a new position
  30560. */
  30561. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  30562. // Reset the base row to the bottom row when switching modes
  30563. if (this.mode_ !== 'rollUp') {
  30564. this.row_ = BOTTOM_ROW;
  30565. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  30566. this.flushDisplayed(pts);
  30567. this.nonDisplayed_ = createDisplayBuffer();
  30568. this.displayed_ = createDisplayBuffer();
  30569. }
  30570. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  30571. // move currently displayed captions (up or down) to the new base row
  30572. for (var i = 0; i < this.rollUpRows_; i++) {
  30573. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  30574. this.displayed_[this.row_ - i] = '';
  30575. }
  30576. }
  30577. if (newBaseRow === undefined) {
  30578. newBaseRow = this.row_;
  30579. }
  30580. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  30581. }; // Adds the opening HTML tag for the passed character to the caption text,
  30582. // and keeps track of it for later closing
  30583. Cea608Stream.prototype.addFormatting = function (pts, format) {
  30584. this.formatting_ = this.formatting_.concat(format);
  30585. var text = format.reduce(function (text, format) {
  30586. return text + '<' + format + '>';
  30587. }, '');
  30588. this[this.mode_](pts, text);
  30589. }; // Adds HTML closing tags for current formatting to caption text and
  30590. // clears remembered formatting
  30591. Cea608Stream.prototype.clearFormatting = function (pts) {
  30592. if (!this.formatting_.length) {
  30593. return;
  30594. }
  30595. var text = this.formatting_.reverse().reduce(function (text, format) {
  30596. return text + '</' + format + '>';
  30597. }, '');
  30598. this.formatting_ = [];
  30599. this[this.mode_](pts, text);
  30600. }; // Mode Implementations
  30601. Cea608Stream.prototype.popOn = function (pts, text) {
  30602. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  30603. baseRow += text;
  30604. this.nonDisplayed_[this.row_] = baseRow;
  30605. };
  30606. Cea608Stream.prototype.rollUp = function (pts, text) {
  30607. var baseRow = this.displayed_[this.row_];
  30608. baseRow += text;
  30609. this.displayed_[this.row_] = baseRow;
  30610. };
  30611. Cea608Stream.prototype.shiftRowsUp_ = function () {
  30612. var i; // clear out inactive rows
  30613. for (i = 0; i < this.topRow_; i++) {
  30614. this.displayed_[i] = '';
  30615. }
  30616. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  30617. this.displayed_[i] = '';
  30618. } // shift displayed rows up
  30619. for (i = this.topRow_; i < this.row_; i++) {
  30620. this.displayed_[i] = this.displayed_[i + 1];
  30621. } // clear out the bottom row
  30622. this.displayed_[this.row_] = '';
  30623. };
  30624. Cea608Stream.prototype.paintOn = function (pts, text) {
  30625. var baseRow = this.displayed_[this.row_];
  30626. baseRow += text;
  30627. this.displayed_[this.row_] = baseRow;
  30628. }; // exports
  30629. var captionStream = {
  30630. CaptionStream: CaptionStream$2,
  30631. Cea608Stream: Cea608Stream,
  30632. Cea708Stream: Cea708Stream
  30633. };
  30634. /**
  30635. * mux.js
  30636. *
  30637. * Copyright (c) Brightcove
  30638. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30639. */
  30640. var streamTypes = {
  30641. H264_STREAM_TYPE: 0x1B,
  30642. ADTS_STREAM_TYPE: 0x0F,
  30643. METADATA_STREAM_TYPE: 0x15
  30644. };
  30645. /**
  30646. * mux.js
  30647. *
  30648. * Copyright (c) Brightcove
  30649. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30650. *
  30651. * Accepts program elementary stream (PES) data events and corrects
  30652. * decode and presentation time stamps to account for a rollover
  30653. * of the 33 bit value.
  30654. */
  30655. var Stream$6 = stream;
  30656. var MAX_TS = 8589934592;
  30657. var RO_THRESH = 4294967296;
  30658. var TYPE_SHARED = 'shared';
  30659. var handleRollover$1 = function (value, reference) {
  30660. var direction = 1;
  30661. if (value > reference) {
  30662. // If the current timestamp value is greater than our reference timestamp and we detect a
  30663. // timestamp rollover, this means the roll over is happening in the opposite direction.
  30664. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  30665. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  30666. // rollover point. In loading this segment, the timestamp values will be very large,
  30667. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  30668. // the time stamp to be `value - 2^33`.
  30669. direction = -1;
  30670. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  30671. // cause an incorrect adjustment.
  30672. while (Math.abs(reference - value) > RO_THRESH) {
  30673. value += direction * MAX_TS;
  30674. }
  30675. return value;
  30676. };
  30677. var TimestampRolloverStream$1 = function (type) {
  30678. var lastDTS, referenceDTS;
  30679. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  30680. // video and audio. We could use `undefined` here, but having a string
  30681. // makes debugging a little clearer.
  30682. this.type_ = type || TYPE_SHARED;
  30683. this.push = function (data) {
  30684. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  30685. // streams will only accept data that matches their type.
  30686. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  30687. return;
  30688. }
  30689. if (referenceDTS === undefined) {
  30690. referenceDTS = data.dts;
  30691. }
  30692. data.dts = handleRollover$1(data.dts, referenceDTS);
  30693. data.pts = handleRollover$1(data.pts, referenceDTS);
  30694. lastDTS = data.dts;
  30695. this.trigger('data', data);
  30696. };
  30697. this.flush = function () {
  30698. referenceDTS = lastDTS;
  30699. this.trigger('done');
  30700. };
  30701. this.endTimeline = function () {
  30702. this.flush();
  30703. this.trigger('endedtimeline');
  30704. };
  30705. this.discontinuity = function () {
  30706. referenceDTS = void 0;
  30707. lastDTS = void 0;
  30708. };
  30709. this.reset = function () {
  30710. this.discontinuity();
  30711. this.trigger('reset');
  30712. };
  30713. };
  30714. TimestampRolloverStream$1.prototype = new Stream$6();
  30715. var timestampRolloverStream = {
  30716. TimestampRolloverStream: TimestampRolloverStream$1,
  30717. handleRollover: handleRollover$1
  30718. }; // Once IE11 support is dropped, this function should be removed.
  30719. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  30720. if (!typedArray) {
  30721. return -1;
  30722. }
  30723. var currentIndex = fromIndex;
  30724. for (; currentIndex < typedArray.length; currentIndex++) {
  30725. if (typedArray[currentIndex] === element) {
  30726. return currentIndex;
  30727. }
  30728. }
  30729. return -1;
  30730. };
  30731. var typedArray = {
  30732. typedArrayIndexOf: typedArrayIndexOf$1
  30733. };
  30734. /**
  30735. * mux.js
  30736. *
  30737. * Copyright (c) Brightcove
  30738. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30739. *
  30740. * Tools for parsing ID3 frame data
  30741. * @see http://id3.org/id3v2.3.0
  30742. */
  30743. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  30744. // Frames that allow different types of text encoding contain a text
  30745. // encoding description byte [ID3v2.4.0 section 4.]
  30746. textEncodingDescriptionByte = {
  30747. Iso88591: 0x00,
  30748. // ISO-8859-1, terminated with \0.
  30749. Utf16: 0x01,
  30750. // UTF-16 encoded Unicode BOM, terminated with \0\0
  30751. Utf16be: 0x02,
  30752. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  30753. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  30754. },
  30755. // return a percent-encoded representation of the specified byte range
  30756. // @see http://en.wikipedia.org/wiki/Percent-encoding
  30757. percentEncode$1 = function (bytes, start, end) {
  30758. var i,
  30759. result = '';
  30760. for (i = start; i < end; i++) {
  30761. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  30762. }
  30763. return result;
  30764. },
  30765. // return the string representation of the specified byte range,
  30766. // interpreted as UTf-8.
  30767. parseUtf8 = function (bytes, start, end) {
  30768. return decodeURIComponent(percentEncode$1(bytes, start, end));
  30769. },
  30770. // return the string representation of the specified byte range,
  30771. // interpreted as ISO-8859-1.
  30772. parseIso88591$1 = function (bytes, start, end) {
  30773. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  30774. },
  30775. parseSyncSafeInteger$1 = function (data) {
  30776. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  30777. },
  30778. frameParsers = {
  30779. 'APIC': function (frame) {
  30780. var i = 1,
  30781. mimeTypeEndIndex,
  30782. descriptionEndIndex,
  30783. LINK_MIME_TYPE = '-->';
  30784. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30785. // ignore frames with unrecognized character encodings
  30786. return;
  30787. } // parsing fields [ID3v2.4.0 section 4.14.]
  30788. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  30789. if (mimeTypeEndIndex < 0) {
  30790. // malformed frame
  30791. return;
  30792. } // parsing Mime type field (terminated with \0)
  30793. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  30794. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  30795. frame.pictureType = frame.data[i];
  30796. i++;
  30797. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  30798. if (descriptionEndIndex < 0) {
  30799. // malformed frame
  30800. return;
  30801. } // parsing Description field (terminated with \0)
  30802. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  30803. i = descriptionEndIndex + 1;
  30804. if (frame.mimeType === LINK_MIME_TYPE) {
  30805. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  30806. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  30807. } else {
  30808. // parsing Picture Data field as binary data
  30809. frame.pictureData = frame.data.subarray(i, frame.data.length);
  30810. }
  30811. },
  30812. 'T*': function (frame) {
  30813. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30814. // ignore frames with unrecognized character encodings
  30815. return;
  30816. } // parse text field, do not include null terminator in the frame value
  30817. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  30818. frame.value = parseUtf8(frame.data, 1, frame.data.length).replace(/\0*$/, ''); // text information frames supports multiple strings, stored as a terminator separated list [ID3v2.4.0 section 4.2.]
  30819. frame.values = frame.value.split('\0');
  30820. },
  30821. 'TXXX': function (frame) {
  30822. var descriptionEndIndex;
  30823. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30824. // ignore frames with unrecognized character encodings
  30825. return;
  30826. }
  30827. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  30828. if (descriptionEndIndex === -1) {
  30829. return;
  30830. } // parse the text fields
  30831. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  30832. // frames that allow different types of encoding contain terminated text
  30833. // [ID3v2.4.0 section 4.]
  30834. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  30835. frame.data = frame.value;
  30836. },
  30837. 'W*': function (frame) {
  30838. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  30839. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  30840. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  30841. },
  30842. 'WXXX': function (frame) {
  30843. var descriptionEndIndex;
  30844. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  30845. // ignore frames with unrecognized character encodings
  30846. return;
  30847. }
  30848. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  30849. if (descriptionEndIndex === -1) {
  30850. return;
  30851. } // parse the description and URL fields
  30852. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  30853. // if the value is followed by a string termination all the following information
  30854. // should be ignored [ID3v2.4.0 section 4.3]
  30855. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  30856. },
  30857. 'PRIV': function (frame) {
  30858. var i;
  30859. for (i = 0; i < frame.data.length; i++) {
  30860. if (frame.data[i] === 0) {
  30861. // parse the description and URL fields
  30862. frame.owner = parseIso88591$1(frame.data, 0, i);
  30863. break;
  30864. }
  30865. }
  30866. frame.privateData = frame.data.subarray(i + 1);
  30867. frame.data = frame.privateData;
  30868. }
  30869. };
  30870. var parseId3Frames$1 = function (data) {
  30871. var frameSize,
  30872. frameHeader,
  30873. frameStart = 10,
  30874. tagSize = 0,
  30875. frames = []; // If we don't have enough data for a header, 10 bytes,
  30876. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  30877. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  30878. return;
  30879. } // the frame size is transmitted as a 28-bit integer in the
  30880. // last four bytes of the ID3 header.
  30881. // The most significant bit of each byte is dropped and the
  30882. // results concatenated to recover the actual value.
  30883. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  30884. // convenient for our comparisons to include it
  30885. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  30886. var hasExtendedHeader = data[5] & 0x40;
  30887. if (hasExtendedHeader) {
  30888. // advance the frame start past the extended header
  30889. frameStart += 4; // header size field
  30890. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  30891. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  30892. } // parse one or more ID3 frames
  30893. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  30894. do {
  30895. // determine the number of bytes in this frame
  30896. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  30897. if (frameSize < 1) {
  30898. break;
  30899. }
  30900. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  30901. var frame = {
  30902. id: frameHeader,
  30903. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  30904. };
  30905. frame.key = frame.id; // parse frame values
  30906. if (frameParsers[frame.id]) {
  30907. // use frame specific parser
  30908. frameParsers[frame.id](frame);
  30909. } else if (frame.id[0] === 'T') {
  30910. // use text frame generic parser
  30911. frameParsers['T*'](frame);
  30912. } else if (frame.id[0] === 'W') {
  30913. // use URL link frame generic parser
  30914. frameParsers['W*'](frame);
  30915. }
  30916. frames.push(frame);
  30917. frameStart += 10; // advance past the frame header
  30918. frameStart += frameSize; // advance past the frame body
  30919. } while (frameStart < tagSize);
  30920. return frames;
  30921. };
  30922. var parseId3 = {
  30923. parseId3Frames: parseId3Frames$1,
  30924. parseSyncSafeInteger: parseSyncSafeInteger$1,
  30925. frameParsers: frameParsers
  30926. };
  30927. /**
  30928. * mux.js
  30929. *
  30930. * Copyright (c) Brightcove
  30931. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30932. *
  30933. * Accepts program elementary stream (PES) data events and parses out
  30934. * ID3 metadata from them, if present.
  30935. * @see http://id3.org/id3v2.3.0
  30936. */
  30937. var Stream$5 = stream,
  30938. StreamTypes$3 = streamTypes,
  30939. id3 = parseId3,
  30940. MetadataStream;
  30941. MetadataStream = function (options) {
  30942. var settings = {
  30943. // the bytes of the program-level descriptor field in MP2T
  30944. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  30945. // program element descriptors"
  30946. descriptor: options && options.descriptor
  30947. },
  30948. // the total size in bytes of the ID3 tag being parsed
  30949. tagSize = 0,
  30950. // tag data that is not complete enough to be parsed
  30951. buffer = [],
  30952. // the total number of bytes currently in the buffer
  30953. bufferSize = 0,
  30954. i;
  30955. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  30956. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  30957. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  30958. if (settings.descriptor) {
  30959. for (i = 0; i < settings.descriptor.length; i++) {
  30960. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  30961. }
  30962. }
  30963. this.push = function (chunk) {
  30964. var tag, frameStart, frameSize, frame, i, frameHeader;
  30965. if (chunk.type !== 'timed-metadata') {
  30966. return;
  30967. } // if data_alignment_indicator is set in the PES header,
  30968. // we must have the start of a new ID3 tag. Assume anything
  30969. // remaining in the buffer was malformed and throw it out
  30970. if (chunk.dataAlignmentIndicator) {
  30971. bufferSize = 0;
  30972. buffer.length = 0;
  30973. } // ignore events that don't look like ID3 data
  30974. if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
  30975. this.trigger('log', {
  30976. level: 'warn',
  30977. message: 'Skipping unrecognized metadata packet'
  30978. });
  30979. return;
  30980. } // add this chunk to the data we've collected so far
  30981. buffer.push(chunk);
  30982. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  30983. if (buffer.length === 1) {
  30984. // the frame size is transmitted as a 28-bit integer in the
  30985. // last four bytes of the ID3 header.
  30986. // The most significant bit of each byte is dropped and the
  30987. // results concatenated to recover the actual value.
  30988. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  30989. // convenient for our comparisons to include it
  30990. tagSize += 10;
  30991. } // if the entire frame has not arrived, wait for more data
  30992. if (bufferSize < tagSize) {
  30993. return;
  30994. } // collect the entire frame so it can be parsed
  30995. tag = {
  30996. data: new Uint8Array(tagSize),
  30997. frames: [],
  30998. pts: buffer[0].pts,
  30999. dts: buffer[0].dts
  31000. };
  31001. for (i = 0; i < tagSize;) {
  31002. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  31003. i += buffer[0].data.byteLength;
  31004. bufferSize -= buffer[0].data.byteLength;
  31005. buffer.shift();
  31006. } // find the start of the first frame and the end of the tag
  31007. frameStart = 10;
  31008. if (tag.data[5] & 0x40) {
  31009. // advance the frame start past the extended header
  31010. frameStart += 4; // header size field
  31011. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  31012. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  31013. } // parse one or more ID3 frames
  31014. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  31015. do {
  31016. // determine the number of bytes in this frame
  31017. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  31018. if (frameSize < 1) {
  31019. this.trigger('log', {
  31020. level: 'warn',
  31021. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  31022. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  31023. // to be sent along.
  31024. break;
  31025. }
  31026. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  31027. frame = {
  31028. id: frameHeader,
  31029. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  31030. };
  31031. frame.key = frame.id; // parse frame values
  31032. if (id3.frameParsers[frame.id]) {
  31033. // use frame specific parser
  31034. id3.frameParsers[frame.id](frame);
  31035. } else if (frame.id[0] === 'T') {
  31036. // use text frame generic parser
  31037. id3.frameParsers['T*'](frame);
  31038. } else if (frame.id[0] === 'W') {
  31039. // use URL link frame generic parser
  31040. id3.frameParsers['W*'](frame);
  31041. } // handle the special PRIV frame used to indicate the start
  31042. // time for raw AAC data
  31043. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  31044. var d = frame.data,
  31045. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  31046. size *= 4;
  31047. size += d[7] & 0x03;
  31048. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  31049. // on the value of this frame
  31050. // we couldn't have known the appropriate pts and dts before
  31051. // parsing this ID3 tag so set those values now
  31052. if (tag.pts === undefined && tag.dts === undefined) {
  31053. tag.pts = frame.timeStamp;
  31054. tag.dts = frame.timeStamp;
  31055. }
  31056. this.trigger('timestamp', frame);
  31057. }
  31058. tag.frames.push(frame);
  31059. frameStart += 10; // advance past the frame header
  31060. frameStart += frameSize; // advance past the frame body
  31061. } while (frameStart < tagSize);
  31062. this.trigger('data', tag);
  31063. };
  31064. };
  31065. MetadataStream.prototype = new Stream$5();
  31066. var metadataStream = MetadataStream;
  31067. /**
  31068. * mux.js
  31069. *
  31070. * Copyright (c) Brightcove
  31071. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31072. *
  31073. * A stream-based mp2t to mp4 converter. This utility can be used to
  31074. * deliver mp4s to a SourceBuffer on platforms that support native
  31075. * Media Source Extensions.
  31076. */
  31077. var Stream$4 = stream,
  31078. CaptionStream$1 = captionStream,
  31079. StreamTypes$2 = streamTypes,
  31080. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  31081. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  31082. var MP2T_PACKET_LENGTH$1 = 188,
  31083. // bytes
  31084. SYNC_BYTE$1 = 0x47;
  31085. /**
  31086. * Splits an incoming stream of binary data into MPEG-2 Transport
  31087. * Stream packets.
  31088. */
  31089. TransportPacketStream = function () {
  31090. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  31091. bytesInBuffer = 0;
  31092. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  31093. /**
  31094. * Split a stream of data into M2TS packets
  31095. **/
  31096. this.push = function (bytes) {
  31097. var startIndex = 0,
  31098. endIndex = MP2T_PACKET_LENGTH$1,
  31099. everything; // If there are bytes remaining from the last segment, prepend them to the
  31100. // bytes that were pushed in
  31101. if (bytesInBuffer) {
  31102. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  31103. everything.set(buffer.subarray(0, bytesInBuffer));
  31104. everything.set(bytes, bytesInBuffer);
  31105. bytesInBuffer = 0;
  31106. } else {
  31107. everything = bytes;
  31108. } // While we have enough data for a packet
  31109. while (endIndex < everything.byteLength) {
  31110. // Look for a pair of start and end sync bytes in the data..
  31111. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  31112. // We found a packet so emit it and jump one whole packet forward in
  31113. // the stream
  31114. this.trigger('data', everything.subarray(startIndex, endIndex));
  31115. startIndex += MP2T_PACKET_LENGTH$1;
  31116. endIndex += MP2T_PACKET_LENGTH$1;
  31117. continue;
  31118. } // If we get here, we have somehow become de-synchronized and we need to step
  31119. // forward one byte at a time until we find a pair of sync bytes that denote
  31120. // a packet
  31121. startIndex++;
  31122. endIndex++;
  31123. } // If there was some data left over at the end of the segment that couldn't
  31124. // possibly be a whole packet, keep it because it might be the start of a packet
  31125. // that continues in the next segment
  31126. if (startIndex < everything.byteLength) {
  31127. buffer.set(everything.subarray(startIndex), 0);
  31128. bytesInBuffer = everything.byteLength - startIndex;
  31129. }
  31130. };
  31131. /**
  31132. * Passes identified M2TS packets to the TransportParseStream to be parsed
  31133. **/
  31134. this.flush = function () {
  31135. // If the buffer contains a whole packet when we are being flushed, emit it
  31136. // and empty the buffer. Otherwise hold onto the data because it may be
  31137. // important for decoding the next segment
  31138. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  31139. this.trigger('data', buffer);
  31140. bytesInBuffer = 0;
  31141. }
  31142. this.trigger('done');
  31143. };
  31144. this.endTimeline = function () {
  31145. this.flush();
  31146. this.trigger('endedtimeline');
  31147. };
  31148. this.reset = function () {
  31149. bytesInBuffer = 0;
  31150. this.trigger('reset');
  31151. };
  31152. };
  31153. TransportPacketStream.prototype = new Stream$4();
  31154. /**
  31155. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  31156. * forms of the individual transport stream packets.
  31157. */
  31158. TransportParseStream = function () {
  31159. var parsePsi, parsePat, parsePmt, self;
  31160. TransportParseStream.prototype.init.call(this);
  31161. self = this;
  31162. this.packetsWaitingForPmt = [];
  31163. this.programMapTable = undefined;
  31164. parsePsi = function (payload, psi) {
  31165. var offset = 0; // PSI packets may be split into multiple sections and those
  31166. // sections may be split into multiple packets. If a PSI
  31167. // section starts in this packet, the payload_unit_start_indicator
  31168. // will be true and the first byte of the payload will indicate
  31169. // the offset from the current position to the start of the
  31170. // section.
  31171. if (psi.payloadUnitStartIndicator) {
  31172. offset += payload[offset] + 1;
  31173. }
  31174. if (psi.type === 'pat') {
  31175. parsePat(payload.subarray(offset), psi);
  31176. } else {
  31177. parsePmt(payload.subarray(offset), psi);
  31178. }
  31179. };
  31180. parsePat = function (payload, pat) {
  31181. pat.section_number = payload[7]; // eslint-disable-line camelcase
  31182. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  31183. // skip the PSI header and parse the first PMT entry
  31184. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  31185. pat.pmtPid = self.pmtPid;
  31186. };
  31187. /**
  31188. * Parse out the relevant fields of a Program Map Table (PMT).
  31189. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  31190. * packet. The first byte in this array should be the table_id
  31191. * field.
  31192. * @param pmt {object} the object that should be decorated with
  31193. * fields parsed from the PMT.
  31194. */
  31195. parsePmt = function (payload, pmt) {
  31196. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  31197. // take effect. We don't believe this should ever be the case
  31198. // for HLS but we'll ignore "forward" PMT declarations if we see
  31199. // them. Future PMT declarations have the current_next_indicator
  31200. // set to zero.
  31201. if (!(payload[5] & 0x01)) {
  31202. return;
  31203. } // overwrite any existing program map table
  31204. self.programMapTable = {
  31205. video: null,
  31206. audio: null,
  31207. 'timed-metadata': {}
  31208. }; // the mapping table ends at the end of the current section
  31209. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  31210. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  31211. // long the program info descriptors are
  31212. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  31213. offset = 12 + programInfoLength;
  31214. while (offset < tableEnd) {
  31215. var streamType = payload[offset];
  31216. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  31217. // TODO: should this be done for metadata too? for now maintain behavior of
  31218. // multiple metadata streams
  31219. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  31220. self.programMapTable.video = pid;
  31221. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  31222. self.programMapTable.audio = pid;
  31223. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  31224. // map pid to stream type for metadata streams
  31225. self.programMapTable['timed-metadata'][pid] = streamType;
  31226. } // move to the next table entry
  31227. // skip past the elementary stream descriptors, if present
  31228. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  31229. } // record the map on the packet as well
  31230. pmt.programMapTable = self.programMapTable;
  31231. };
  31232. /**
  31233. * Deliver a new MP2T packet to the next stream in the pipeline.
  31234. */
  31235. this.push = function (packet) {
  31236. var result = {},
  31237. offset = 4;
  31238. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  31239. result.pid = packet[1] & 0x1f;
  31240. result.pid <<= 8;
  31241. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  31242. // fifth byte of the TS packet header. The adaptation field is
  31243. // used to add stuffing to PES packets that don't fill a complete
  31244. // TS packet, and to specify some forms of timing and control data
  31245. // that we do not currently use.
  31246. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  31247. offset += packet[offset] + 1;
  31248. } // parse the rest of the packet based on the type
  31249. if (result.pid === 0) {
  31250. result.type = 'pat';
  31251. parsePsi(packet.subarray(offset), result);
  31252. this.trigger('data', result);
  31253. } else if (result.pid === this.pmtPid) {
  31254. result.type = 'pmt';
  31255. parsePsi(packet.subarray(offset), result);
  31256. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  31257. while (this.packetsWaitingForPmt.length) {
  31258. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  31259. }
  31260. } else if (this.programMapTable === undefined) {
  31261. // When we have not seen a PMT yet, defer further processing of
  31262. // PES packets until one has been parsed
  31263. this.packetsWaitingForPmt.push([packet, offset, result]);
  31264. } else {
  31265. this.processPes_(packet, offset, result);
  31266. }
  31267. };
  31268. this.processPes_ = function (packet, offset, result) {
  31269. // set the appropriate stream type
  31270. if (result.pid === this.programMapTable.video) {
  31271. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  31272. } else if (result.pid === this.programMapTable.audio) {
  31273. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  31274. } else {
  31275. // if not video or audio, it is timed-metadata or unknown
  31276. // if unknown, streamType will be undefined
  31277. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  31278. }
  31279. result.type = 'pes';
  31280. result.data = packet.subarray(offset);
  31281. this.trigger('data', result);
  31282. };
  31283. };
  31284. TransportParseStream.prototype = new Stream$4();
  31285. TransportParseStream.STREAM_TYPES = {
  31286. h264: 0x1b,
  31287. adts: 0x0f
  31288. };
  31289. /**
  31290. * Reconsistutes program elementary stream (PES) packets from parsed
  31291. * transport stream packets. That is, if you pipe an
  31292. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  31293. * events will be events which capture the bytes for individual PES
  31294. * packets plus relevant metadata that has been extracted from the
  31295. * container.
  31296. */
  31297. ElementaryStream = function () {
  31298. var self = this,
  31299. segmentHadPmt = false,
  31300. // PES packet fragments
  31301. video = {
  31302. data: [],
  31303. size: 0
  31304. },
  31305. audio = {
  31306. data: [],
  31307. size: 0
  31308. },
  31309. timedMetadata = {
  31310. data: [],
  31311. size: 0
  31312. },
  31313. programMapTable,
  31314. parsePes = function (payload, pes) {
  31315. var ptsDtsFlags;
  31316. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  31317. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  31318. // that are frame data that is continuing from the previous fragment. This
  31319. // is to check that the pes data is the start of a new pes payload
  31320. if (startPrefix !== 1) {
  31321. return;
  31322. } // get the packet length, this will be 0 for video
  31323. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  31324. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  31325. // and a DTS value. Determine what combination of values is
  31326. // available to work with.
  31327. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  31328. // performs all bitwise operations on 32-bit integers but javascript
  31329. // supports a much greater range (52-bits) of integer using standard
  31330. // mathematical operations.
  31331. // We construct a 31-bit value using bitwise operators over the 31
  31332. // most significant bits and then multiply by 4 (equal to a left-shift
  31333. // of 2) before we add the final 2 least significant bits of the
  31334. // timestamp (equal to an OR.)
  31335. if (ptsDtsFlags & 0xC0) {
  31336. // the PTS and DTS are not written out directly. For information
  31337. // on how they are encoded, see
  31338. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  31339. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  31340. pes.pts *= 4; // Left shift by 2
  31341. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  31342. pes.dts = pes.pts;
  31343. if (ptsDtsFlags & 0x40) {
  31344. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  31345. pes.dts *= 4; // Left shift by 2
  31346. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  31347. }
  31348. } // the data section starts immediately after the PES header.
  31349. // pes_header_data_length specifies the number of header bytes
  31350. // that follow the last byte of the field.
  31351. pes.data = payload.subarray(9 + payload[8]);
  31352. },
  31353. /**
  31354. * Pass completely parsed PES packets to the next stream in the pipeline
  31355. **/
  31356. flushStream = function (stream, type, forceFlush) {
  31357. var packetData = new Uint8Array(stream.size),
  31358. event = {
  31359. type: type
  31360. },
  31361. i = 0,
  31362. offset = 0,
  31363. packetFlushable = false,
  31364. fragment; // do nothing if there is not enough buffered data for a complete
  31365. // PES header
  31366. if (!stream.data.length || stream.size < 9) {
  31367. return;
  31368. }
  31369. event.trackId = stream.data[0].pid; // reassemble the packet
  31370. for (i = 0; i < stream.data.length; i++) {
  31371. fragment = stream.data[i];
  31372. packetData.set(fragment.data, offset);
  31373. offset += fragment.data.byteLength;
  31374. } // parse assembled packet's PES header
  31375. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  31376. // check that there is enough stream data to fill the packet
  31377. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  31378. if (forceFlush || packetFlushable) {
  31379. stream.size = 0;
  31380. stream.data.length = 0;
  31381. } // only emit packets that are complete. this is to avoid assembling
  31382. // incomplete PES packets due to poor segmentation
  31383. if (packetFlushable) {
  31384. self.trigger('data', event);
  31385. }
  31386. };
  31387. ElementaryStream.prototype.init.call(this);
  31388. /**
  31389. * Identifies M2TS packet types and parses PES packets using metadata
  31390. * parsed from the PMT
  31391. **/
  31392. this.push = function (data) {
  31393. ({
  31394. pat: function () {// we have to wait for the PMT to arrive as well before we
  31395. // have any meaningful metadata
  31396. },
  31397. pes: function () {
  31398. var stream, streamType;
  31399. switch (data.streamType) {
  31400. case StreamTypes$2.H264_STREAM_TYPE:
  31401. stream = video;
  31402. streamType = 'video';
  31403. break;
  31404. case StreamTypes$2.ADTS_STREAM_TYPE:
  31405. stream = audio;
  31406. streamType = 'audio';
  31407. break;
  31408. case StreamTypes$2.METADATA_STREAM_TYPE:
  31409. stream = timedMetadata;
  31410. streamType = 'timed-metadata';
  31411. break;
  31412. default:
  31413. // ignore unknown stream types
  31414. return;
  31415. } // if a new packet is starting, we can flush the completed
  31416. // packet
  31417. if (data.payloadUnitStartIndicator) {
  31418. flushStream(stream, streamType, true);
  31419. } // buffer this fragment until we are sure we've received the
  31420. // complete payload
  31421. stream.data.push(data);
  31422. stream.size += data.data.byteLength;
  31423. },
  31424. pmt: function () {
  31425. var event = {
  31426. type: 'metadata',
  31427. tracks: []
  31428. };
  31429. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  31430. if (programMapTable.video !== null) {
  31431. event.tracks.push({
  31432. timelineStartInfo: {
  31433. baseMediaDecodeTime: 0
  31434. },
  31435. id: +programMapTable.video,
  31436. codec: 'avc',
  31437. type: 'video'
  31438. });
  31439. }
  31440. if (programMapTable.audio !== null) {
  31441. event.tracks.push({
  31442. timelineStartInfo: {
  31443. baseMediaDecodeTime: 0
  31444. },
  31445. id: +programMapTable.audio,
  31446. codec: 'adts',
  31447. type: 'audio'
  31448. });
  31449. }
  31450. segmentHadPmt = true;
  31451. self.trigger('data', event);
  31452. }
  31453. })[data.type]();
  31454. };
  31455. this.reset = function () {
  31456. video.size = 0;
  31457. video.data.length = 0;
  31458. audio.size = 0;
  31459. audio.data.length = 0;
  31460. this.trigger('reset');
  31461. };
  31462. /**
  31463. * Flush any remaining input. Video PES packets may be of variable
  31464. * length. Normally, the start of a new video packet can trigger the
  31465. * finalization of the previous packet. That is not possible if no
  31466. * more video is forthcoming, however. In that case, some other
  31467. * mechanism (like the end of the file) has to be employed. When it is
  31468. * clear that no additional data is forthcoming, calling this method
  31469. * will flush the buffered packets.
  31470. */
  31471. this.flushStreams_ = function () {
  31472. // !!THIS ORDER IS IMPORTANT!!
  31473. // video first then audio
  31474. flushStream(video, 'video');
  31475. flushStream(audio, 'audio');
  31476. flushStream(timedMetadata, 'timed-metadata');
  31477. };
  31478. this.flush = function () {
  31479. // if on flush we haven't had a pmt emitted
  31480. // and we have a pmt to emit. emit the pmt
  31481. // so that we trigger a trackinfo downstream.
  31482. if (!segmentHadPmt && programMapTable) {
  31483. var pmt = {
  31484. type: 'metadata',
  31485. tracks: []
  31486. }; // translate audio and video streams to tracks
  31487. if (programMapTable.video !== null) {
  31488. pmt.tracks.push({
  31489. timelineStartInfo: {
  31490. baseMediaDecodeTime: 0
  31491. },
  31492. id: +programMapTable.video,
  31493. codec: 'avc',
  31494. type: 'video'
  31495. });
  31496. }
  31497. if (programMapTable.audio !== null) {
  31498. pmt.tracks.push({
  31499. timelineStartInfo: {
  31500. baseMediaDecodeTime: 0
  31501. },
  31502. id: +programMapTable.audio,
  31503. codec: 'adts',
  31504. type: 'audio'
  31505. });
  31506. }
  31507. self.trigger('data', pmt);
  31508. }
  31509. segmentHadPmt = false;
  31510. this.flushStreams_();
  31511. this.trigger('done');
  31512. };
  31513. };
  31514. ElementaryStream.prototype = new Stream$4();
  31515. var m2ts$1 = {
  31516. PAT_PID: 0x0000,
  31517. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  31518. TransportPacketStream: TransportPacketStream,
  31519. TransportParseStream: TransportParseStream,
  31520. ElementaryStream: ElementaryStream,
  31521. TimestampRolloverStream: TimestampRolloverStream,
  31522. CaptionStream: CaptionStream$1.CaptionStream,
  31523. Cea608Stream: CaptionStream$1.Cea608Stream,
  31524. Cea708Stream: CaptionStream$1.Cea708Stream,
  31525. MetadataStream: metadataStream
  31526. };
  31527. for (var type in StreamTypes$2) {
  31528. if (StreamTypes$2.hasOwnProperty(type)) {
  31529. m2ts$1[type] = StreamTypes$2[type];
  31530. }
  31531. }
  31532. var m2ts_1 = m2ts$1;
  31533. /**
  31534. * mux.js
  31535. *
  31536. * Copyright (c) Brightcove
  31537. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31538. */
  31539. var Stream$3 = stream;
  31540. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  31541. var AdtsStream$1;
  31542. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  31543. /*
  31544. * Accepts a ElementaryStream and emits data events with parsed
  31545. * AAC Audio Frames of the individual packets. Input audio in ADTS
  31546. * format is unpacked and re-emitted as AAC frames.
  31547. *
  31548. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  31549. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  31550. */
  31551. AdtsStream$1 = function (handlePartialSegments) {
  31552. var buffer,
  31553. frameNum = 0;
  31554. AdtsStream$1.prototype.init.call(this);
  31555. this.skipWarn_ = function (start, end) {
  31556. this.trigger('log', {
  31557. level: 'warn',
  31558. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  31559. });
  31560. };
  31561. this.push = function (packet) {
  31562. var i = 0,
  31563. frameLength,
  31564. protectionSkipBytes,
  31565. oldBuffer,
  31566. sampleCount,
  31567. adtsFrameDuration;
  31568. if (!handlePartialSegments) {
  31569. frameNum = 0;
  31570. }
  31571. if (packet.type !== 'audio') {
  31572. // ignore non-audio data
  31573. return;
  31574. } // Prepend any data in the buffer to the input data so that we can parse
  31575. // aac frames the cross a PES packet boundary
  31576. if (buffer && buffer.length) {
  31577. oldBuffer = buffer;
  31578. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  31579. buffer.set(oldBuffer);
  31580. buffer.set(packet.data, oldBuffer.byteLength);
  31581. } else {
  31582. buffer = packet.data;
  31583. } // unpack any ADTS frames which have been fully received
  31584. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  31585. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  31586. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  31587. while (i + 7 < buffer.length) {
  31588. // Look for the start of an ADTS header..
  31589. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  31590. if (typeof skip !== 'number') {
  31591. skip = i;
  31592. } // If a valid header was not found, jump one forward and attempt to
  31593. // find a valid ADTS header starting at the next byte
  31594. i++;
  31595. continue;
  31596. }
  31597. if (typeof skip === 'number') {
  31598. this.skipWarn_(skip, i);
  31599. skip = null;
  31600. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  31601. // end of the ADTS header
  31602. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  31603. // end of the sync sequence
  31604. // NOTE: frame length includes the size of the header
  31605. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  31606. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  31607. adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2]; // If we don't have enough data to actually finish this ADTS frame,
  31608. // then we have to wait for more data
  31609. if (buffer.byteLength - i < frameLength) {
  31610. break;
  31611. } // Otherwise, deliver the complete AAC frame
  31612. this.trigger('data', {
  31613. pts: packet.pts + frameNum * adtsFrameDuration,
  31614. dts: packet.dts + frameNum * adtsFrameDuration,
  31615. sampleCount: sampleCount,
  31616. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  31617. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  31618. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  31619. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  31620. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  31621. samplesize: 16,
  31622. // data is the frame without it's header
  31623. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  31624. });
  31625. frameNum++;
  31626. i += frameLength;
  31627. }
  31628. if (typeof skip === 'number') {
  31629. this.skipWarn_(skip, i);
  31630. skip = null;
  31631. } // remove processed bytes from the buffer.
  31632. buffer = buffer.subarray(i);
  31633. };
  31634. this.flush = function () {
  31635. frameNum = 0;
  31636. this.trigger('done');
  31637. };
  31638. this.reset = function () {
  31639. buffer = void 0;
  31640. this.trigger('reset');
  31641. };
  31642. this.endTimeline = function () {
  31643. buffer = void 0;
  31644. this.trigger('endedtimeline');
  31645. };
  31646. };
  31647. AdtsStream$1.prototype = new Stream$3();
  31648. var adts = AdtsStream$1;
  31649. /**
  31650. * mux.js
  31651. *
  31652. * Copyright (c) Brightcove
  31653. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31654. */
  31655. var ExpGolomb$1;
  31656. /**
  31657. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  31658. * scheme used by h264.
  31659. */
  31660. ExpGolomb$1 = function (workingData) {
  31661. var
  31662. // the number of bytes left to examine in workingData
  31663. workingBytesAvailable = workingData.byteLength,
  31664. // the current word being examined
  31665. workingWord = 0,
  31666. // :uint
  31667. // the number of bits left to examine in the current word
  31668. workingBitsAvailable = 0; // :uint;
  31669. // ():uint
  31670. this.length = function () {
  31671. return 8 * workingBytesAvailable;
  31672. }; // ():uint
  31673. this.bitsAvailable = function () {
  31674. return 8 * workingBytesAvailable + workingBitsAvailable;
  31675. }; // ():void
  31676. this.loadWord = function () {
  31677. var position = workingData.byteLength - workingBytesAvailable,
  31678. workingBytes = new Uint8Array(4),
  31679. availableBytes = Math.min(4, workingBytesAvailable);
  31680. if (availableBytes === 0) {
  31681. throw new Error('no bytes available');
  31682. }
  31683. workingBytes.set(workingData.subarray(position, position + availableBytes));
  31684. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  31685. workingBitsAvailable = availableBytes * 8;
  31686. workingBytesAvailable -= availableBytes;
  31687. }; // (count:int):void
  31688. this.skipBits = function (count) {
  31689. var skipBytes; // :int
  31690. if (workingBitsAvailable > count) {
  31691. workingWord <<= count;
  31692. workingBitsAvailable -= count;
  31693. } else {
  31694. count -= workingBitsAvailable;
  31695. skipBytes = Math.floor(count / 8);
  31696. count -= skipBytes * 8;
  31697. workingBytesAvailable -= skipBytes;
  31698. this.loadWord();
  31699. workingWord <<= count;
  31700. workingBitsAvailable -= count;
  31701. }
  31702. }; // (size:int):uint
  31703. this.readBits = function (size) {
  31704. var bits = Math.min(workingBitsAvailable, size),
  31705. // :uint
  31706. valu = workingWord >>> 32 - bits; // :uint
  31707. // if size > 31, handle error
  31708. workingBitsAvailable -= bits;
  31709. if (workingBitsAvailable > 0) {
  31710. workingWord <<= bits;
  31711. } else if (workingBytesAvailable > 0) {
  31712. this.loadWord();
  31713. }
  31714. bits = size - bits;
  31715. if (bits > 0) {
  31716. return valu << bits | this.readBits(bits);
  31717. }
  31718. return valu;
  31719. }; // ():uint
  31720. this.skipLeadingZeros = function () {
  31721. var leadingZeroCount; // :uint
  31722. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  31723. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  31724. // the first bit of working word is 1
  31725. workingWord <<= leadingZeroCount;
  31726. workingBitsAvailable -= leadingZeroCount;
  31727. return leadingZeroCount;
  31728. }
  31729. } // we exhausted workingWord and still have not found a 1
  31730. this.loadWord();
  31731. return leadingZeroCount + this.skipLeadingZeros();
  31732. }; // ():void
  31733. this.skipUnsignedExpGolomb = function () {
  31734. this.skipBits(1 + this.skipLeadingZeros());
  31735. }; // ():void
  31736. this.skipExpGolomb = function () {
  31737. this.skipBits(1 + this.skipLeadingZeros());
  31738. }; // ():uint
  31739. this.readUnsignedExpGolomb = function () {
  31740. var clz = this.skipLeadingZeros(); // :uint
  31741. return this.readBits(clz + 1) - 1;
  31742. }; // ():int
  31743. this.readExpGolomb = function () {
  31744. var valu = this.readUnsignedExpGolomb(); // :int
  31745. if (0x01 & valu) {
  31746. // the number is odd if the low order bit is set
  31747. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  31748. }
  31749. return -1 * (valu >>> 1); // divide by two then make it negative
  31750. }; // Some convenience functions
  31751. // :Boolean
  31752. this.readBoolean = function () {
  31753. return this.readBits(1) === 1;
  31754. }; // ():int
  31755. this.readUnsignedByte = function () {
  31756. return this.readBits(8);
  31757. };
  31758. this.loadWord();
  31759. };
  31760. var expGolomb = ExpGolomb$1;
  31761. /**
  31762. * mux.js
  31763. *
  31764. * Copyright (c) Brightcove
  31765. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31766. */
  31767. var Stream$2 = stream;
  31768. var ExpGolomb = expGolomb;
  31769. var H264Stream$1, NalByteStream;
  31770. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  31771. /**
  31772. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  31773. */
  31774. NalByteStream = function () {
  31775. var syncPoint = 0,
  31776. i,
  31777. buffer;
  31778. NalByteStream.prototype.init.call(this);
  31779. /*
  31780. * Scans a byte stream and triggers a data event with the NAL units found.
  31781. * @param {Object} data Event received from H264Stream
  31782. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  31783. *
  31784. * @see H264Stream.push
  31785. */
  31786. this.push = function (data) {
  31787. var swapBuffer;
  31788. if (!buffer) {
  31789. buffer = data.data;
  31790. } else {
  31791. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  31792. swapBuffer.set(buffer);
  31793. swapBuffer.set(data.data, buffer.byteLength);
  31794. buffer = swapBuffer;
  31795. }
  31796. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  31797. // scan for NAL unit boundaries
  31798. // a match looks like this:
  31799. // 0 0 1 .. NAL .. 0 0 1
  31800. // ^ sync point ^ i
  31801. // or this:
  31802. // 0 0 1 .. NAL .. 0 0 0
  31803. // ^ sync point ^ i
  31804. // advance the sync point to a NAL start, if necessary
  31805. for (; syncPoint < len - 3; syncPoint++) {
  31806. if (buffer[syncPoint + 2] === 1) {
  31807. // the sync point is properly aligned
  31808. i = syncPoint + 5;
  31809. break;
  31810. }
  31811. }
  31812. while (i < len) {
  31813. // look at the current byte to determine if we've hit the end of
  31814. // a NAL unit boundary
  31815. switch (buffer[i]) {
  31816. case 0:
  31817. // skip past non-sync sequences
  31818. if (buffer[i - 1] !== 0) {
  31819. i += 2;
  31820. break;
  31821. } else if (buffer[i - 2] !== 0) {
  31822. i++;
  31823. break;
  31824. } // deliver the NAL unit if it isn't empty
  31825. if (syncPoint + 3 !== i - 2) {
  31826. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31827. } // drop trailing zeroes
  31828. do {
  31829. i++;
  31830. } while (buffer[i] !== 1 && i < len);
  31831. syncPoint = i - 2;
  31832. i += 3;
  31833. break;
  31834. case 1:
  31835. // skip past non-sync sequences
  31836. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  31837. i += 3;
  31838. break;
  31839. } // deliver the NAL unit
  31840. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31841. syncPoint = i - 2;
  31842. i += 3;
  31843. break;
  31844. default:
  31845. // the current byte isn't a one or zero, so it cannot be part
  31846. // of a sync sequence
  31847. i += 3;
  31848. break;
  31849. }
  31850. } // filter out the NAL units that were delivered
  31851. buffer = buffer.subarray(syncPoint);
  31852. i -= syncPoint;
  31853. syncPoint = 0;
  31854. };
  31855. this.reset = function () {
  31856. buffer = null;
  31857. syncPoint = 0;
  31858. this.trigger('reset');
  31859. };
  31860. this.flush = function () {
  31861. // deliver the last buffered NAL unit
  31862. if (buffer && buffer.byteLength > 3) {
  31863. this.trigger('data', buffer.subarray(syncPoint + 3));
  31864. } // reset the stream state
  31865. buffer = null;
  31866. syncPoint = 0;
  31867. this.trigger('done');
  31868. };
  31869. this.endTimeline = function () {
  31870. this.flush();
  31871. this.trigger('endedtimeline');
  31872. };
  31873. };
  31874. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  31875. // see Recommendation ITU-T H.264 (4/2013),
  31876. // 7.3.2.1.1 Sequence parameter set data syntax
  31877. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  31878. 100: true,
  31879. 110: true,
  31880. 122: true,
  31881. 244: true,
  31882. 44: true,
  31883. 83: true,
  31884. 86: true,
  31885. 118: true,
  31886. 128: true,
  31887. // TODO: the three profiles below don't
  31888. // appear to have sps data in the specificiation anymore?
  31889. 138: true,
  31890. 139: true,
  31891. 134: true
  31892. };
  31893. /**
  31894. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  31895. * events.
  31896. */
  31897. H264Stream$1 = function () {
  31898. var nalByteStream = new NalByteStream(),
  31899. self,
  31900. trackId,
  31901. currentPts,
  31902. currentDts,
  31903. discardEmulationPreventionBytes,
  31904. readSequenceParameterSet,
  31905. skipScalingList;
  31906. H264Stream$1.prototype.init.call(this);
  31907. self = this;
  31908. /*
  31909. * Pushes a packet from a stream onto the NalByteStream
  31910. *
  31911. * @param {Object} packet - A packet received from a stream
  31912. * @param {Uint8Array} packet.data - The raw bytes of the packet
  31913. * @param {Number} packet.dts - Decode timestamp of the packet
  31914. * @param {Number} packet.pts - Presentation timestamp of the packet
  31915. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  31916. * @param {('video'|'audio')} packet.type - The type of packet
  31917. *
  31918. */
  31919. this.push = function (packet) {
  31920. if (packet.type !== 'video') {
  31921. return;
  31922. }
  31923. trackId = packet.trackId;
  31924. currentPts = packet.pts;
  31925. currentDts = packet.dts;
  31926. nalByteStream.push(packet);
  31927. };
  31928. /*
  31929. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  31930. * for the NALUs to the next stream component.
  31931. * Also, preprocess caption and sequence parameter NALUs.
  31932. *
  31933. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  31934. * @see NalByteStream.push
  31935. */
  31936. nalByteStream.on('data', function (data) {
  31937. var event = {
  31938. trackId: trackId,
  31939. pts: currentPts,
  31940. dts: currentDts,
  31941. data: data,
  31942. nalUnitTypeCode: data[0] & 0x1f
  31943. };
  31944. switch (event.nalUnitTypeCode) {
  31945. case 0x05:
  31946. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  31947. break;
  31948. case 0x06:
  31949. event.nalUnitType = 'sei_rbsp';
  31950. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31951. break;
  31952. case 0x07:
  31953. event.nalUnitType = 'seq_parameter_set_rbsp';
  31954. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31955. event.config = readSequenceParameterSet(event.escapedRBSP);
  31956. break;
  31957. case 0x08:
  31958. event.nalUnitType = 'pic_parameter_set_rbsp';
  31959. break;
  31960. case 0x09:
  31961. event.nalUnitType = 'access_unit_delimiter_rbsp';
  31962. break;
  31963. } // This triggers data on the H264Stream
  31964. self.trigger('data', event);
  31965. });
  31966. nalByteStream.on('done', function () {
  31967. self.trigger('done');
  31968. });
  31969. nalByteStream.on('partialdone', function () {
  31970. self.trigger('partialdone');
  31971. });
  31972. nalByteStream.on('reset', function () {
  31973. self.trigger('reset');
  31974. });
  31975. nalByteStream.on('endedtimeline', function () {
  31976. self.trigger('endedtimeline');
  31977. });
  31978. this.flush = function () {
  31979. nalByteStream.flush();
  31980. };
  31981. this.partialFlush = function () {
  31982. nalByteStream.partialFlush();
  31983. };
  31984. this.reset = function () {
  31985. nalByteStream.reset();
  31986. };
  31987. this.endTimeline = function () {
  31988. nalByteStream.endTimeline();
  31989. };
  31990. /**
  31991. * Advance the ExpGolomb decoder past a scaling list. The scaling
  31992. * list is optionally transmitted as part of a sequence parameter
  31993. * set and is not relevant to transmuxing.
  31994. * @param count {number} the number of entries in this scaling list
  31995. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  31996. * start of a scaling list
  31997. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  31998. */
  31999. skipScalingList = function (count, expGolombDecoder) {
  32000. var lastScale = 8,
  32001. nextScale = 8,
  32002. j,
  32003. deltaScale;
  32004. for (j = 0; j < count; j++) {
  32005. if (nextScale !== 0) {
  32006. deltaScale = expGolombDecoder.readExpGolomb();
  32007. nextScale = (lastScale + deltaScale + 256) % 256;
  32008. }
  32009. lastScale = nextScale === 0 ? lastScale : nextScale;
  32010. }
  32011. };
  32012. /**
  32013. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  32014. * Sequence Payload"
  32015. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  32016. * unit
  32017. * @return {Uint8Array} the RBSP without any Emulation
  32018. * Prevention Bytes
  32019. */
  32020. discardEmulationPreventionBytes = function (data) {
  32021. var length = data.byteLength,
  32022. emulationPreventionBytesPositions = [],
  32023. i = 1,
  32024. newLength,
  32025. newData; // Find all `Emulation Prevention Bytes`
  32026. while (i < length - 2) {
  32027. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  32028. emulationPreventionBytesPositions.push(i + 2);
  32029. i += 2;
  32030. } else {
  32031. i++;
  32032. }
  32033. } // If no Emulation Prevention Bytes were found just return the original
  32034. // array
  32035. if (emulationPreventionBytesPositions.length === 0) {
  32036. return data;
  32037. } // Create a new array to hold the NAL unit data
  32038. newLength = length - emulationPreventionBytesPositions.length;
  32039. newData = new Uint8Array(newLength);
  32040. var sourceIndex = 0;
  32041. for (i = 0; i < newLength; sourceIndex++, i++) {
  32042. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  32043. // Skip this byte
  32044. sourceIndex++; // Remove this position index
  32045. emulationPreventionBytesPositions.shift();
  32046. }
  32047. newData[i] = data[sourceIndex];
  32048. }
  32049. return newData;
  32050. };
  32051. /**
  32052. * Read a sequence parameter set and return some interesting video
  32053. * properties. A sequence parameter set is the H264 metadata that
  32054. * describes the properties of upcoming video frames.
  32055. * @param data {Uint8Array} the bytes of a sequence parameter set
  32056. * @return {object} an object with configuration parsed from the
  32057. * sequence parameter set, including the dimensions of the
  32058. * associated video frames.
  32059. */
  32060. readSequenceParameterSet = function (data) {
  32061. var frameCropLeftOffset = 0,
  32062. frameCropRightOffset = 0,
  32063. frameCropTopOffset = 0,
  32064. frameCropBottomOffset = 0,
  32065. expGolombDecoder,
  32066. profileIdc,
  32067. levelIdc,
  32068. profileCompatibility,
  32069. chromaFormatIdc,
  32070. picOrderCntType,
  32071. numRefFramesInPicOrderCntCycle,
  32072. picWidthInMbsMinus1,
  32073. picHeightInMapUnitsMinus1,
  32074. frameMbsOnlyFlag,
  32075. scalingListCount,
  32076. sarRatio = [1, 1],
  32077. aspectRatioIdc,
  32078. i;
  32079. expGolombDecoder = new ExpGolomb(data);
  32080. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  32081. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  32082. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  32083. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  32084. // some profiles have more optional data we don't need
  32085. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  32086. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  32087. if (chromaFormatIdc === 3) {
  32088. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  32089. }
  32090. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  32091. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  32092. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  32093. if (expGolombDecoder.readBoolean()) {
  32094. // seq_scaling_matrix_present_flag
  32095. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  32096. for (i = 0; i < scalingListCount; i++) {
  32097. if (expGolombDecoder.readBoolean()) {
  32098. // seq_scaling_list_present_flag[ i ]
  32099. if (i < 6) {
  32100. skipScalingList(16, expGolombDecoder);
  32101. } else {
  32102. skipScalingList(64, expGolombDecoder);
  32103. }
  32104. }
  32105. }
  32106. }
  32107. }
  32108. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  32109. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  32110. if (picOrderCntType === 0) {
  32111. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  32112. } else if (picOrderCntType === 1) {
  32113. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  32114. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  32115. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  32116. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  32117. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  32118. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  32119. }
  32120. }
  32121. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  32122. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  32123. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32124. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32125. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  32126. if (frameMbsOnlyFlag === 0) {
  32127. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  32128. }
  32129. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  32130. if (expGolombDecoder.readBoolean()) {
  32131. // frame_cropping_flag
  32132. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  32133. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  32134. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  32135. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  32136. }
  32137. if (expGolombDecoder.readBoolean()) {
  32138. // vui_parameters_present_flag
  32139. if (expGolombDecoder.readBoolean()) {
  32140. // aspect_ratio_info_present_flag
  32141. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  32142. switch (aspectRatioIdc) {
  32143. case 1:
  32144. sarRatio = [1, 1];
  32145. break;
  32146. case 2:
  32147. sarRatio = [12, 11];
  32148. break;
  32149. case 3:
  32150. sarRatio = [10, 11];
  32151. break;
  32152. case 4:
  32153. sarRatio = [16, 11];
  32154. break;
  32155. case 5:
  32156. sarRatio = [40, 33];
  32157. break;
  32158. case 6:
  32159. sarRatio = [24, 11];
  32160. break;
  32161. case 7:
  32162. sarRatio = [20, 11];
  32163. break;
  32164. case 8:
  32165. sarRatio = [32, 11];
  32166. break;
  32167. case 9:
  32168. sarRatio = [80, 33];
  32169. break;
  32170. case 10:
  32171. sarRatio = [18, 11];
  32172. break;
  32173. case 11:
  32174. sarRatio = [15, 11];
  32175. break;
  32176. case 12:
  32177. sarRatio = [64, 33];
  32178. break;
  32179. case 13:
  32180. sarRatio = [160, 99];
  32181. break;
  32182. case 14:
  32183. sarRatio = [4, 3];
  32184. break;
  32185. case 15:
  32186. sarRatio = [3, 2];
  32187. break;
  32188. case 16:
  32189. sarRatio = [2, 1];
  32190. break;
  32191. case 255:
  32192. {
  32193. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  32194. break;
  32195. }
  32196. }
  32197. if (sarRatio) {
  32198. sarRatio[0] / sarRatio[1];
  32199. }
  32200. }
  32201. }
  32202. return {
  32203. profileIdc: profileIdc,
  32204. levelIdc: levelIdc,
  32205. profileCompatibility: profileCompatibility,
  32206. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  32207. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  32208. // sar is sample aspect ratio
  32209. sarRatio: sarRatio
  32210. };
  32211. };
  32212. };
  32213. H264Stream$1.prototype = new Stream$2();
  32214. var h264 = {
  32215. H264Stream: H264Stream$1,
  32216. NalByteStream: NalByteStream
  32217. };
  32218. /**
  32219. * mux.js
  32220. *
  32221. * Copyright (c) Brightcove
  32222. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32223. *
  32224. * Utilities to detect basic properties and metadata about Aac data.
  32225. */
  32226. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  32227. var parseId3TagSize = function (header, byteIndex) {
  32228. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  32229. flags = header[byteIndex + 5],
  32230. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  32231. returnSize = returnSize >= 0 ? returnSize : 0;
  32232. if (footerPresent) {
  32233. return returnSize + 20;
  32234. }
  32235. return returnSize + 10;
  32236. };
  32237. var getId3Offset = function (data, offset) {
  32238. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  32239. return offset;
  32240. }
  32241. offset += parseId3TagSize(data, offset);
  32242. return getId3Offset(data, offset);
  32243. }; // TODO: use vhs-utils
  32244. var isLikelyAacData$1 = function (data) {
  32245. var offset = getId3Offset(data, 0);
  32246. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 &&
  32247. // verify that the 2 layer bits are 0, aka this
  32248. // is not mp3 data but aac data.
  32249. (data[offset + 1] & 0x16) === 0x10;
  32250. };
  32251. var parseSyncSafeInteger = function (data) {
  32252. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  32253. }; // return a percent-encoded representation of the specified byte range
  32254. // @see http://en.wikipedia.org/wiki/Percent-encoding
  32255. var percentEncode = function (bytes, start, end) {
  32256. var i,
  32257. result = '';
  32258. for (i = start; i < end; i++) {
  32259. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  32260. }
  32261. return result;
  32262. }; // return the string representation of the specified byte range,
  32263. // interpreted as ISO-8859-1.
  32264. var parseIso88591 = function (bytes, start, end) {
  32265. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  32266. };
  32267. var parseAdtsSize = function (header, byteIndex) {
  32268. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  32269. middle = header[byteIndex + 4] << 3,
  32270. highTwo = header[byteIndex + 3] & 0x3 << 11;
  32271. return highTwo | middle | lowThree;
  32272. };
  32273. var parseType$4 = function (header, byteIndex) {
  32274. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  32275. return 'timed-metadata';
  32276. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  32277. return 'audio';
  32278. }
  32279. return null;
  32280. };
  32281. var parseSampleRate = function (packet) {
  32282. var i = 0;
  32283. while (i + 5 < packet.length) {
  32284. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  32285. // If a valid header was not found, jump one forward and attempt to
  32286. // find a valid ADTS header starting at the next byte
  32287. i++;
  32288. continue;
  32289. }
  32290. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  32291. }
  32292. return null;
  32293. };
  32294. var parseAacTimestamp = function (packet) {
  32295. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  32296. frameStart = 10;
  32297. if (packet[5] & 0x40) {
  32298. // advance the frame start past the extended header
  32299. frameStart += 4; // header size field
  32300. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  32301. } // parse one or more ID3 frames
  32302. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  32303. do {
  32304. // determine the number of bytes in this frame
  32305. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  32306. if (frameSize < 1) {
  32307. return null;
  32308. }
  32309. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  32310. if (frameHeader === 'PRIV') {
  32311. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  32312. for (var i = 0; i < frame.byteLength; i++) {
  32313. if (frame[i] === 0) {
  32314. var owner = parseIso88591(frame, 0, i);
  32315. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  32316. var d = frame.subarray(i + 1);
  32317. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  32318. size *= 4;
  32319. size += d[7] & 0x03;
  32320. return size;
  32321. }
  32322. break;
  32323. }
  32324. }
  32325. }
  32326. frameStart += 10; // advance past the frame header
  32327. frameStart += frameSize; // advance past the frame body
  32328. } while (frameStart < packet.byteLength);
  32329. return null;
  32330. };
  32331. var utils = {
  32332. isLikelyAacData: isLikelyAacData$1,
  32333. parseId3TagSize: parseId3TagSize,
  32334. parseAdtsSize: parseAdtsSize,
  32335. parseType: parseType$4,
  32336. parseSampleRate: parseSampleRate,
  32337. parseAacTimestamp: parseAacTimestamp
  32338. };
  32339. /**
  32340. * mux.js
  32341. *
  32342. * Copyright (c) Brightcove
  32343. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32344. *
  32345. * A stream-based aac to mp4 converter. This utility can be used to
  32346. * deliver mp4s to a SourceBuffer on platforms that support native
  32347. * Media Source Extensions.
  32348. */
  32349. var Stream$1 = stream;
  32350. var aacUtils = utils; // Constants
  32351. var AacStream$1;
  32352. /**
  32353. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  32354. */
  32355. AacStream$1 = function () {
  32356. var everything = new Uint8Array(),
  32357. timeStamp = 0;
  32358. AacStream$1.prototype.init.call(this);
  32359. this.setTimestamp = function (timestamp) {
  32360. timeStamp = timestamp;
  32361. };
  32362. this.push = function (bytes) {
  32363. var frameSize = 0,
  32364. byteIndex = 0,
  32365. bytesLeft,
  32366. chunk,
  32367. packet,
  32368. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  32369. // bytes that were pushed in
  32370. if (everything.length) {
  32371. tempLength = everything.length;
  32372. everything = new Uint8Array(bytes.byteLength + tempLength);
  32373. everything.set(everything.subarray(0, tempLength));
  32374. everything.set(bytes, tempLength);
  32375. } else {
  32376. everything = bytes;
  32377. }
  32378. while (everything.length - byteIndex >= 3) {
  32379. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  32380. // Exit early because we don't have enough to parse
  32381. // the ID3 tag header
  32382. if (everything.length - byteIndex < 10) {
  32383. break;
  32384. } // check framesize
  32385. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32386. // to emit a full packet
  32387. // Add to byteIndex to support multiple ID3 tags in sequence
  32388. if (byteIndex + frameSize > everything.length) {
  32389. break;
  32390. }
  32391. chunk = {
  32392. type: 'timed-metadata',
  32393. data: everything.subarray(byteIndex, byteIndex + frameSize)
  32394. };
  32395. this.trigger('data', chunk);
  32396. byteIndex += frameSize;
  32397. continue;
  32398. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  32399. // Exit early because we don't have enough to parse
  32400. // the ADTS frame header
  32401. if (everything.length - byteIndex < 7) {
  32402. break;
  32403. }
  32404. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32405. // to emit a full packet
  32406. if (byteIndex + frameSize > everything.length) {
  32407. break;
  32408. }
  32409. packet = {
  32410. type: 'audio',
  32411. data: everything.subarray(byteIndex, byteIndex + frameSize),
  32412. pts: timeStamp,
  32413. dts: timeStamp
  32414. };
  32415. this.trigger('data', packet);
  32416. byteIndex += frameSize;
  32417. continue;
  32418. }
  32419. byteIndex++;
  32420. }
  32421. bytesLeft = everything.length - byteIndex;
  32422. if (bytesLeft > 0) {
  32423. everything = everything.subarray(byteIndex);
  32424. } else {
  32425. everything = new Uint8Array();
  32426. }
  32427. };
  32428. this.reset = function () {
  32429. everything = new Uint8Array();
  32430. this.trigger('reset');
  32431. };
  32432. this.endTimeline = function () {
  32433. everything = new Uint8Array();
  32434. this.trigger('endedtimeline');
  32435. };
  32436. };
  32437. AacStream$1.prototype = new Stream$1();
  32438. var aac = AacStream$1;
  32439. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  32440. var audioProperties = AUDIO_PROPERTIES$1;
  32441. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  32442. var videoProperties = VIDEO_PROPERTIES$1;
  32443. /**
  32444. * mux.js
  32445. *
  32446. * Copyright (c) Brightcove
  32447. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32448. *
  32449. * A stream-based mp2t to mp4 converter. This utility can be used to
  32450. * deliver mp4s to a SourceBuffer on platforms that support native
  32451. * Media Source Extensions.
  32452. */
  32453. var Stream = stream;
  32454. var mp4 = mp4Generator;
  32455. var frameUtils = frameUtils$1;
  32456. var audioFrameUtils = audioFrameUtils$1;
  32457. var trackDecodeInfo = trackDecodeInfo$1;
  32458. var m2ts = m2ts_1;
  32459. var clock = clock$2;
  32460. var AdtsStream = adts;
  32461. var H264Stream = h264.H264Stream;
  32462. var AacStream = aac;
  32463. var isLikelyAacData = utils.isLikelyAacData;
  32464. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  32465. var AUDIO_PROPERTIES = audioProperties;
  32466. var VIDEO_PROPERTIES = videoProperties; // object types
  32467. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  32468. var retriggerForStream = function (key, event) {
  32469. event.stream = key;
  32470. this.trigger('log', event);
  32471. };
  32472. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  32473. var keys = Object.keys(pipeline);
  32474. for (var i = 0; i < keys.length; i++) {
  32475. var key = keys[i]; // skip non-stream keys and headOfPipeline
  32476. // which is just a duplicate
  32477. if (key === 'headOfPipeline' || !pipeline[key].on) {
  32478. continue;
  32479. }
  32480. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  32481. }
  32482. };
  32483. /**
  32484. * Compare two arrays (even typed) for same-ness
  32485. */
  32486. var arrayEquals = function (a, b) {
  32487. var i;
  32488. if (a.length !== b.length) {
  32489. return false;
  32490. } // compare the value of each element in the array
  32491. for (i = 0; i < a.length; i++) {
  32492. if (a[i] !== b[i]) {
  32493. return false;
  32494. }
  32495. }
  32496. return true;
  32497. };
  32498. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  32499. var ptsOffsetFromDts = startPts - startDts,
  32500. decodeDuration = endDts - startDts,
  32501. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  32502. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  32503. // In order to provide relevant values for the player times, base timing info on the
  32504. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  32505. return {
  32506. start: {
  32507. dts: baseMediaDecodeTime,
  32508. pts: baseMediaDecodeTime + ptsOffsetFromDts
  32509. },
  32510. end: {
  32511. dts: baseMediaDecodeTime + decodeDuration,
  32512. pts: baseMediaDecodeTime + presentationDuration
  32513. },
  32514. prependedContentDuration: prependedContentDuration,
  32515. baseMediaDecodeTime: baseMediaDecodeTime
  32516. };
  32517. };
  32518. /**
  32519. * Constructs a single-track, ISO BMFF media segment from AAC data
  32520. * events. The output of this stream can be fed to a SourceBuffer
  32521. * configured with a suitable initialization segment.
  32522. * @param track {object} track metadata configuration
  32523. * @param options {object} transmuxer options object
  32524. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32525. * in the source; false to adjust the first segment to start at 0.
  32526. */
  32527. AudioSegmentStream = function (track, options) {
  32528. var adtsFrames = [],
  32529. sequenceNumber,
  32530. earliestAllowedDts = 0,
  32531. audioAppendStartTs = 0,
  32532. videoBaseMediaDecodeTime = Infinity;
  32533. options = options || {};
  32534. sequenceNumber = options.firstSequenceNumber || 0;
  32535. AudioSegmentStream.prototype.init.call(this);
  32536. this.push = function (data) {
  32537. trackDecodeInfo.collectDtsInfo(track, data);
  32538. if (track) {
  32539. AUDIO_PROPERTIES.forEach(function (prop) {
  32540. track[prop] = data[prop];
  32541. });
  32542. } // buffer audio data until end() is called
  32543. adtsFrames.push(data);
  32544. };
  32545. this.setEarliestDts = function (earliestDts) {
  32546. earliestAllowedDts = earliestDts;
  32547. };
  32548. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  32549. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  32550. };
  32551. this.setAudioAppendStart = function (timestamp) {
  32552. audioAppendStartTs = timestamp;
  32553. };
  32554. this.flush = function () {
  32555. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  32556. if (adtsFrames.length === 0) {
  32557. this.trigger('done', 'AudioSegmentStream');
  32558. return;
  32559. }
  32560. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  32561. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  32562. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  32563. // samples (that is, adts frames) in the audio data
  32564. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  32565. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  32566. adtsFrames = [];
  32567. moof = mp4.moof(sequenceNumber, [track]);
  32568. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  32569. sequenceNumber++;
  32570. boxes.set(moof);
  32571. boxes.set(mdat, moof.byteLength);
  32572. trackDecodeInfo.clearDtsInfo(track);
  32573. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  32574. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  32575. // valid use-case where an init segment/data should be triggered without associated
  32576. // frames. Leaving for now, but should be looked into.
  32577. if (frames.length) {
  32578. segmentDuration = frames.length * frameDuration;
  32579. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(
  32580. // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  32581. // frame info is in video clock cycles. Convert to match expectation of
  32582. // listeners (that all timestamps will be based on video clock cycles).
  32583. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
  32584. // frame times are already in video clock, as is segment duration
  32585. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  32586. this.trigger('timingInfo', {
  32587. start: frames[0].pts,
  32588. end: frames[0].pts + segmentDuration
  32589. });
  32590. }
  32591. this.trigger('data', {
  32592. track: track,
  32593. boxes: boxes
  32594. });
  32595. this.trigger('done', 'AudioSegmentStream');
  32596. };
  32597. this.reset = function () {
  32598. trackDecodeInfo.clearDtsInfo(track);
  32599. adtsFrames = [];
  32600. this.trigger('reset');
  32601. };
  32602. };
  32603. AudioSegmentStream.prototype = new Stream();
  32604. /**
  32605. * Constructs a single-track, ISO BMFF media segment from H264 data
  32606. * events. The output of this stream can be fed to a SourceBuffer
  32607. * configured with a suitable initialization segment.
  32608. * @param track {object} track metadata configuration
  32609. * @param options {object} transmuxer options object
  32610. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  32611. * gopsToAlignWith list when attempting to align gop pts
  32612. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32613. * in the source; false to adjust the first segment to start at 0.
  32614. */
  32615. VideoSegmentStream = function (track, options) {
  32616. var sequenceNumber,
  32617. nalUnits = [],
  32618. gopsToAlignWith = [],
  32619. config,
  32620. pps;
  32621. options = options || {};
  32622. sequenceNumber = options.firstSequenceNumber || 0;
  32623. VideoSegmentStream.prototype.init.call(this);
  32624. delete track.minPTS;
  32625. this.gopCache_ = [];
  32626. /**
  32627. * Constructs a ISO BMFF segment given H264 nalUnits
  32628. * @param {Object} nalUnit A data event representing a nalUnit
  32629. * @param {String} nalUnit.nalUnitType
  32630. * @param {Object} nalUnit.config Properties for a mp4 track
  32631. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  32632. * @see lib/codecs/h264.js
  32633. **/
  32634. this.push = function (nalUnit) {
  32635. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  32636. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  32637. config = nalUnit.config;
  32638. track.sps = [nalUnit.data];
  32639. VIDEO_PROPERTIES.forEach(function (prop) {
  32640. track[prop] = config[prop];
  32641. }, this);
  32642. }
  32643. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  32644. pps = nalUnit.data;
  32645. track.pps = [nalUnit.data];
  32646. } // buffer video until flush() is called
  32647. nalUnits.push(nalUnit);
  32648. };
  32649. /**
  32650. * Pass constructed ISO BMFF track and boxes on to the
  32651. * next stream in the pipeline
  32652. **/
  32653. this.flush = function () {
  32654. var frames,
  32655. gopForFusion,
  32656. gops,
  32657. moof,
  32658. mdat,
  32659. boxes,
  32660. prependedContentDuration = 0,
  32661. firstGop,
  32662. lastGop; // Throw away nalUnits at the start of the byte stream until
  32663. // we find the first AUD
  32664. while (nalUnits.length) {
  32665. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  32666. break;
  32667. }
  32668. nalUnits.shift();
  32669. } // Return early if no video data has been observed
  32670. if (nalUnits.length === 0) {
  32671. this.resetStream_();
  32672. this.trigger('done', 'VideoSegmentStream');
  32673. return;
  32674. } // Organize the raw nal-units into arrays that represent
  32675. // higher-level constructs such as frames and gops
  32676. // (group-of-pictures)
  32677. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  32678. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  32679. // a problem since MSE (on Chrome) requires a leading keyframe.
  32680. //
  32681. // We have two approaches to repairing this situation:
  32682. // 1) GOP-FUSION:
  32683. // This is where we keep track of the GOPS (group-of-pictures)
  32684. // from previous fragments and attempt to find one that we can
  32685. // prepend to the current fragment in order to create a valid
  32686. // fragment.
  32687. // 2) KEYFRAME-PULLING:
  32688. // Here we search for the first keyframe in the fragment and
  32689. // throw away all the frames between the start of the fragment
  32690. // and that keyframe. We then extend the duration and pull the
  32691. // PTS of the keyframe forward so that it covers the time range
  32692. // of the frames that were disposed of.
  32693. //
  32694. // #1 is far prefereable over #2 which can cause "stuttering" but
  32695. // requires more things to be just right.
  32696. if (!gops[0][0].keyFrame) {
  32697. // Search for a gop for fusion from our gopCache
  32698. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  32699. if (gopForFusion) {
  32700. // in order to provide more accurate timing information about the segment, save
  32701. // the number of seconds prepended to the original segment due to GOP fusion
  32702. prependedContentDuration = gopForFusion.duration;
  32703. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  32704. // new gop at the beginning
  32705. gops.byteLength += gopForFusion.byteLength;
  32706. gops.nalCount += gopForFusion.nalCount;
  32707. gops.pts = gopForFusion.pts;
  32708. gops.dts = gopForFusion.dts;
  32709. gops.duration += gopForFusion.duration;
  32710. } else {
  32711. // If we didn't find a candidate gop fall back to keyframe-pulling
  32712. gops = frameUtils.extendFirstKeyFrame(gops);
  32713. }
  32714. } // Trim gops to align with gopsToAlignWith
  32715. if (gopsToAlignWith.length) {
  32716. var alignedGops;
  32717. if (options.alignGopsAtEnd) {
  32718. alignedGops = this.alignGopsAtEnd_(gops);
  32719. } else {
  32720. alignedGops = this.alignGopsAtStart_(gops);
  32721. }
  32722. if (!alignedGops) {
  32723. // save all the nals in the last GOP into the gop cache
  32724. this.gopCache_.unshift({
  32725. gop: gops.pop(),
  32726. pps: track.pps,
  32727. sps: track.sps
  32728. }); // Keep a maximum of 6 GOPs in the cache
  32729. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32730. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  32731. this.resetStream_();
  32732. this.trigger('done', 'VideoSegmentStream');
  32733. return;
  32734. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  32735. // when recalculated before sending off to CoalesceStream
  32736. trackDecodeInfo.clearDtsInfo(track);
  32737. gops = alignedGops;
  32738. }
  32739. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  32740. // samples (that is, frames) in the video data
  32741. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  32742. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  32743. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  32744. this.trigger('processedGopsInfo', gops.map(function (gop) {
  32745. return {
  32746. pts: gop.pts,
  32747. dts: gop.dts,
  32748. byteLength: gop.byteLength
  32749. };
  32750. }));
  32751. firstGop = gops[0];
  32752. lastGop = gops[gops.length - 1];
  32753. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  32754. this.trigger('timingInfo', {
  32755. start: gops[0].pts,
  32756. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  32757. }); // save all the nals in the last GOP into the gop cache
  32758. this.gopCache_.unshift({
  32759. gop: gops.pop(),
  32760. pps: track.pps,
  32761. sps: track.sps
  32762. }); // Keep a maximum of 6 GOPs in the cache
  32763. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32764. nalUnits = [];
  32765. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  32766. this.trigger('timelineStartInfo', track.timelineStartInfo);
  32767. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  32768. // throwing away hundreds of media segment fragments
  32769. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  32770. sequenceNumber++;
  32771. boxes.set(moof);
  32772. boxes.set(mdat, moof.byteLength);
  32773. this.trigger('data', {
  32774. track: track,
  32775. boxes: boxes
  32776. });
  32777. this.resetStream_(); // Continue with the flush process now
  32778. this.trigger('done', 'VideoSegmentStream');
  32779. };
  32780. this.reset = function () {
  32781. this.resetStream_();
  32782. nalUnits = [];
  32783. this.gopCache_.length = 0;
  32784. gopsToAlignWith.length = 0;
  32785. this.trigger('reset');
  32786. };
  32787. this.resetStream_ = function () {
  32788. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  32789. // for instance, when we are rendition switching
  32790. config = undefined;
  32791. pps = undefined;
  32792. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  32793. // return it or return null if no good candidate was found
  32794. this.getGopForFusion_ = function (nalUnit) {
  32795. var halfSecond = 45000,
  32796. // Half-a-second in a 90khz clock
  32797. allowableOverlap = 10000,
  32798. // About 3 frames @ 30fps
  32799. nearestDistance = Infinity,
  32800. dtsDistance,
  32801. nearestGopObj,
  32802. currentGop,
  32803. currentGopObj,
  32804. i; // Search for the GOP nearest to the beginning of this nal unit
  32805. for (i = 0; i < this.gopCache_.length; i++) {
  32806. currentGopObj = this.gopCache_[i];
  32807. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  32808. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  32809. continue;
  32810. } // Reject Gops that would require a negative baseMediaDecodeTime
  32811. if (currentGop.dts < track.timelineStartInfo.dts) {
  32812. continue;
  32813. } // The distance between the end of the gop and the start of the nalUnit
  32814. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  32815. // a half-second of the nal unit
  32816. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  32817. // Always use the closest GOP we found if there is more than
  32818. // one candidate
  32819. if (!nearestGopObj || nearestDistance > dtsDistance) {
  32820. nearestGopObj = currentGopObj;
  32821. nearestDistance = dtsDistance;
  32822. }
  32823. }
  32824. }
  32825. if (nearestGopObj) {
  32826. return nearestGopObj.gop;
  32827. }
  32828. return null;
  32829. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32830. // of gopsToAlignWith starting from the START of the list
  32831. this.alignGopsAtStart_ = function (gops) {
  32832. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  32833. byteLength = gops.byteLength;
  32834. nalCount = gops.nalCount;
  32835. duration = gops.duration;
  32836. alignIndex = gopIndex = 0;
  32837. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  32838. align = gopsToAlignWith[alignIndex];
  32839. gop = gops[gopIndex];
  32840. if (align.pts === gop.pts) {
  32841. break;
  32842. }
  32843. if (gop.pts > align.pts) {
  32844. // this current gop starts after the current gop we want to align on, so increment
  32845. // align index
  32846. alignIndex++;
  32847. continue;
  32848. } // current gop starts before the current gop we want to align on. so increment gop
  32849. // index
  32850. gopIndex++;
  32851. byteLength -= gop.byteLength;
  32852. nalCount -= gop.nalCount;
  32853. duration -= gop.duration;
  32854. }
  32855. if (gopIndex === 0) {
  32856. // no gops to trim
  32857. return gops;
  32858. }
  32859. if (gopIndex === gops.length) {
  32860. // all gops trimmed, skip appending all gops
  32861. return null;
  32862. }
  32863. alignedGops = gops.slice(gopIndex);
  32864. alignedGops.byteLength = byteLength;
  32865. alignedGops.duration = duration;
  32866. alignedGops.nalCount = nalCount;
  32867. alignedGops.pts = alignedGops[0].pts;
  32868. alignedGops.dts = alignedGops[0].dts;
  32869. return alignedGops;
  32870. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32871. // of gopsToAlignWith starting from the END of the list
  32872. this.alignGopsAtEnd_ = function (gops) {
  32873. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  32874. alignIndex = gopsToAlignWith.length - 1;
  32875. gopIndex = gops.length - 1;
  32876. alignEndIndex = null;
  32877. matchFound = false;
  32878. while (alignIndex >= 0 && gopIndex >= 0) {
  32879. align = gopsToAlignWith[alignIndex];
  32880. gop = gops[gopIndex];
  32881. if (align.pts === gop.pts) {
  32882. matchFound = true;
  32883. break;
  32884. }
  32885. if (align.pts > gop.pts) {
  32886. alignIndex--;
  32887. continue;
  32888. }
  32889. if (alignIndex === gopsToAlignWith.length - 1) {
  32890. // gop.pts is greater than the last alignment candidate. If no match is found
  32891. // by the end of this loop, we still want to append gops that come after this
  32892. // point
  32893. alignEndIndex = gopIndex;
  32894. }
  32895. gopIndex--;
  32896. }
  32897. if (!matchFound && alignEndIndex === null) {
  32898. return null;
  32899. }
  32900. var trimIndex;
  32901. if (matchFound) {
  32902. trimIndex = gopIndex;
  32903. } else {
  32904. trimIndex = alignEndIndex;
  32905. }
  32906. if (trimIndex === 0) {
  32907. return gops;
  32908. }
  32909. var alignedGops = gops.slice(trimIndex);
  32910. var metadata = alignedGops.reduce(function (total, gop) {
  32911. total.byteLength += gop.byteLength;
  32912. total.duration += gop.duration;
  32913. total.nalCount += gop.nalCount;
  32914. return total;
  32915. }, {
  32916. byteLength: 0,
  32917. duration: 0,
  32918. nalCount: 0
  32919. });
  32920. alignedGops.byteLength = metadata.byteLength;
  32921. alignedGops.duration = metadata.duration;
  32922. alignedGops.nalCount = metadata.nalCount;
  32923. alignedGops.pts = alignedGops[0].pts;
  32924. alignedGops.dts = alignedGops[0].dts;
  32925. return alignedGops;
  32926. };
  32927. this.alignGopsWith = function (newGopsToAlignWith) {
  32928. gopsToAlignWith = newGopsToAlignWith;
  32929. };
  32930. };
  32931. VideoSegmentStream.prototype = new Stream();
  32932. /**
  32933. * A Stream that can combine multiple streams (ie. audio & video)
  32934. * into a single output segment for MSE. Also supports audio-only
  32935. * and video-only streams.
  32936. * @param options {object} transmuxer options object
  32937. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32938. * in the source; false to adjust the first segment to start at media timeline start.
  32939. */
  32940. CoalesceStream = function (options, metadataStream) {
  32941. // Number of Tracks per output segment
  32942. // If greater than 1, we combine multiple
  32943. // tracks into a single segment
  32944. this.numberOfTracks = 0;
  32945. this.metadataStream = metadataStream;
  32946. options = options || {};
  32947. if (typeof options.remux !== 'undefined') {
  32948. this.remuxTracks = !!options.remux;
  32949. } else {
  32950. this.remuxTracks = true;
  32951. }
  32952. if (typeof options.keepOriginalTimestamps === 'boolean') {
  32953. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  32954. } else {
  32955. this.keepOriginalTimestamps = false;
  32956. }
  32957. this.pendingTracks = [];
  32958. this.videoTrack = null;
  32959. this.pendingBoxes = [];
  32960. this.pendingCaptions = [];
  32961. this.pendingMetadata = [];
  32962. this.pendingBytes = 0;
  32963. this.emittedTracks = 0;
  32964. CoalesceStream.prototype.init.call(this); // Take output from multiple
  32965. this.push = function (output) {
  32966. // buffer incoming captions until the associated video segment
  32967. // finishes
  32968. if (output.text) {
  32969. return this.pendingCaptions.push(output);
  32970. } // buffer incoming id3 tags until the final flush
  32971. if (output.frames) {
  32972. return this.pendingMetadata.push(output);
  32973. } // Add this track to the list of pending tracks and store
  32974. // important information required for the construction of
  32975. // the final segment
  32976. this.pendingTracks.push(output.track);
  32977. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  32978. // We unshift audio and push video because
  32979. // as of Chrome 75 when switching from
  32980. // one init segment to another if the video
  32981. // mdat does not appear after the audio mdat
  32982. // only audio will play for the duration of our transmux.
  32983. if (output.track.type === 'video') {
  32984. this.videoTrack = output.track;
  32985. this.pendingBoxes.push(output.boxes);
  32986. }
  32987. if (output.track.type === 'audio') {
  32988. this.audioTrack = output.track;
  32989. this.pendingBoxes.unshift(output.boxes);
  32990. }
  32991. };
  32992. };
  32993. CoalesceStream.prototype = new Stream();
  32994. CoalesceStream.prototype.flush = function (flushSource) {
  32995. var offset = 0,
  32996. event = {
  32997. captions: [],
  32998. captionStreams: {},
  32999. metadata: [],
  33000. info: {}
  33001. },
  33002. caption,
  33003. id3,
  33004. initSegment,
  33005. timelineStartPts = 0,
  33006. i;
  33007. if (this.pendingTracks.length < this.numberOfTracks) {
  33008. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  33009. // Return because we haven't received a flush from a data-generating
  33010. // portion of the segment (meaning that we have only recieved meta-data
  33011. // or captions.)
  33012. return;
  33013. } else if (this.remuxTracks) {
  33014. // Return until we have enough tracks from the pipeline to remux (if we
  33015. // are remuxing audio and video into a single MP4)
  33016. return;
  33017. } else if (this.pendingTracks.length === 0) {
  33018. // In the case where we receive a flush without any data having been
  33019. // received we consider it an emitted track for the purposes of coalescing
  33020. // `done` events.
  33021. // We do this for the case where there is an audio and video track in the
  33022. // segment but no audio data. (seen in several playlists with alternate
  33023. // audio tracks and no audio present in the main TS segments.)
  33024. this.emittedTracks++;
  33025. if (this.emittedTracks >= this.numberOfTracks) {
  33026. this.trigger('done');
  33027. this.emittedTracks = 0;
  33028. }
  33029. return;
  33030. }
  33031. }
  33032. if (this.videoTrack) {
  33033. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  33034. VIDEO_PROPERTIES.forEach(function (prop) {
  33035. event.info[prop] = this.videoTrack[prop];
  33036. }, this);
  33037. } else if (this.audioTrack) {
  33038. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  33039. AUDIO_PROPERTIES.forEach(function (prop) {
  33040. event.info[prop] = this.audioTrack[prop];
  33041. }, this);
  33042. }
  33043. if (this.videoTrack || this.audioTrack) {
  33044. if (this.pendingTracks.length === 1) {
  33045. event.type = this.pendingTracks[0].type;
  33046. } else {
  33047. event.type = 'combined';
  33048. }
  33049. this.emittedTracks += this.pendingTracks.length;
  33050. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  33051. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  33052. // and track definitions
  33053. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  33054. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  33055. for (i = 0; i < this.pendingBoxes.length; i++) {
  33056. event.data.set(this.pendingBoxes[i], offset);
  33057. offset += this.pendingBoxes[i].byteLength;
  33058. } // Translate caption PTS times into second offsets to match the
  33059. // video timeline for the segment, and add track info
  33060. for (i = 0; i < this.pendingCaptions.length; i++) {
  33061. caption = this.pendingCaptions[i];
  33062. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  33063. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  33064. event.captionStreams[caption.stream] = true;
  33065. event.captions.push(caption);
  33066. } // Translate ID3 frame PTS times into second offsets to match the
  33067. // video timeline for the segment
  33068. for (i = 0; i < this.pendingMetadata.length; i++) {
  33069. id3 = this.pendingMetadata[i];
  33070. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  33071. event.metadata.push(id3);
  33072. } // We add this to every single emitted segment even though we only need
  33073. // it for the first
  33074. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  33075. this.pendingTracks.length = 0;
  33076. this.videoTrack = null;
  33077. this.pendingBoxes.length = 0;
  33078. this.pendingCaptions.length = 0;
  33079. this.pendingBytes = 0;
  33080. this.pendingMetadata.length = 0; // Emit the built segment
  33081. // We include captions and ID3 tags for backwards compatibility,
  33082. // ideally we should send only video and audio in the data event
  33083. this.trigger('data', event); // Emit each caption to the outside world
  33084. // Ideally, this would happen immediately on parsing captions,
  33085. // but we need to ensure that video data is sent back first
  33086. // so that caption timing can be adjusted to match video timing
  33087. for (i = 0; i < event.captions.length; i++) {
  33088. caption = event.captions[i];
  33089. this.trigger('caption', caption);
  33090. } // Emit each id3 tag to the outside world
  33091. // Ideally, this would happen immediately on parsing the tag,
  33092. // but we need to ensure that video data is sent back first
  33093. // so that ID3 frame timing can be adjusted to match video timing
  33094. for (i = 0; i < event.metadata.length; i++) {
  33095. id3 = event.metadata[i];
  33096. this.trigger('id3Frame', id3);
  33097. }
  33098. } // Only emit `done` if all tracks have been flushed and emitted
  33099. if (this.emittedTracks >= this.numberOfTracks) {
  33100. this.trigger('done');
  33101. this.emittedTracks = 0;
  33102. }
  33103. };
  33104. CoalesceStream.prototype.setRemux = function (val) {
  33105. this.remuxTracks = val;
  33106. };
  33107. /**
  33108. * A Stream that expects MP2T binary data as input and produces
  33109. * corresponding media segments, suitable for use with Media Source
  33110. * Extension (MSE) implementations that support the ISO BMFF byte
  33111. * stream format, like Chrome.
  33112. */
  33113. Transmuxer = function (options) {
  33114. var self = this,
  33115. hasFlushed = true,
  33116. videoTrack,
  33117. audioTrack;
  33118. Transmuxer.prototype.init.call(this);
  33119. options = options || {};
  33120. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  33121. this.transmuxPipeline_ = {};
  33122. this.setupAacPipeline = function () {
  33123. var pipeline = {};
  33124. this.transmuxPipeline_ = pipeline;
  33125. pipeline.type = 'aac';
  33126. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  33127. pipeline.aacStream = new AacStream();
  33128. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  33129. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  33130. pipeline.adtsStream = new AdtsStream();
  33131. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  33132. pipeline.headOfPipeline = pipeline.aacStream;
  33133. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  33134. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  33135. pipeline.metadataStream.on('timestamp', function (frame) {
  33136. pipeline.aacStream.setTimestamp(frame.timeStamp);
  33137. });
  33138. pipeline.aacStream.on('data', function (data) {
  33139. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  33140. return;
  33141. }
  33142. audioTrack = audioTrack || {
  33143. timelineStartInfo: {
  33144. baseMediaDecodeTime: self.baseMediaDecodeTime
  33145. },
  33146. codec: 'adts',
  33147. type: 'audio'
  33148. }; // hook up the audio segment stream to the first track with aac data
  33149. pipeline.coalesceStream.numberOfTracks++;
  33150. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  33151. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33152. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  33153. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  33154. self.trigger('trackinfo', {
  33155. hasAudio: !!audioTrack,
  33156. hasVideo: !!videoTrack
  33157. });
  33158. }); // Re-emit any data coming from the coalesce stream to the outside world
  33159. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  33160. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33161. addPipelineLogRetriggers(this, pipeline);
  33162. };
  33163. this.setupTsPipeline = function () {
  33164. var pipeline = {};
  33165. this.transmuxPipeline_ = pipeline;
  33166. pipeline.type = 'ts';
  33167. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  33168. pipeline.packetStream = new m2ts.TransportPacketStream();
  33169. pipeline.parseStream = new m2ts.TransportParseStream();
  33170. pipeline.elementaryStream = new m2ts.ElementaryStream();
  33171. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  33172. pipeline.adtsStream = new AdtsStream();
  33173. pipeline.h264Stream = new H264Stream();
  33174. pipeline.captionStream = new m2ts.CaptionStream(options);
  33175. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  33176. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  33177. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  33178. // demux the streams
  33179. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  33180. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  33181. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  33182. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  33183. pipeline.elementaryStream.on('data', function (data) {
  33184. var i;
  33185. if (data.type === 'metadata') {
  33186. i = data.tracks.length; // scan the tracks listed in the metadata
  33187. while (i--) {
  33188. if (!videoTrack && data.tracks[i].type === 'video') {
  33189. videoTrack = data.tracks[i];
  33190. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33191. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  33192. audioTrack = data.tracks[i];
  33193. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33194. }
  33195. } // hook up the video segment stream to the first track with h264 data
  33196. if (videoTrack && !pipeline.videoSegmentStream) {
  33197. pipeline.coalesceStream.numberOfTracks++;
  33198. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  33199. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  33200. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  33201. // When video emits timelineStartInfo data after a flush, we forward that
  33202. // info to the AudioSegmentStream, if it exists, because video timeline
  33203. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  33204. // because this is a particularly subtle form of timestamp alteration.
  33205. if (audioTrack && !options.keepOriginalTimestamps) {
  33206. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  33207. // very earliest DTS we have seen in video because Chrome will
  33208. // interpret any video track with a baseMediaDecodeTime that is
  33209. // non-zero as a gap.
  33210. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  33211. }
  33212. });
  33213. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  33214. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  33215. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  33216. if (audioTrack) {
  33217. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  33218. }
  33219. });
  33220. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  33221. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  33222. }
  33223. if (audioTrack && !pipeline.audioSegmentStream) {
  33224. // hook up the audio segment stream to the first track with aac data
  33225. pipeline.coalesceStream.numberOfTracks++;
  33226. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  33227. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33228. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  33229. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  33230. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  33231. } // emit pmt info
  33232. self.trigger('trackinfo', {
  33233. hasAudio: !!audioTrack,
  33234. hasVideo: !!videoTrack
  33235. });
  33236. }
  33237. }); // Re-emit any data coming from the coalesce stream to the outside world
  33238. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  33239. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  33240. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  33241. self.trigger('id3Frame', id3Frame);
  33242. });
  33243. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  33244. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33245. addPipelineLogRetriggers(this, pipeline);
  33246. }; // hook up the segment streams once track metadata is delivered
  33247. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  33248. var pipeline = this.transmuxPipeline_;
  33249. if (!options.keepOriginalTimestamps) {
  33250. this.baseMediaDecodeTime = baseMediaDecodeTime;
  33251. }
  33252. if (audioTrack) {
  33253. audioTrack.timelineStartInfo.dts = undefined;
  33254. audioTrack.timelineStartInfo.pts = undefined;
  33255. trackDecodeInfo.clearDtsInfo(audioTrack);
  33256. if (pipeline.audioTimestampRolloverStream) {
  33257. pipeline.audioTimestampRolloverStream.discontinuity();
  33258. }
  33259. }
  33260. if (videoTrack) {
  33261. if (pipeline.videoSegmentStream) {
  33262. pipeline.videoSegmentStream.gopCache_ = [];
  33263. }
  33264. videoTrack.timelineStartInfo.dts = undefined;
  33265. videoTrack.timelineStartInfo.pts = undefined;
  33266. trackDecodeInfo.clearDtsInfo(videoTrack);
  33267. pipeline.captionStream.reset();
  33268. }
  33269. if (pipeline.timestampRolloverStream) {
  33270. pipeline.timestampRolloverStream.discontinuity();
  33271. }
  33272. };
  33273. this.setAudioAppendStart = function (timestamp) {
  33274. if (audioTrack) {
  33275. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  33276. }
  33277. };
  33278. this.setRemux = function (val) {
  33279. var pipeline = this.transmuxPipeline_;
  33280. options.remux = val;
  33281. if (pipeline && pipeline.coalesceStream) {
  33282. pipeline.coalesceStream.setRemux(val);
  33283. }
  33284. };
  33285. this.alignGopsWith = function (gopsToAlignWith) {
  33286. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  33287. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  33288. }
  33289. };
  33290. this.getLogTrigger_ = function (key) {
  33291. var self = this;
  33292. return function (event) {
  33293. event.stream = key;
  33294. self.trigger('log', event);
  33295. };
  33296. }; // feed incoming data to the front of the parsing pipeline
  33297. this.push = function (data) {
  33298. if (hasFlushed) {
  33299. var isAac = isLikelyAacData(data);
  33300. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  33301. this.setupAacPipeline();
  33302. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  33303. this.setupTsPipeline();
  33304. }
  33305. hasFlushed = false;
  33306. }
  33307. this.transmuxPipeline_.headOfPipeline.push(data);
  33308. }; // flush any buffered data
  33309. this.flush = function () {
  33310. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  33311. this.transmuxPipeline_.headOfPipeline.flush();
  33312. };
  33313. this.endTimeline = function () {
  33314. this.transmuxPipeline_.headOfPipeline.endTimeline();
  33315. };
  33316. this.reset = function () {
  33317. if (this.transmuxPipeline_.headOfPipeline) {
  33318. this.transmuxPipeline_.headOfPipeline.reset();
  33319. }
  33320. }; // Caption data has to be reset when seeking outside buffered range
  33321. this.resetCaptions = function () {
  33322. if (this.transmuxPipeline_.captionStream) {
  33323. this.transmuxPipeline_.captionStream.reset();
  33324. }
  33325. };
  33326. };
  33327. Transmuxer.prototype = new Stream();
  33328. var transmuxer = {
  33329. Transmuxer: Transmuxer,
  33330. VideoSegmentStream: VideoSegmentStream,
  33331. AudioSegmentStream: AudioSegmentStream,
  33332. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  33333. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  33334. // exported for testing
  33335. generateSegmentTimingInfo: generateSegmentTimingInfo
  33336. };
  33337. /**
  33338. * mux.js
  33339. *
  33340. * Copyright (c) Brightcove
  33341. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  33342. */
  33343. var toUnsigned$3 = function (value) {
  33344. return value >>> 0;
  33345. };
  33346. var toHexString$1 = function (value) {
  33347. return ('00' + value.toString(16)).slice(-2);
  33348. };
  33349. var bin = {
  33350. toUnsigned: toUnsigned$3,
  33351. toHexString: toHexString$1
  33352. };
  33353. var parseType$3 = function (buffer) {
  33354. var result = '';
  33355. result += String.fromCharCode(buffer[0]);
  33356. result += String.fromCharCode(buffer[1]);
  33357. result += String.fromCharCode(buffer[2]);
  33358. result += String.fromCharCode(buffer[3]);
  33359. return result;
  33360. };
  33361. var parseType_1 = parseType$3;
  33362. var toUnsigned$2 = bin.toUnsigned;
  33363. var parseType$2 = parseType_1;
  33364. var findBox$2 = function (data, path) {
  33365. var results = [],
  33366. i,
  33367. size,
  33368. type,
  33369. end,
  33370. subresults;
  33371. if (!path.length) {
  33372. // short-circuit the search for empty paths
  33373. return null;
  33374. }
  33375. for (i = 0; i < data.byteLength;) {
  33376. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  33377. type = parseType$2(data.subarray(i + 4, i + 8));
  33378. end = size > 1 ? i + size : data.byteLength;
  33379. if (type === path[0]) {
  33380. if (path.length === 1) {
  33381. // this is the end of the path and we've found the box we were
  33382. // looking for
  33383. results.push(data.subarray(i + 8, end));
  33384. } else {
  33385. // recursively search for the next box along the path
  33386. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  33387. if (subresults.length) {
  33388. results = results.concat(subresults);
  33389. }
  33390. }
  33391. }
  33392. i = end;
  33393. } // we've finished searching all of data
  33394. return results;
  33395. };
  33396. var findBox_1 = findBox$2;
  33397. var toUnsigned$1 = bin.toUnsigned;
  33398. var getUint64$2 = numbers.getUint64;
  33399. var tfdt = function (data) {
  33400. var result = {
  33401. version: data[0],
  33402. flags: new Uint8Array(data.subarray(1, 4))
  33403. };
  33404. if (result.version === 1) {
  33405. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  33406. } else {
  33407. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  33408. }
  33409. return result;
  33410. };
  33411. var parseTfdt$2 = tfdt;
  33412. var parseSampleFlags$1 = function (flags) {
  33413. return {
  33414. isLeading: (flags[0] & 0x0c) >>> 2,
  33415. dependsOn: flags[0] & 0x03,
  33416. isDependedOn: (flags[1] & 0xc0) >>> 6,
  33417. hasRedundancy: (flags[1] & 0x30) >>> 4,
  33418. paddingValue: (flags[1] & 0x0e) >>> 1,
  33419. isNonSyncSample: flags[1] & 0x01,
  33420. degradationPriority: flags[2] << 8 | flags[3]
  33421. };
  33422. };
  33423. var parseSampleFlags_1 = parseSampleFlags$1;
  33424. var parseSampleFlags = parseSampleFlags_1;
  33425. var trun = function (data) {
  33426. var result = {
  33427. version: data[0],
  33428. flags: new Uint8Array(data.subarray(1, 4)),
  33429. samples: []
  33430. },
  33431. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33432. // Flag interpretation
  33433. dataOffsetPresent = result.flags[2] & 0x01,
  33434. // compare with 2nd byte of 0x1
  33435. firstSampleFlagsPresent = result.flags[2] & 0x04,
  33436. // compare with 2nd byte of 0x4
  33437. sampleDurationPresent = result.flags[1] & 0x01,
  33438. // compare with 2nd byte of 0x100
  33439. sampleSizePresent = result.flags[1] & 0x02,
  33440. // compare with 2nd byte of 0x200
  33441. sampleFlagsPresent = result.flags[1] & 0x04,
  33442. // compare with 2nd byte of 0x400
  33443. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  33444. // compare with 2nd byte of 0x800
  33445. sampleCount = view.getUint32(4),
  33446. offset = 8,
  33447. sample;
  33448. if (dataOffsetPresent) {
  33449. // 32 bit signed integer
  33450. result.dataOffset = view.getInt32(offset);
  33451. offset += 4;
  33452. } // Overrides the flags for the first sample only. The order of
  33453. // optional values will be: duration, size, compositionTimeOffset
  33454. if (firstSampleFlagsPresent && sampleCount) {
  33455. sample = {
  33456. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  33457. };
  33458. offset += 4;
  33459. if (sampleDurationPresent) {
  33460. sample.duration = view.getUint32(offset);
  33461. offset += 4;
  33462. }
  33463. if (sampleSizePresent) {
  33464. sample.size = view.getUint32(offset);
  33465. offset += 4;
  33466. }
  33467. if (sampleCompositionTimeOffsetPresent) {
  33468. if (result.version === 1) {
  33469. sample.compositionTimeOffset = view.getInt32(offset);
  33470. } else {
  33471. sample.compositionTimeOffset = view.getUint32(offset);
  33472. }
  33473. offset += 4;
  33474. }
  33475. result.samples.push(sample);
  33476. sampleCount--;
  33477. }
  33478. while (sampleCount--) {
  33479. sample = {};
  33480. if (sampleDurationPresent) {
  33481. sample.duration = view.getUint32(offset);
  33482. offset += 4;
  33483. }
  33484. if (sampleSizePresent) {
  33485. sample.size = view.getUint32(offset);
  33486. offset += 4;
  33487. }
  33488. if (sampleFlagsPresent) {
  33489. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  33490. offset += 4;
  33491. }
  33492. if (sampleCompositionTimeOffsetPresent) {
  33493. if (result.version === 1) {
  33494. sample.compositionTimeOffset = view.getInt32(offset);
  33495. } else {
  33496. sample.compositionTimeOffset = view.getUint32(offset);
  33497. }
  33498. offset += 4;
  33499. }
  33500. result.samples.push(sample);
  33501. }
  33502. return result;
  33503. };
  33504. var parseTrun$2 = trun;
  33505. var tfhd = function (data) {
  33506. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33507. result = {
  33508. version: data[0],
  33509. flags: new Uint8Array(data.subarray(1, 4)),
  33510. trackId: view.getUint32(4)
  33511. },
  33512. baseDataOffsetPresent = result.flags[2] & 0x01,
  33513. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  33514. defaultSampleDurationPresent = result.flags[2] & 0x08,
  33515. defaultSampleSizePresent = result.flags[2] & 0x10,
  33516. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  33517. durationIsEmpty = result.flags[0] & 0x010000,
  33518. defaultBaseIsMoof = result.flags[0] & 0x020000,
  33519. i;
  33520. i = 8;
  33521. if (baseDataOffsetPresent) {
  33522. i += 4; // truncate top 4 bytes
  33523. // FIXME: should we read the full 64 bits?
  33524. result.baseDataOffset = view.getUint32(12);
  33525. i += 4;
  33526. }
  33527. if (sampleDescriptionIndexPresent) {
  33528. result.sampleDescriptionIndex = view.getUint32(i);
  33529. i += 4;
  33530. }
  33531. if (defaultSampleDurationPresent) {
  33532. result.defaultSampleDuration = view.getUint32(i);
  33533. i += 4;
  33534. }
  33535. if (defaultSampleSizePresent) {
  33536. result.defaultSampleSize = view.getUint32(i);
  33537. i += 4;
  33538. }
  33539. if (defaultSampleFlagsPresent) {
  33540. result.defaultSampleFlags = view.getUint32(i);
  33541. }
  33542. if (durationIsEmpty) {
  33543. result.durationIsEmpty = true;
  33544. }
  33545. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  33546. result.baseDataOffsetIsMoof = true;
  33547. }
  33548. return result;
  33549. };
  33550. var parseTfhd$2 = tfhd;
  33551. var win;
  33552. if (typeof window !== "undefined") {
  33553. win = window;
  33554. } else if (typeof commonjsGlobal !== "undefined") {
  33555. win = commonjsGlobal;
  33556. } else if (typeof self !== "undefined") {
  33557. win = self;
  33558. } else {
  33559. win = {};
  33560. }
  33561. var window_1 = win;
  33562. /**
  33563. * mux.js
  33564. *
  33565. * Copyright (c) Brightcove
  33566. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  33567. *
  33568. * Reads in-band CEA-708 captions out of FMP4 segments.
  33569. * @see https://en.wikipedia.org/wiki/CEA-708
  33570. */
  33571. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  33572. var CaptionStream = captionStream.CaptionStream;
  33573. var findBox$1 = findBox_1;
  33574. var parseTfdt$1 = parseTfdt$2;
  33575. var parseTrun$1 = parseTrun$2;
  33576. var parseTfhd$1 = parseTfhd$2;
  33577. var window$2 = window_1;
  33578. /**
  33579. * Maps an offset in the mdat to a sample based on the the size of the samples.
  33580. * Assumes that `parseSamples` has been called first.
  33581. *
  33582. * @param {Number} offset - The offset into the mdat
  33583. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  33584. * @return {?Object} The matching sample, or null if no match was found.
  33585. *
  33586. * @see ISO-BMFF-12/2015, Section 8.8.8
  33587. **/
  33588. var mapToSample = function (offset, samples) {
  33589. var approximateOffset = offset;
  33590. for (var i = 0; i < samples.length; i++) {
  33591. var sample = samples[i];
  33592. if (approximateOffset < sample.size) {
  33593. return sample;
  33594. }
  33595. approximateOffset -= sample.size;
  33596. }
  33597. return null;
  33598. };
  33599. /**
  33600. * Finds SEI nal units contained in a Media Data Box.
  33601. * Assumes that `parseSamples` has been called first.
  33602. *
  33603. * @param {Uint8Array} avcStream - The bytes of the mdat
  33604. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  33605. * @param {Number} trackId - The trackId of this video track
  33606. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  33607. * The contents of the seiNal should match what is expected by
  33608. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  33609. *
  33610. * @see ISO-BMFF-12/2015, Section 8.1.1
  33611. * @see Rec. ITU-T H.264, 7.3.2.3.1
  33612. **/
  33613. var findSeiNals = function (avcStream, samples, trackId) {
  33614. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  33615. result = {
  33616. logs: [],
  33617. seiNals: []
  33618. },
  33619. seiNal,
  33620. i,
  33621. length,
  33622. lastMatchedSample;
  33623. for (i = 0; i + 4 < avcStream.length; i += length) {
  33624. length = avcView.getUint32(i);
  33625. i += 4; // Bail if this doesn't appear to be an H264 stream
  33626. if (length <= 0) {
  33627. continue;
  33628. }
  33629. switch (avcStream[i] & 0x1F) {
  33630. case 0x06:
  33631. var data = avcStream.subarray(i + 1, i + 1 + length);
  33632. var matchingSample = mapToSample(i, samples);
  33633. seiNal = {
  33634. nalUnitType: 'sei_rbsp',
  33635. size: length,
  33636. data: data,
  33637. escapedRBSP: discardEmulationPreventionBytes(data),
  33638. trackId: trackId
  33639. };
  33640. if (matchingSample) {
  33641. seiNal.pts = matchingSample.pts;
  33642. seiNal.dts = matchingSample.dts;
  33643. lastMatchedSample = matchingSample;
  33644. } else if (lastMatchedSample) {
  33645. // If a matching sample cannot be found, use the last
  33646. // sample's values as they should be as close as possible
  33647. seiNal.pts = lastMatchedSample.pts;
  33648. seiNal.dts = lastMatchedSample.dts;
  33649. } else {
  33650. result.logs.push({
  33651. level: 'warn',
  33652. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  33653. });
  33654. break;
  33655. }
  33656. result.seiNals.push(seiNal);
  33657. break;
  33658. }
  33659. }
  33660. return result;
  33661. };
  33662. /**
  33663. * Parses sample information out of Track Run Boxes and calculates
  33664. * the absolute presentation and decode timestamps of each sample.
  33665. *
  33666. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  33667. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  33668. @see ISO-BMFF-12/2015, Section 8.8.12
  33669. * @param {Object} tfhd - The parsed Track Fragment Header
  33670. * @see inspect.parseTfhd
  33671. * @return {Object[]} the parsed samples
  33672. *
  33673. * @see ISO-BMFF-12/2015, Section 8.8.8
  33674. **/
  33675. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  33676. var currentDts = baseMediaDecodeTime;
  33677. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  33678. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  33679. var trackId = tfhd.trackId;
  33680. var allSamples = [];
  33681. truns.forEach(function (trun) {
  33682. // Note: We currently do not parse the sample table as well
  33683. // as the trun. It's possible some sources will require this.
  33684. // moov > trak > mdia > minf > stbl
  33685. var trackRun = parseTrun$1(trun);
  33686. var samples = trackRun.samples;
  33687. samples.forEach(function (sample) {
  33688. if (sample.duration === undefined) {
  33689. sample.duration = defaultSampleDuration;
  33690. }
  33691. if (sample.size === undefined) {
  33692. sample.size = defaultSampleSize;
  33693. }
  33694. sample.trackId = trackId;
  33695. sample.dts = currentDts;
  33696. if (sample.compositionTimeOffset === undefined) {
  33697. sample.compositionTimeOffset = 0;
  33698. }
  33699. if (typeof currentDts === 'bigint') {
  33700. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  33701. currentDts += window$2.BigInt(sample.duration);
  33702. } else {
  33703. sample.pts = currentDts + sample.compositionTimeOffset;
  33704. currentDts += sample.duration;
  33705. }
  33706. });
  33707. allSamples = allSamples.concat(samples);
  33708. });
  33709. return allSamples;
  33710. };
  33711. /**
  33712. * Parses out caption nals from an FMP4 segment's video tracks.
  33713. *
  33714. * @param {Uint8Array} segment - The bytes of a single segment
  33715. * @param {Number} videoTrackId - The trackId of a video track in the segment
  33716. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  33717. * a list of seiNals found in that track
  33718. **/
  33719. var parseCaptionNals = function (segment, videoTrackId) {
  33720. // To get the samples
  33721. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  33722. var mdats = findBox$1(segment, ['mdat']);
  33723. var captionNals = {};
  33724. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  33725. mdats.forEach(function (mdat, index) {
  33726. var matchingTraf = trafs[index];
  33727. mdatTrafPairs.push({
  33728. mdat: mdat,
  33729. traf: matchingTraf
  33730. });
  33731. });
  33732. mdatTrafPairs.forEach(function (pair) {
  33733. var mdat = pair.mdat;
  33734. var traf = pair.traf;
  33735. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  33736. var headerInfo = parseTfhd$1(tfhd[0]);
  33737. var trackId = headerInfo.trackId;
  33738. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  33739. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  33740. var truns = findBox$1(traf, ['trun']);
  33741. var samples;
  33742. var result; // Only parse video data for the chosen video track
  33743. if (videoTrackId === trackId && truns.length > 0) {
  33744. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  33745. result = findSeiNals(mdat, samples, trackId);
  33746. if (!captionNals[trackId]) {
  33747. captionNals[trackId] = {
  33748. seiNals: [],
  33749. logs: []
  33750. };
  33751. }
  33752. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  33753. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  33754. }
  33755. });
  33756. return captionNals;
  33757. };
  33758. /**
  33759. * Parses out inband captions from an MP4 container and returns
  33760. * caption objects that can be used by WebVTT and the TextTrack API.
  33761. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  33762. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  33763. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  33764. *
  33765. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33766. * @param {Number} trackId - The id of the video track to parse
  33767. * @param {Number} timescale - The timescale for the video track from the init segment
  33768. *
  33769. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  33770. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  33771. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  33772. * @return {String} parsedCaptions[].text - The visible content of the caption
  33773. **/
  33774. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  33775. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33776. if (trackId === null) {
  33777. return null;
  33778. }
  33779. captionNals = parseCaptionNals(segment, trackId);
  33780. var trackNals = captionNals[trackId] || {};
  33781. return {
  33782. seiNals: trackNals.seiNals,
  33783. logs: trackNals.logs,
  33784. timescale: timescale
  33785. };
  33786. };
  33787. /**
  33788. * Converts SEI NALUs into captions that can be used by video.js
  33789. **/
  33790. var CaptionParser = function () {
  33791. var isInitialized = false;
  33792. var captionStream; // Stores segments seen before trackId and timescale are set
  33793. var segmentCache; // Stores video track ID of the track being parsed
  33794. var trackId; // Stores the timescale of the track being parsed
  33795. var timescale; // Stores captions parsed so far
  33796. var parsedCaptions; // Stores whether we are receiving partial data or not
  33797. var parsingPartial;
  33798. /**
  33799. * A method to indicate whether a CaptionParser has been initalized
  33800. * @returns {Boolean}
  33801. **/
  33802. this.isInitialized = function () {
  33803. return isInitialized;
  33804. };
  33805. /**
  33806. * Initializes the underlying CaptionStream, SEI NAL parsing
  33807. * and management, and caption collection
  33808. **/
  33809. this.init = function (options) {
  33810. captionStream = new CaptionStream();
  33811. isInitialized = true;
  33812. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  33813. captionStream.on('data', function (event) {
  33814. // Convert to seconds in the source's timescale
  33815. event.startTime = event.startPts / timescale;
  33816. event.endTime = event.endPts / timescale;
  33817. parsedCaptions.captions.push(event);
  33818. parsedCaptions.captionStreams[event.stream] = true;
  33819. });
  33820. captionStream.on('log', function (log) {
  33821. parsedCaptions.logs.push(log);
  33822. });
  33823. };
  33824. /**
  33825. * Determines if a new video track will be selected
  33826. * or if the timescale changed
  33827. * @return {Boolean}
  33828. **/
  33829. this.isNewInit = function (videoTrackIds, timescales) {
  33830. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  33831. return false;
  33832. }
  33833. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  33834. };
  33835. /**
  33836. * Parses out SEI captions and interacts with underlying
  33837. * CaptionStream to return dispatched captions
  33838. *
  33839. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33840. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  33841. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  33842. * @see parseEmbeddedCaptions
  33843. * @see m2ts/caption-stream.js
  33844. **/
  33845. this.parse = function (segment, videoTrackIds, timescales) {
  33846. var parsedData;
  33847. if (!this.isInitialized()) {
  33848. return null; // This is not likely to be a video segment
  33849. } else if (!videoTrackIds || !timescales) {
  33850. return null;
  33851. } else if (this.isNewInit(videoTrackIds, timescales)) {
  33852. // Use the first video track only as there is no
  33853. // mechanism to switch to other video tracks
  33854. trackId = videoTrackIds[0];
  33855. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  33856. // data until we have one.
  33857. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33858. } else if (trackId === null || !timescale) {
  33859. segmentCache.push(segment);
  33860. return null;
  33861. } // Now that a timescale and trackId is set, parse cached segments
  33862. while (segmentCache.length > 0) {
  33863. var cachedSegment = segmentCache.shift();
  33864. this.parse(cachedSegment, videoTrackIds, timescales);
  33865. }
  33866. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  33867. if (parsedData && parsedData.logs) {
  33868. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  33869. }
  33870. if (parsedData === null || !parsedData.seiNals) {
  33871. if (parsedCaptions.logs.length) {
  33872. return {
  33873. logs: parsedCaptions.logs,
  33874. captions: [],
  33875. captionStreams: []
  33876. };
  33877. }
  33878. return null;
  33879. }
  33880. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  33881. this.flushStream();
  33882. return parsedCaptions;
  33883. };
  33884. /**
  33885. * Pushes SEI NALUs onto CaptionStream
  33886. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  33887. * Assumes that `parseCaptionNals` has been called first
  33888. * @see m2ts/caption-stream.js
  33889. **/
  33890. this.pushNals = function (nals) {
  33891. if (!this.isInitialized() || !nals || nals.length === 0) {
  33892. return null;
  33893. }
  33894. nals.forEach(function (nal) {
  33895. captionStream.push(nal);
  33896. });
  33897. };
  33898. /**
  33899. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  33900. * @see m2ts/caption-stream.js
  33901. **/
  33902. this.flushStream = function () {
  33903. if (!this.isInitialized()) {
  33904. return null;
  33905. }
  33906. if (!parsingPartial) {
  33907. captionStream.flush();
  33908. } else {
  33909. captionStream.partialFlush();
  33910. }
  33911. };
  33912. /**
  33913. * Reset caption buckets for new data
  33914. **/
  33915. this.clearParsedCaptions = function () {
  33916. parsedCaptions.captions = [];
  33917. parsedCaptions.captionStreams = {};
  33918. parsedCaptions.logs = [];
  33919. };
  33920. /**
  33921. * Resets underlying CaptionStream
  33922. * @see m2ts/caption-stream.js
  33923. **/
  33924. this.resetCaptionStream = function () {
  33925. if (!this.isInitialized()) {
  33926. return null;
  33927. }
  33928. captionStream.reset();
  33929. };
  33930. /**
  33931. * Convenience method to clear all captions flushed from the
  33932. * CaptionStream and still being parsed
  33933. * @see m2ts/caption-stream.js
  33934. **/
  33935. this.clearAllCaptions = function () {
  33936. this.clearParsedCaptions();
  33937. this.resetCaptionStream();
  33938. };
  33939. /**
  33940. * Reset caption parser
  33941. **/
  33942. this.reset = function () {
  33943. segmentCache = [];
  33944. trackId = null;
  33945. timescale = null;
  33946. if (!parsedCaptions) {
  33947. parsedCaptions = {
  33948. captions: [],
  33949. // CC1, CC2, CC3, CC4
  33950. captionStreams: {},
  33951. logs: []
  33952. };
  33953. } else {
  33954. this.clearParsedCaptions();
  33955. }
  33956. this.resetCaptionStream();
  33957. };
  33958. this.reset();
  33959. };
  33960. var captionParser = CaptionParser;
  33961. /**
  33962. * Returns the first string in the data array ending with a null char '\0'
  33963. * @param {UInt8} data
  33964. * @returns the string with the null char
  33965. */
  33966. var uint8ToCString$1 = function (data) {
  33967. var index = 0;
  33968. var curChar = String.fromCharCode(data[index]);
  33969. var retString = '';
  33970. while (curChar !== '\0') {
  33971. retString += curChar;
  33972. index++;
  33973. curChar = String.fromCharCode(data[index]);
  33974. } // Add nullChar
  33975. retString += curChar;
  33976. return retString;
  33977. };
  33978. var string = {
  33979. uint8ToCString: uint8ToCString$1
  33980. };
  33981. var uint8ToCString = string.uint8ToCString;
  33982. var getUint64$1 = numbers.getUint64;
  33983. /**
  33984. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  33985. * References:
  33986. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  33987. * https://aomediacodec.github.io/id3-emsg/
  33988. *
  33989. * Takes emsg box data as a uint8 array and returns a emsg box object
  33990. * @param {UInt8Array} boxData data from emsg box
  33991. * @returns A parsed emsg box object
  33992. */
  33993. var parseEmsgBox = function (boxData) {
  33994. // version + flags
  33995. var offset = 4;
  33996. var version = boxData[0];
  33997. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  33998. if (version === 0) {
  33999. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  34000. offset += scheme_id_uri.length;
  34001. value = uint8ToCString(boxData.subarray(offset));
  34002. offset += value.length;
  34003. var dv = new DataView(boxData.buffer);
  34004. timescale = dv.getUint32(offset);
  34005. offset += 4;
  34006. presentation_time_delta = dv.getUint32(offset);
  34007. offset += 4;
  34008. event_duration = dv.getUint32(offset);
  34009. offset += 4;
  34010. id = dv.getUint32(offset);
  34011. offset += 4;
  34012. } else if (version === 1) {
  34013. var dv = new DataView(boxData.buffer);
  34014. timescale = dv.getUint32(offset);
  34015. offset += 4;
  34016. presentation_time = getUint64$1(boxData.subarray(offset));
  34017. offset += 8;
  34018. event_duration = dv.getUint32(offset);
  34019. offset += 4;
  34020. id = dv.getUint32(offset);
  34021. offset += 4;
  34022. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  34023. offset += scheme_id_uri.length;
  34024. value = uint8ToCString(boxData.subarray(offset));
  34025. offset += value.length;
  34026. }
  34027. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  34028. var emsgBox = {
  34029. scheme_id_uri,
  34030. value,
  34031. // if timescale is undefined or 0 set to 1
  34032. timescale: timescale ? timescale : 1,
  34033. presentation_time,
  34034. presentation_time_delta,
  34035. event_duration,
  34036. id,
  34037. message_data
  34038. };
  34039. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  34040. };
  34041. /**
  34042. * Scales a presentation time or time delta with an offset with a provided timescale
  34043. * @param {number} presentationTime
  34044. * @param {number} timescale
  34045. * @param {number} timeDelta
  34046. * @param {number} offset
  34047. * @returns the scaled time as a number
  34048. */
  34049. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  34050. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  34051. };
  34052. /**
  34053. * Checks the emsg box data for validity based on the version
  34054. * @param {number} version of the emsg box to validate
  34055. * @param {Object} emsg the emsg data to validate
  34056. * @returns if the box is valid as a boolean
  34057. */
  34058. var isValidEmsgBox = function (version, emsg) {
  34059. var hasScheme = emsg.scheme_id_uri !== '\0';
  34060. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  34061. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  34062. return !(version > 1) && isValidV0Box || isValidV1Box;
  34063. }; // Utility function to check if an object is defined
  34064. var isDefined = function (data) {
  34065. return data !== undefined || data !== null;
  34066. };
  34067. var emsg$1 = {
  34068. parseEmsgBox: parseEmsgBox,
  34069. scaleTime: scaleTime
  34070. };
  34071. /**
  34072. * mux.js
  34073. *
  34074. * Copyright (c) Brightcove
  34075. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34076. *
  34077. * Utilities to detect basic properties and metadata about MP4s.
  34078. */
  34079. var toUnsigned = bin.toUnsigned;
  34080. var toHexString = bin.toHexString;
  34081. var findBox = findBox_1;
  34082. var parseType$1 = parseType_1;
  34083. var emsg = emsg$1;
  34084. var parseTfhd = parseTfhd$2;
  34085. var parseTrun = parseTrun$2;
  34086. var parseTfdt = parseTfdt$2;
  34087. var getUint64 = numbers.getUint64;
  34088. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  34089. var window$1 = window_1;
  34090. var parseId3Frames = parseId3.parseId3Frames;
  34091. /**
  34092. * Parses an MP4 initialization segment and extracts the timescale
  34093. * values for any declared tracks. Timescale values indicate the
  34094. * number of clock ticks per second to assume for time-based values
  34095. * elsewhere in the MP4.
  34096. *
  34097. * To determine the start time of an MP4, you need two pieces of
  34098. * information: the timescale unit and the earliest base media decode
  34099. * time. Multiple timescales can be specified within an MP4 but the
  34100. * base media decode time is always expressed in the timescale from
  34101. * the media header box for the track:
  34102. * ```
  34103. * moov > trak > mdia > mdhd.timescale
  34104. * ```
  34105. * @param init {Uint8Array} the bytes of the init segment
  34106. * @return {object} a hash of track ids to timescale values or null if
  34107. * the init segment is malformed.
  34108. */
  34109. timescale = function (init) {
  34110. var result = {},
  34111. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  34112. return traks.reduce(function (result, trak) {
  34113. var tkhd, version, index, id, mdhd;
  34114. tkhd = findBox(trak, ['tkhd'])[0];
  34115. if (!tkhd) {
  34116. return null;
  34117. }
  34118. version = tkhd[0];
  34119. index = version === 0 ? 12 : 20;
  34120. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  34121. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  34122. if (!mdhd) {
  34123. return null;
  34124. }
  34125. version = mdhd[0];
  34126. index = version === 0 ? 12 : 20;
  34127. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  34128. return result;
  34129. }, result);
  34130. };
  34131. /**
  34132. * Determine the base media decode start time, in seconds, for an MP4
  34133. * fragment. If multiple fragments are specified, the earliest time is
  34134. * returned.
  34135. *
  34136. * The base media decode time can be parsed from track fragment
  34137. * metadata:
  34138. * ```
  34139. * moof > traf > tfdt.baseMediaDecodeTime
  34140. * ```
  34141. * It requires the timescale value from the mdhd to interpret.
  34142. *
  34143. * @param timescale {object} a hash of track ids to timescale values.
  34144. * @return {number} the earliest base media decode start time for the
  34145. * fragment, in seconds
  34146. */
  34147. startTime = function (timescale, fragment) {
  34148. var trafs; // we need info from two childrend of each track fragment box
  34149. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  34150. var lowestTime = trafs.reduce(function (acc, traf) {
  34151. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  34152. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  34153. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  34154. var tfdt = findBox(traf, ['tfdt'])[0];
  34155. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  34156. var baseTime; // version 1 is 64 bit
  34157. if (tfdt[0] === 1) {
  34158. baseTime = getUint64(tfdt.subarray(4, 12));
  34159. } else {
  34160. baseTime = dv.getUint32(4);
  34161. } // convert base time to seconds if it is a valid number.
  34162. let seconds;
  34163. if (typeof baseTime === 'bigint') {
  34164. seconds = baseTime / window$1.BigInt(scale);
  34165. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  34166. seconds = baseTime / scale;
  34167. }
  34168. if (seconds < Number.MAX_SAFE_INTEGER) {
  34169. seconds = Number(seconds);
  34170. }
  34171. if (seconds < acc) {
  34172. acc = seconds;
  34173. }
  34174. return acc;
  34175. }, Infinity);
  34176. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  34177. };
  34178. /**
  34179. * Determine the composition start, in seconds, for an MP4
  34180. * fragment.
  34181. *
  34182. * The composition start time of a fragment can be calculated using the base
  34183. * media decode time, composition time offset, and timescale, as follows:
  34184. *
  34185. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  34186. *
  34187. * All of the aforementioned information is contained within a media fragment's
  34188. * `traf` box, except for timescale info, which comes from the initialization
  34189. * segment, so a track id (also contained within a `traf`) is also necessary to
  34190. * associate it with a timescale
  34191. *
  34192. *
  34193. * @param timescales {object} - a hash of track ids to timescale values.
  34194. * @param fragment {Unit8Array} - the bytes of a media segment
  34195. * @return {number} the composition start time for the fragment, in seconds
  34196. **/
  34197. compositionStartTime = function (timescales, fragment) {
  34198. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  34199. var baseMediaDecodeTime = 0;
  34200. var compositionTimeOffset = 0;
  34201. var trackId;
  34202. if (trafBoxes && trafBoxes.length) {
  34203. // The spec states that track run samples contained within a `traf` box are contiguous, but
  34204. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  34205. // We will assume that they are, so we only need the first to calculate start time.
  34206. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  34207. var trun = findBox(trafBoxes[0], ['trun'])[0];
  34208. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  34209. if (tfhd) {
  34210. var parsedTfhd = parseTfhd(tfhd);
  34211. trackId = parsedTfhd.trackId;
  34212. }
  34213. if (tfdt) {
  34214. var parsedTfdt = parseTfdt(tfdt);
  34215. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  34216. }
  34217. if (trun) {
  34218. var parsedTrun = parseTrun(trun);
  34219. if (parsedTrun.samples && parsedTrun.samples.length) {
  34220. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  34221. }
  34222. }
  34223. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  34224. // specified.
  34225. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  34226. if (typeof baseMediaDecodeTime === 'bigint') {
  34227. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  34228. timescale = window$1.BigInt(timescale);
  34229. }
  34230. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  34231. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  34232. result = Number(result);
  34233. }
  34234. return result;
  34235. };
  34236. /**
  34237. * Find the trackIds of the video tracks in this source.
  34238. * Found by parsing the Handler Reference and Track Header Boxes:
  34239. * moov > trak > mdia > hdlr
  34240. * moov > trak > tkhd
  34241. *
  34242. * @param {Uint8Array} init - The bytes of the init segment for this source
  34243. * @return {Number[]} A list of trackIds
  34244. *
  34245. * @see ISO-BMFF-12/2015, Section 8.4.3
  34246. **/
  34247. getVideoTrackIds = function (init) {
  34248. var traks = findBox(init, ['moov', 'trak']);
  34249. var videoTrackIds = [];
  34250. traks.forEach(function (trak) {
  34251. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  34252. var tkhds = findBox(trak, ['tkhd']);
  34253. hdlrs.forEach(function (hdlr, index) {
  34254. var handlerType = parseType$1(hdlr.subarray(8, 12));
  34255. var tkhd = tkhds[index];
  34256. var view;
  34257. var version;
  34258. var trackId;
  34259. if (handlerType === 'vide') {
  34260. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  34261. version = view.getUint8(0);
  34262. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  34263. videoTrackIds.push(trackId);
  34264. }
  34265. });
  34266. });
  34267. return videoTrackIds;
  34268. };
  34269. getTimescaleFromMediaHeader = function (mdhd) {
  34270. // mdhd is a FullBox, meaning it will have its own version as the first byte
  34271. var version = mdhd[0];
  34272. var index = version === 0 ? 12 : 20;
  34273. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  34274. };
  34275. /**
  34276. * Get all the video, audio, and hint tracks from a non fragmented
  34277. * mp4 segment
  34278. */
  34279. getTracks = function (init) {
  34280. var traks = findBox(init, ['moov', 'trak']);
  34281. var tracks = [];
  34282. traks.forEach(function (trak) {
  34283. var track = {};
  34284. var tkhd = findBox(trak, ['tkhd'])[0];
  34285. var view, tkhdVersion; // id
  34286. if (tkhd) {
  34287. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  34288. tkhdVersion = view.getUint8(0);
  34289. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  34290. }
  34291. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  34292. if (hdlr) {
  34293. var type = parseType$1(hdlr.subarray(8, 12));
  34294. if (type === 'vide') {
  34295. track.type = 'video';
  34296. } else if (type === 'soun') {
  34297. track.type = 'audio';
  34298. } else {
  34299. track.type = type;
  34300. }
  34301. } // codec
  34302. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  34303. if (stsd) {
  34304. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  34305. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  34306. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  34307. var codecConfig, codecConfigType;
  34308. if (codecBox) {
  34309. // https://tools.ietf.org/html/rfc6381#section-3.3
  34310. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  34311. // we don't need anything but the "config" parameter of the
  34312. // avc1 codecBox
  34313. codecConfig = codecBox.subarray(78);
  34314. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  34315. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  34316. track.codec += '.'; // left padded with zeroes for single digit hex
  34317. // profile idc
  34318. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  34319. track.codec += toHexString(codecConfig[10]); // level idc
  34320. track.codec += toHexString(codecConfig[11]);
  34321. } else {
  34322. // TODO: show a warning that we couldn't parse the codec
  34323. // and are using the default
  34324. track.codec = 'avc1.4d400d';
  34325. }
  34326. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  34327. // we do not need anything but the streamDescriptor of the mp4a codecBox
  34328. codecConfig = codecBox.subarray(28);
  34329. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  34330. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  34331. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  34332. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  34333. } else {
  34334. // TODO: show a warning that we couldn't parse the codec
  34335. // and are using the default
  34336. track.codec = 'mp4a.40.2';
  34337. }
  34338. } else {
  34339. // flac, opus, etc
  34340. track.codec = track.codec.toLowerCase();
  34341. }
  34342. }
  34343. }
  34344. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  34345. if (mdhd) {
  34346. track.timescale = getTimescaleFromMediaHeader(mdhd);
  34347. }
  34348. tracks.push(track);
  34349. });
  34350. return tracks;
  34351. };
  34352. /**
  34353. * Returns an array of emsg ID3 data from the provided segmentData.
  34354. * An offset can also be provided as the Latest Arrival Time to calculate
  34355. * the Event Start Time of v0 EMSG boxes.
  34356. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  34357. *
  34358. * @param {Uint8Array} segmentData the segment byte array.
  34359. * @param {number} offset the segment start time or Latest Arrival Time,
  34360. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  34361. */
  34362. getEmsgID3 = function (segmentData, offset = 0) {
  34363. var emsgBoxes = findBox(segmentData, ['emsg']);
  34364. return emsgBoxes.map(data => {
  34365. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  34366. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  34367. return {
  34368. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  34369. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  34370. frames: parsedId3Frames
  34371. };
  34372. });
  34373. };
  34374. var probe$2 = {
  34375. // export mp4 inspector's findBox and parseType for backwards compatibility
  34376. findBox: findBox,
  34377. parseType: parseType$1,
  34378. timescale: timescale,
  34379. startTime: startTime,
  34380. compositionStartTime: compositionStartTime,
  34381. videoTrackIds: getVideoTrackIds,
  34382. tracks: getTracks,
  34383. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  34384. getEmsgID3: getEmsgID3
  34385. };
  34386. /**
  34387. * mux.js
  34388. *
  34389. * Copyright (c) Brightcove
  34390. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34391. *
  34392. * Utilities to detect basic properties and metadata about TS Segments.
  34393. */
  34394. var StreamTypes$1 = streamTypes;
  34395. var parsePid = function (packet) {
  34396. var pid = packet[1] & 0x1f;
  34397. pid <<= 8;
  34398. pid |= packet[2];
  34399. return pid;
  34400. };
  34401. var parsePayloadUnitStartIndicator = function (packet) {
  34402. return !!(packet[1] & 0x40);
  34403. };
  34404. var parseAdaptionField = function (packet) {
  34405. var offset = 0; // if an adaption field is present, its length is specified by the
  34406. // fifth byte of the TS packet header. The adaptation field is
  34407. // used to add stuffing to PES packets that don't fill a complete
  34408. // TS packet, and to specify some forms of timing and control data
  34409. // that we do not currently use.
  34410. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  34411. offset += packet[4] + 1;
  34412. }
  34413. return offset;
  34414. };
  34415. var parseType = function (packet, pmtPid) {
  34416. var pid = parsePid(packet);
  34417. if (pid === 0) {
  34418. return 'pat';
  34419. } else if (pid === pmtPid) {
  34420. return 'pmt';
  34421. } else if (pmtPid) {
  34422. return 'pes';
  34423. }
  34424. return null;
  34425. };
  34426. var parsePat = function (packet) {
  34427. var pusi = parsePayloadUnitStartIndicator(packet);
  34428. var offset = 4 + parseAdaptionField(packet);
  34429. if (pusi) {
  34430. offset += packet[offset] + 1;
  34431. }
  34432. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  34433. };
  34434. var parsePmt = function (packet) {
  34435. var programMapTable = {};
  34436. var pusi = parsePayloadUnitStartIndicator(packet);
  34437. var payloadOffset = 4 + parseAdaptionField(packet);
  34438. if (pusi) {
  34439. payloadOffset += packet[payloadOffset] + 1;
  34440. } // PMTs can be sent ahead of the time when they should actually
  34441. // take effect. We don't believe this should ever be the case
  34442. // for HLS but we'll ignore "forward" PMT declarations if we see
  34443. // them. Future PMT declarations have the current_next_indicator
  34444. // set to zero.
  34445. if (!(packet[payloadOffset + 5] & 0x01)) {
  34446. return;
  34447. }
  34448. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  34449. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  34450. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  34451. // long the program info descriptors are
  34452. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  34453. var offset = 12 + programInfoLength;
  34454. while (offset < tableEnd) {
  34455. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  34456. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  34457. // skip past the elementary stream descriptors, if present
  34458. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  34459. }
  34460. return programMapTable;
  34461. };
  34462. var parsePesType = function (packet, programMapTable) {
  34463. var pid = parsePid(packet);
  34464. var type = programMapTable[pid];
  34465. switch (type) {
  34466. case StreamTypes$1.H264_STREAM_TYPE:
  34467. return 'video';
  34468. case StreamTypes$1.ADTS_STREAM_TYPE:
  34469. return 'audio';
  34470. case StreamTypes$1.METADATA_STREAM_TYPE:
  34471. return 'timed-metadata';
  34472. default:
  34473. return null;
  34474. }
  34475. };
  34476. var parsePesTime = function (packet) {
  34477. var pusi = parsePayloadUnitStartIndicator(packet);
  34478. if (!pusi) {
  34479. return null;
  34480. }
  34481. var offset = 4 + parseAdaptionField(packet);
  34482. if (offset >= packet.byteLength) {
  34483. // From the H 222.0 MPEG-TS spec
  34484. // "For transport stream packets carrying PES packets, stuffing is needed when there
  34485. // is insufficient PES packet data to completely fill the transport stream packet
  34486. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  34487. // the sum of the lengths of the data elements in it, so that the payload bytes
  34488. // remaining after the adaptation field exactly accommodates the available PES packet
  34489. // data."
  34490. //
  34491. // If the offset is >= the length of the packet, then the packet contains no data
  34492. // and instead is just adaption field stuffing bytes
  34493. return null;
  34494. }
  34495. var pes = null;
  34496. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  34497. // and a DTS value. Determine what combination of values is
  34498. // available to work with.
  34499. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  34500. // performs all bitwise operations on 32-bit integers but javascript
  34501. // supports a much greater range (52-bits) of integer using standard
  34502. // mathematical operations.
  34503. // We construct a 31-bit value using bitwise operators over the 31
  34504. // most significant bits and then multiply by 4 (equal to a left-shift
  34505. // of 2) before we add the final 2 least significant bits of the
  34506. // timestamp (equal to an OR.)
  34507. if (ptsDtsFlags & 0xC0) {
  34508. pes = {}; // the PTS and DTS are not written out directly. For information
  34509. // on how they are encoded, see
  34510. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  34511. pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
  34512. pes.pts *= 4; // Left shift by 2
  34513. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  34514. pes.dts = pes.pts;
  34515. if (ptsDtsFlags & 0x40) {
  34516. pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
  34517. pes.dts *= 4; // Left shift by 2
  34518. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  34519. }
  34520. }
  34521. return pes;
  34522. };
  34523. var parseNalUnitType = function (type) {
  34524. switch (type) {
  34525. case 0x05:
  34526. return 'slice_layer_without_partitioning_rbsp_idr';
  34527. case 0x06:
  34528. return 'sei_rbsp';
  34529. case 0x07:
  34530. return 'seq_parameter_set_rbsp';
  34531. case 0x08:
  34532. return 'pic_parameter_set_rbsp';
  34533. case 0x09:
  34534. return 'access_unit_delimiter_rbsp';
  34535. default:
  34536. return null;
  34537. }
  34538. };
  34539. var videoPacketContainsKeyFrame = function (packet) {
  34540. var offset = 4 + parseAdaptionField(packet);
  34541. var frameBuffer = packet.subarray(offset);
  34542. var frameI = 0;
  34543. var frameSyncPoint = 0;
  34544. var foundKeyFrame = false;
  34545. var nalType; // advance the sync point to a NAL start, if necessary
  34546. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  34547. if (frameBuffer[frameSyncPoint + 2] === 1) {
  34548. // the sync point is properly aligned
  34549. frameI = frameSyncPoint + 5;
  34550. break;
  34551. }
  34552. }
  34553. while (frameI < frameBuffer.byteLength) {
  34554. // look at the current byte to determine if we've hit the end of
  34555. // a NAL unit boundary
  34556. switch (frameBuffer[frameI]) {
  34557. case 0:
  34558. // skip past non-sync sequences
  34559. if (frameBuffer[frameI - 1] !== 0) {
  34560. frameI += 2;
  34561. break;
  34562. } else if (frameBuffer[frameI - 2] !== 0) {
  34563. frameI++;
  34564. break;
  34565. }
  34566. if (frameSyncPoint + 3 !== frameI - 2) {
  34567. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34568. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34569. foundKeyFrame = true;
  34570. }
  34571. } // drop trailing zeroes
  34572. do {
  34573. frameI++;
  34574. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  34575. frameSyncPoint = frameI - 2;
  34576. frameI += 3;
  34577. break;
  34578. case 1:
  34579. // skip past non-sync sequences
  34580. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  34581. frameI += 3;
  34582. break;
  34583. }
  34584. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34585. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34586. foundKeyFrame = true;
  34587. }
  34588. frameSyncPoint = frameI - 2;
  34589. frameI += 3;
  34590. break;
  34591. default:
  34592. // the current byte isn't a one or zero, so it cannot be part
  34593. // of a sync sequence
  34594. frameI += 3;
  34595. break;
  34596. }
  34597. }
  34598. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  34599. frameI -= frameSyncPoint;
  34600. frameSyncPoint = 0; // parse the final nal
  34601. if (frameBuffer && frameBuffer.byteLength > 3) {
  34602. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34603. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34604. foundKeyFrame = true;
  34605. }
  34606. }
  34607. return foundKeyFrame;
  34608. };
  34609. var probe$1 = {
  34610. parseType: parseType,
  34611. parsePat: parsePat,
  34612. parsePmt: parsePmt,
  34613. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  34614. parsePesType: parsePesType,
  34615. parsePesTime: parsePesTime,
  34616. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  34617. };
  34618. /**
  34619. * mux.js
  34620. *
  34621. * Copyright (c) Brightcove
  34622. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34623. *
  34624. * Parse mpeg2 transport stream packets to extract basic timing information
  34625. */
  34626. var StreamTypes = streamTypes;
  34627. var handleRollover = timestampRolloverStream.handleRollover;
  34628. var probe = {};
  34629. probe.ts = probe$1;
  34630. probe.aac = utils;
  34631. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  34632. var MP2T_PACKET_LENGTH = 188,
  34633. // bytes
  34634. SYNC_BYTE = 0x47;
  34635. /**
  34636. * walks through segment data looking for pat and pmt packets to parse out
  34637. * program map table information
  34638. */
  34639. var parsePsi_ = function (bytes, pmt) {
  34640. var startIndex = 0,
  34641. endIndex = MP2T_PACKET_LENGTH,
  34642. packet,
  34643. type;
  34644. while (endIndex < bytes.byteLength) {
  34645. // Look for a pair of start and end sync bytes in the data..
  34646. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34647. // We found a packet
  34648. packet = bytes.subarray(startIndex, endIndex);
  34649. type = probe.ts.parseType(packet, pmt.pid);
  34650. switch (type) {
  34651. case 'pat':
  34652. pmt.pid = probe.ts.parsePat(packet);
  34653. break;
  34654. case 'pmt':
  34655. var table = probe.ts.parsePmt(packet);
  34656. pmt.table = pmt.table || {};
  34657. Object.keys(table).forEach(function (key) {
  34658. pmt.table[key] = table[key];
  34659. });
  34660. break;
  34661. }
  34662. startIndex += MP2T_PACKET_LENGTH;
  34663. endIndex += MP2T_PACKET_LENGTH;
  34664. continue;
  34665. } // If we get here, we have somehow become de-synchronized and we need to step
  34666. // forward one byte at a time until we find a pair of sync bytes that denote
  34667. // a packet
  34668. startIndex++;
  34669. endIndex++;
  34670. }
  34671. };
  34672. /**
  34673. * walks through the segment data from the start and end to get timing information
  34674. * for the first and last audio pes packets
  34675. */
  34676. var parseAudioPes_ = function (bytes, pmt, result) {
  34677. var startIndex = 0,
  34678. endIndex = MP2T_PACKET_LENGTH,
  34679. packet,
  34680. type,
  34681. pesType,
  34682. pusi,
  34683. parsed;
  34684. var endLoop = false; // Start walking from start of segment to get first audio packet
  34685. while (endIndex <= bytes.byteLength) {
  34686. // Look for a pair of start and end sync bytes in the data..
  34687. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34688. // We found a packet
  34689. packet = bytes.subarray(startIndex, endIndex);
  34690. type = probe.ts.parseType(packet, pmt.pid);
  34691. switch (type) {
  34692. case 'pes':
  34693. pesType = probe.ts.parsePesType(packet, pmt.table);
  34694. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34695. if (pesType === 'audio' && pusi) {
  34696. parsed = probe.ts.parsePesTime(packet);
  34697. if (parsed) {
  34698. parsed.type = 'audio';
  34699. result.audio.push(parsed);
  34700. endLoop = true;
  34701. }
  34702. }
  34703. break;
  34704. }
  34705. if (endLoop) {
  34706. break;
  34707. }
  34708. startIndex += MP2T_PACKET_LENGTH;
  34709. endIndex += MP2T_PACKET_LENGTH;
  34710. continue;
  34711. } // If we get here, we have somehow become de-synchronized and we need to step
  34712. // forward one byte at a time until we find a pair of sync bytes that denote
  34713. // a packet
  34714. startIndex++;
  34715. endIndex++;
  34716. } // Start walking from end of segment to get last audio packet
  34717. endIndex = bytes.byteLength;
  34718. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34719. endLoop = false;
  34720. while (startIndex >= 0) {
  34721. // Look for a pair of start and end sync bytes in the data..
  34722. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34723. // We found a packet
  34724. packet = bytes.subarray(startIndex, endIndex);
  34725. type = probe.ts.parseType(packet, pmt.pid);
  34726. switch (type) {
  34727. case 'pes':
  34728. pesType = probe.ts.parsePesType(packet, pmt.table);
  34729. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34730. if (pesType === 'audio' && pusi) {
  34731. parsed = probe.ts.parsePesTime(packet);
  34732. if (parsed) {
  34733. parsed.type = 'audio';
  34734. result.audio.push(parsed);
  34735. endLoop = true;
  34736. }
  34737. }
  34738. break;
  34739. }
  34740. if (endLoop) {
  34741. break;
  34742. }
  34743. startIndex -= MP2T_PACKET_LENGTH;
  34744. endIndex -= MP2T_PACKET_LENGTH;
  34745. continue;
  34746. } // If we get here, we have somehow become de-synchronized and we need to step
  34747. // forward one byte at a time until we find a pair of sync bytes that denote
  34748. // a packet
  34749. startIndex--;
  34750. endIndex--;
  34751. }
  34752. };
  34753. /**
  34754. * walks through the segment data from the start and end to get timing information
  34755. * for the first and last video pes packets as well as timing information for the first
  34756. * key frame.
  34757. */
  34758. var parseVideoPes_ = function (bytes, pmt, result) {
  34759. var startIndex = 0,
  34760. endIndex = MP2T_PACKET_LENGTH,
  34761. packet,
  34762. type,
  34763. pesType,
  34764. pusi,
  34765. parsed,
  34766. frame,
  34767. i,
  34768. pes;
  34769. var endLoop = false;
  34770. var currentFrame = {
  34771. data: [],
  34772. size: 0
  34773. }; // Start walking from start of segment to get first video packet
  34774. while (endIndex < bytes.byteLength) {
  34775. // Look for a pair of start and end sync bytes in the data..
  34776. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34777. // We found a packet
  34778. packet = bytes.subarray(startIndex, endIndex);
  34779. type = probe.ts.parseType(packet, pmt.pid);
  34780. switch (type) {
  34781. case 'pes':
  34782. pesType = probe.ts.parsePesType(packet, pmt.table);
  34783. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34784. if (pesType === 'video') {
  34785. if (pusi && !endLoop) {
  34786. parsed = probe.ts.parsePesTime(packet);
  34787. if (parsed) {
  34788. parsed.type = 'video';
  34789. result.video.push(parsed);
  34790. endLoop = true;
  34791. }
  34792. }
  34793. if (!result.firstKeyFrame) {
  34794. if (pusi) {
  34795. if (currentFrame.size !== 0) {
  34796. frame = new Uint8Array(currentFrame.size);
  34797. i = 0;
  34798. while (currentFrame.data.length) {
  34799. pes = currentFrame.data.shift();
  34800. frame.set(pes, i);
  34801. i += pes.byteLength;
  34802. }
  34803. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  34804. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  34805. // the keyframe seems to work fine with HLS playback
  34806. // and definitely preferable to a crash with TypeError...
  34807. if (firstKeyFrame) {
  34808. result.firstKeyFrame = firstKeyFrame;
  34809. result.firstKeyFrame.type = 'video';
  34810. } else {
  34811. // eslint-disable-next-line
  34812. console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
  34813. }
  34814. }
  34815. currentFrame.size = 0;
  34816. }
  34817. }
  34818. currentFrame.data.push(packet);
  34819. currentFrame.size += packet.byteLength;
  34820. }
  34821. }
  34822. break;
  34823. }
  34824. if (endLoop && result.firstKeyFrame) {
  34825. break;
  34826. }
  34827. startIndex += MP2T_PACKET_LENGTH;
  34828. endIndex += MP2T_PACKET_LENGTH;
  34829. continue;
  34830. } // If we get here, we have somehow become de-synchronized and we need to step
  34831. // forward one byte at a time until we find a pair of sync bytes that denote
  34832. // a packet
  34833. startIndex++;
  34834. endIndex++;
  34835. } // Start walking from end of segment to get last video packet
  34836. endIndex = bytes.byteLength;
  34837. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34838. endLoop = false;
  34839. while (startIndex >= 0) {
  34840. // Look for a pair of start and end sync bytes in the data..
  34841. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34842. // We found a packet
  34843. packet = bytes.subarray(startIndex, endIndex);
  34844. type = probe.ts.parseType(packet, pmt.pid);
  34845. switch (type) {
  34846. case 'pes':
  34847. pesType = probe.ts.parsePesType(packet, pmt.table);
  34848. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34849. if (pesType === 'video' && pusi) {
  34850. parsed = probe.ts.parsePesTime(packet);
  34851. if (parsed) {
  34852. parsed.type = 'video';
  34853. result.video.push(parsed);
  34854. endLoop = true;
  34855. }
  34856. }
  34857. break;
  34858. }
  34859. if (endLoop) {
  34860. break;
  34861. }
  34862. startIndex -= MP2T_PACKET_LENGTH;
  34863. endIndex -= MP2T_PACKET_LENGTH;
  34864. continue;
  34865. } // If we get here, we have somehow become de-synchronized and we need to step
  34866. // forward one byte at a time until we find a pair of sync bytes that denote
  34867. // a packet
  34868. startIndex--;
  34869. endIndex--;
  34870. }
  34871. };
  34872. /**
  34873. * Adjusts the timestamp information for the segment to account for
  34874. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  34875. */
  34876. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  34877. if (segmentInfo.audio && segmentInfo.audio.length) {
  34878. var audioBaseTimestamp = baseTimestamp;
  34879. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  34880. audioBaseTimestamp = segmentInfo.audio[0].dts;
  34881. }
  34882. segmentInfo.audio.forEach(function (info) {
  34883. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  34884. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  34885. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34886. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34887. });
  34888. }
  34889. if (segmentInfo.video && segmentInfo.video.length) {
  34890. var videoBaseTimestamp = baseTimestamp;
  34891. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  34892. videoBaseTimestamp = segmentInfo.video[0].dts;
  34893. }
  34894. segmentInfo.video.forEach(function (info) {
  34895. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  34896. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  34897. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34898. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34899. });
  34900. if (segmentInfo.firstKeyFrame) {
  34901. var frame = segmentInfo.firstKeyFrame;
  34902. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  34903. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  34904. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  34905. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  34906. }
  34907. }
  34908. };
  34909. /**
  34910. * inspects the aac data stream for start and end time information
  34911. */
  34912. var inspectAac_ = function (bytes) {
  34913. var endLoop = false,
  34914. audioCount = 0,
  34915. sampleRate = null,
  34916. timestamp = null,
  34917. frameSize = 0,
  34918. byteIndex = 0,
  34919. packet;
  34920. while (bytes.length - byteIndex >= 3) {
  34921. var type = probe.aac.parseType(bytes, byteIndex);
  34922. switch (type) {
  34923. case 'timed-metadata':
  34924. // Exit early because we don't have enough to parse
  34925. // the ID3 tag header
  34926. if (bytes.length - byteIndex < 10) {
  34927. endLoop = true;
  34928. break;
  34929. }
  34930. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34931. // to emit a full packet
  34932. if (frameSize > bytes.length) {
  34933. endLoop = true;
  34934. break;
  34935. }
  34936. if (timestamp === null) {
  34937. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34938. timestamp = probe.aac.parseAacTimestamp(packet);
  34939. }
  34940. byteIndex += frameSize;
  34941. break;
  34942. case 'audio':
  34943. // Exit early because we don't have enough to parse
  34944. // the ADTS frame header
  34945. if (bytes.length - byteIndex < 7) {
  34946. endLoop = true;
  34947. break;
  34948. }
  34949. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34950. // to emit a full packet
  34951. if (frameSize > bytes.length) {
  34952. endLoop = true;
  34953. break;
  34954. }
  34955. if (sampleRate === null) {
  34956. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34957. sampleRate = probe.aac.parseSampleRate(packet);
  34958. }
  34959. audioCount++;
  34960. byteIndex += frameSize;
  34961. break;
  34962. default:
  34963. byteIndex++;
  34964. break;
  34965. }
  34966. if (endLoop) {
  34967. return null;
  34968. }
  34969. }
  34970. if (sampleRate === null || timestamp === null) {
  34971. return null;
  34972. }
  34973. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  34974. var result = {
  34975. audio: [{
  34976. type: 'audio',
  34977. dts: timestamp,
  34978. pts: timestamp
  34979. }, {
  34980. type: 'audio',
  34981. dts: timestamp + audioCount * 1024 * audioTimescale,
  34982. pts: timestamp + audioCount * 1024 * audioTimescale
  34983. }]
  34984. };
  34985. return result;
  34986. };
  34987. /**
  34988. * inspects the transport stream segment data for start and end time information
  34989. * of the audio and video tracks (when present) as well as the first key frame's
  34990. * start time.
  34991. */
  34992. var inspectTs_ = function (bytes) {
  34993. var pmt = {
  34994. pid: null,
  34995. table: null
  34996. };
  34997. var result = {};
  34998. parsePsi_(bytes, pmt);
  34999. for (var pid in pmt.table) {
  35000. if (pmt.table.hasOwnProperty(pid)) {
  35001. var type = pmt.table[pid];
  35002. switch (type) {
  35003. case StreamTypes.H264_STREAM_TYPE:
  35004. result.video = [];
  35005. parseVideoPes_(bytes, pmt, result);
  35006. if (result.video.length === 0) {
  35007. delete result.video;
  35008. }
  35009. break;
  35010. case StreamTypes.ADTS_STREAM_TYPE:
  35011. result.audio = [];
  35012. parseAudioPes_(bytes, pmt, result);
  35013. if (result.audio.length === 0) {
  35014. delete result.audio;
  35015. }
  35016. break;
  35017. }
  35018. }
  35019. }
  35020. return result;
  35021. };
  35022. /**
  35023. * Inspects segment byte data and returns an object with start and end timing information
  35024. *
  35025. * @param {Uint8Array} bytes The segment byte data
  35026. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  35027. * timestamps for rollover. This value must be in 90khz clock.
  35028. * @return {Object} Object containing start and end frame timing info of segment.
  35029. */
  35030. var inspect = function (bytes, baseTimestamp) {
  35031. var isAacData = probe.aac.isLikelyAacData(bytes);
  35032. var result;
  35033. if (isAacData) {
  35034. result = inspectAac_(bytes);
  35035. } else {
  35036. result = inspectTs_(bytes);
  35037. }
  35038. if (!result || !result.audio && !result.video) {
  35039. return null;
  35040. }
  35041. adjustTimestamp_(result, baseTimestamp);
  35042. return result;
  35043. };
  35044. var tsInspector = {
  35045. inspect: inspect,
  35046. parseAudioPes_: parseAudioPes_
  35047. };
  35048. /* global self */
  35049. /**
  35050. * Re-emits transmuxer events by converting them into messages to the
  35051. * world outside the worker.
  35052. *
  35053. * @param {Object} transmuxer the transmuxer to wire events on
  35054. * @private
  35055. */
  35056. const wireTransmuxerEvents = function (self, transmuxer) {
  35057. transmuxer.on('data', function (segment) {
  35058. // transfer ownership of the underlying ArrayBuffer
  35059. // instead of doing a copy to save memory
  35060. // ArrayBuffers are transferable but generic TypedArrays are not
  35061. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  35062. const initArray = segment.initSegment;
  35063. segment.initSegment = {
  35064. data: initArray.buffer,
  35065. byteOffset: initArray.byteOffset,
  35066. byteLength: initArray.byteLength
  35067. };
  35068. const typedArray = segment.data;
  35069. segment.data = typedArray.buffer;
  35070. self.postMessage({
  35071. action: 'data',
  35072. segment,
  35073. byteOffset: typedArray.byteOffset,
  35074. byteLength: typedArray.byteLength
  35075. }, [segment.data]);
  35076. });
  35077. transmuxer.on('done', function (data) {
  35078. self.postMessage({
  35079. action: 'done'
  35080. });
  35081. });
  35082. transmuxer.on('gopInfo', function (gopInfo) {
  35083. self.postMessage({
  35084. action: 'gopInfo',
  35085. gopInfo
  35086. });
  35087. });
  35088. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  35089. const videoSegmentTimingInfo = {
  35090. start: {
  35091. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  35092. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  35093. },
  35094. end: {
  35095. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  35096. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  35097. },
  35098. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  35099. };
  35100. if (timingInfo.prependedContentDuration) {
  35101. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  35102. }
  35103. self.postMessage({
  35104. action: 'videoSegmentTimingInfo',
  35105. videoSegmentTimingInfo
  35106. });
  35107. });
  35108. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  35109. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  35110. const audioSegmentTimingInfo = {
  35111. start: {
  35112. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  35113. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  35114. },
  35115. end: {
  35116. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  35117. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  35118. },
  35119. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  35120. };
  35121. if (timingInfo.prependedContentDuration) {
  35122. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  35123. }
  35124. self.postMessage({
  35125. action: 'audioSegmentTimingInfo',
  35126. audioSegmentTimingInfo
  35127. });
  35128. });
  35129. transmuxer.on('id3Frame', function (id3Frame) {
  35130. self.postMessage({
  35131. action: 'id3Frame',
  35132. id3Frame
  35133. });
  35134. });
  35135. transmuxer.on('caption', function (caption) {
  35136. self.postMessage({
  35137. action: 'caption',
  35138. caption
  35139. });
  35140. });
  35141. transmuxer.on('trackinfo', function (trackInfo) {
  35142. self.postMessage({
  35143. action: 'trackinfo',
  35144. trackInfo
  35145. });
  35146. });
  35147. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  35148. // convert to video TS since we prioritize video time over audio
  35149. self.postMessage({
  35150. action: 'audioTimingInfo',
  35151. audioTimingInfo: {
  35152. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  35153. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  35154. }
  35155. });
  35156. });
  35157. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  35158. self.postMessage({
  35159. action: 'videoTimingInfo',
  35160. videoTimingInfo: {
  35161. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  35162. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  35163. }
  35164. });
  35165. });
  35166. transmuxer.on('log', function (log) {
  35167. self.postMessage({
  35168. action: 'log',
  35169. log
  35170. });
  35171. });
  35172. };
  35173. /**
  35174. * All incoming messages route through this hash. If no function exists
  35175. * to handle an incoming message, then we ignore the message.
  35176. *
  35177. * @class MessageHandlers
  35178. * @param {Object} options the options to initialize with
  35179. */
  35180. class MessageHandlers {
  35181. constructor(self, options) {
  35182. this.options = options || {};
  35183. this.self = self;
  35184. this.init();
  35185. }
  35186. /**
  35187. * initialize our web worker and wire all the events.
  35188. */
  35189. init() {
  35190. if (this.transmuxer) {
  35191. this.transmuxer.dispose();
  35192. }
  35193. this.transmuxer = new transmuxer.Transmuxer(this.options);
  35194. wireTransmuxerEvents(this.self, this.transmuxer);
  35195. }
  35196. pushMp4Captions(data) {
  35197. if (!this.captionParser) {
  35198. this.captionParser = new captionParser();
  35199. this.captionParser.init();
  35200. }
  35201. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  35202. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  35203. this.self.postMessage({
  35204. action: 'mp4Captions',
  35205. captions: parsed && parsed.captions || [],
  35206. logs: parsed && parsed.logs || [],
  35207. data: segment.buffer
  35208. }, [segment.buffer]);
  35209. }
  35210. probeMp4StartTime({
  35211. timescales,
  35212. data
  35213. }) {
  35214. const startTime = probe$2.startTime(timescales, data);
  35215. this.self.postMessage({
  35216. action: 'probeMp4StartTime',
  35217. startTime,
  35218. data
  35219. }, [data.buffer]);
  35220. }
  35221. probeMp4Tracks({
  35222. data
  35223. }) {
  35224. const tracks = probe$2.tracks(data);
  35225. this.self.postMessage({
  35226. action: 'probeMp4Tracks',
  35227. tracks,
  35228. data
  35229. }, [data.buffer]);
  35230. }
  35231. /**
  35232. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  35233. * internal "media time," as well as whether it contains video and/or audio.
  35234. *
  35235. * @private
  35236. * @param {Uint8Array} bytes - segment bytes
  35237. * @param {number} baseStartTime
  35238. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  35239. * This value should be in seconds, as it's converted to a 90khz clock within the
  35240. * function body.
  35241. * @return {Object} The start time of the current segment in "media time" as well as
  35242. * whether it contains video and/or audio
  35243. */
  35244. probeTs({
  35245. data,
  35246. baseStartTime
  35247. }) {
  35248. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  35249. const timeInfo = tsInspector.inspect(data, tsStartTime);
  35250. let result = null;
  35251. if (timeInfo) {
  35252. result = {
  35253. // each type's time info comes back as an array of 2 times, start and end
  35254. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  35255. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  35256. };
  35257. if (result.hasVideo) {
  35258. result.videoStart = timeInfo.video[0].ptsTime;
  35259. }
  35260. if (result.hasAudio) {
  35261. result.audioStart = timeInfo.audio[0].ptsTime;
  35262. }
  35263. }
  35264. this.self.postMessage({
  35265. action: 'probeTs',
  35266. result,
  35267. data
  35268. }, [data.buffer]);
  35269. }
  35270. clearAllMp4Captions() {
  35271. if (this.captionParser) {
  35272. this.captionParser.clearAllCaptions();
  35273. }
  35274. }
  35275. clearParsedMp4Captions() {
  35276. if (this.captionParser) {
  35277. this.captionParser.clearParsedCaptions();
  35278. }
  35279. }
  35280. /**
  35281. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  35282. * processing.
  35283. *
  35284. * @param {ArrayBuffer} data data to push into the muxer
  35285. */
  35286. push(data) {
  35287. // Cast array buffer to correct type for transmuxer
  35288. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  35289. this.transmuxer.push(segment);
  35290. }
  35291. /**
  35292. * Recreate the transmuxer so that the next segment added via `push`
  35293. * start with a fresh transmuxer.
  35294. */
  35295. reset() {
  35296. this.transmuxer.reset();
  35297. }
  35298. /**
  35299. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  35300. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  35301. * set relative to the first based on the PTS values.
  35302. *
  35303. * @param {Object} data used to set the timestamp offset in the muxer
  35304. */
  35305. setTimestampOffset(data) {
  35306. const timestampOffset = data.timestampOffset || 0;
  35307. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  35308. }
  35309. setAudioAppendStart(data) {
  35310. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  35311. }
  35312. setRemux(data) {
  35313. this.transmuxer.setRemux(data.remux);
  35314. }
  35315. /**
  35316. * Forces the pipeline to finish processing the last segment and emit it's
  35317. * results.
  35318. *
  35319. * @param {Object} data event data, not really used
  35320. */
  35321. flush(data) {
  35322. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  35323. self.postMessage({
  35324. action: 'done',
  35325. type: 'transmuxed'
  35326. });
  35327. }
  35328. endTimeline() {
  35329. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  35330. // timelines
  35331. self.postMessage({
  35332. action: 'endedtimeline',
  35333. type: 'transmuxed'
  35334. });
  35335. }
  35336. alignGopsWith(data) {
  35337. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  35338. }
  35339. }
  35340. /**
  35341. * Our web worker interface so that things can talk to mux.js
  35342. * that will be running in a web worker. the scope is passed to this by
  35343. * webworkify.
  35344. *
  35345. * @param {Object} self the scope for the web worker
  35346. */
  35347. self.onmessage = function (event) {
  35348. if (event.data.action === 'init' && event.data.options) {
  35349. this.messageHandlers = new MessageHandlers(self, event.data.options);
  35350. return;
  35351. }
  35352. if (!this.messageHandlers) {
  35353. this.messageHandlers = new MessageHandlers(self);
  35354. }
  35355. if (event.data && event.data.action && event.data.action !== 'init') {
  35356. if (this.messageHandlers[event.data.action]) {
  35357. this.messageHandlers[event.data.action](event.data);
  35358. }
  35359. }
  35360. };
  35361. }));
  35362. var TransmuxWorker = factory(workerCode$1);
  35363. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  35364. const handleData_ = (event, transmuxedData, callback) => {
  35365. const {
  35366. type,
  35367. initSegment,
  35368. captions,
  35369. captionStreams,
  35370. metadata,
  35371. videoFrameDtsTime,
  35372. videoFramePtsTime
  35373. } = event.data.segment;
  35374. transmuxedData.buffer.push({
  35375. captions,
  35376. captionStreams,
  35377. metadata
  35378. });
  35379. const boxes = event.data.segment.boxes || {
  35380. data: event.data.segment.data
  35381. };
  35382. const result = {
  35383. type,
  35384. // cast ArrayBuffer to TypedArray
  35385. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  35386. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  35387. };
  35388. if (typeof videoFrameDtsTime !== 'undefined') {
  35389. result.videoFrameDtsTime = videoFrameDtsTime;
  35390. }
  35391. if (typeof videoFramePtsTime !== 'undefined') {
  35392. result.videoFramePtsTime = videoFramePtsTime;
  35393. }
  35394. callback(result);
  35395. };
  35396. const handleDone_ = ({
  35397. transmuxedData,
  35398. callback
  35399. }) => {
  35400. // Previously we only returned data on data events,
  35401. // not on done events. Clear out the buffer to keep that consistent.
  35402. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  35403. // have received
  35404. callback(transmuxedData);
  35405. };
  35406. const handleGopInfo_ = (event, transmuxedData) => {
  35407. transmuxedData.gopInfo = event.data.gopInfo;
  35408. };
  35409. const processTransmux = options => {
  35410. const {
  35411. transmuxer,
  35412. bytes,
  35413. audioAppendStart,
  35414. gopsToAlignWith,
  35415. remux,
  35416. onData,
  35417. onTrackInfo,
  35418. onAudioTimingInfo,
  35419. onVideoTimingInfo,
  35420. onVideoSegmentTimingInfo,
  35421. onAudioSegmentTimingInfo,
  35422. onId3,
  35423. onCaptions,
  35424. onDone,
  35425. onEndedTimeline,
  35426. onTransmuxerLog,
  35427. isEndOfTimeline
  35428. } = options;
  35429. const transmuxedData = {
  35430. buffer: []
  35431. };
  35432. let waitForEndedTimelineEvent = isEndOfTimeline;
  35433. const handleMessage = event => {
  35434. if (transmuxer.currentTransmux !== options) {
  35435. // disposed
  35436. return;
  35437. }
  35438. if (event.data.action === 'data') {
  35439. handleData_(event, transmuxedData, onData);
  35440. }
  35441. if (event.data.action === 'trackinfo') {
  35442. onTrackInfo(event.data.trackInfo);
  35443. }
  35444. if (event.data.action === 'gopInfo') {
  35445. handleGopInfo_(event, transmuxedData);
  35446. }
  35447. if (event.data.action === 'audioTimingInfo') {
  35448. onAudioTimingInfo(event.data.audioTimingInfo);
  35449. }
  35450. if (event.data.action === 'videoTimingInfo') {
  35451. onVideoTimingInfo(event.data.videoTimingInfo);
  35452. }
  35453. if (event.data.action === 'videoSegmentTimingInfo') {
  35454. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  35455. }
  35456. if (event.data.action === 'audioSegmentTimingInfo') {
  35457. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  35458. }
  35459. if (event.data.action === 'id3Frame') {
  35460. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  35461. }
  35462. if (event.data.action === 'caption') {
  35463. onCaptions(event.data.caption);
  35464. }
  35465. if (event.data.action === 'endedtimeline') {
  35466. waitForEndedTimelineEvent = false;
  35467. onEndedTimeline();
  35468. }
  35469. if (event.data.action === 'log') {
  35470. onTransmuxerLog(event.data.log);
  35471. } // wait for the transmuxed event since we may have audio and video
  35472. if (event.data.type !== 'transmuxed') {
  35473. return;
  35474. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  35475. // of a timeline, that means there may still be data events before the segment
  35476. // processing can be considerred complete. In that case, the final event should be
  35477. // an "endedtimeline" event with the type "transmuxed."
  35478. if (waitForEndedTimelineEvent) {
  35479. return;
  35480. }
  35481. transmuxer.onmessage = null;
  35482. handleDone_({
  35483. transmuxedData,
  35484. callback: onDone
  35485. });
  35486. /* eslint-disable no-use-before-define */
  35487. dequeue(transmuxer);
  35488. /* eslint-enable */
  35489. };
  35490. transmuxer.onmessage = handleMessage;
  35491. if (audioAppendStart) {
  35492. transmuxer.postMessage({
  35493. action: 'setAudioAppendStart',
  35494. appendStart: audioAppendStart
  35495. });
  35496. } // allow empty arrays to be passed to clear out GOPs
  35497. if (Array.isArray(gopsToAlignWith)) {
  35498. transmuxer.postMessage({
  35499. action: 'alignGopsWith',
  35500. gopsToAlignWith
  35501. });
  35502. }
  35503. if (typeof remux !== 'undefined') {
  35504. transmuxer.postMessage({
  35505. action: 'setRemux',
  35506. remux
  35507. });
  35508. }
  35509. if (bytes.byteLength) {
  35510. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  35511. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  35512. transmuxer.postMessage({
  35513. action: 'push',
  35514. // Send the typed-array of data as an ArrayBuffer so that
  35515. // it can be sent as a "Transferable" and avoid the costly
  35516. // memory copy
  35517. data: buffer,
  35518. // To recreate the original typed-array, we need information
  35519. // about what portion of the ArrayBuffer it was a view into
  35520. byteOffset,
  35521. byteLength: bytes.byteLength
  35522. }, [buffer]);
  35523. }
  35524. if (isEndOfTimeline) {
  35525. transmuxer.postMessage({
  35526. action: 'endTimeline'
  35527. });
  35528. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  35529. // the end of the segment
  35530. transmuxer.postMessage({
  35531. action: 'flush'
  35532. });
  35533. };
  35534. const dequeue = transmuxer => {
  35535. transmuxer.currentTransmux = null;
  35536. if (transmuxer.transmuxQueue.length) {
  35537. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  35538. if (typeof transmuxer.currentTransmux === 'function') {
  35539. transmuxer.currentTransmux();
  35540. } else {
  35541. processTransmux(transmuxer.currentTransmux);
  35542. }
  35543. }
  35544. };
  35545. const processAction = (transmuxer, action) => {
  35546. transmuxer.postMessage({
  35547. action
  35548. });
  35549. dequeue(transmuxer);
  35550. };
  35551. const enqueueAction = (action, transmuxer) => {
  35552. if (!transmuxer.currentTransmux) {
  35553. transmuxer.currentTransmux = action;
  35554. processAction(transmuxer, action);
  35555. return;
  35556. }
  35557. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  35558. };
  35559. const reset = transmuxer => {
  35560. enqueueAction('reset', transmuxer);
  35561. };
  35562. const endTimeline = transmuxer => {
  35563. enqueueAction('endTimeline', transmuxer);
  35564. };
  35565. const transmux = options => {
  35566. if (!options.transmuxer.currentTransmux) {
  35567. options.transmuxer.currentTransmux = options;
  35568. processTransmux(options);
  35569. return;
  35570. }
  35571. options.transmuxer.transmuxQueue.push(options);
  35572. };
  35573. const createTransmuxer = options => {
  35574. const transmuxer = new TransmuxWorker();
  35575. transmuxer.currentTransmux = null;
  35576. transmuxer.transmuxQueue = [];
  35577. const term = transmuxer.terminate;
  35578. transmuxer.terminate = () => {
  35579. transmuxer.currentTransmux = null;
  35580. transmuxer.transmuxQueue.length = 0;
  35581. return term.call(transmuxer);
  35582. };
  35583. transmuxer.postMessage({
  35584. action: 'init',
  35585. options
  35586. });
  35587. return transmuxer;
  35588. };
  35589. var segmentTransmuxer = {
  35590. reset,
  35591. endTimeline,
  35592. transmux,
  35593. createTransmuxer
  35594. };
  35595. const workerCallback = function (options) {
  35596. const transmuxer = options.transmuxer;
  35597. const endAction = options.endAction || options.action;
  35598. const callback = options.callback;
  35599. const message = _extends__default["default"]({}, options, {
  35600. endAction: null,
  35601. transmuxer: null,
  35602. callback: null
  35603. });
  35604. const listenForEndEvent = event => {
  35605. if (event.data.action !== endAction) {
  35606. return;
  35607. }
  35608. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  35609. if (event.data.data) {
  35610. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  35611. if (options.data) {
  35612. options.data = event.data.data;
  35613. }
  35614. }
  35615. callback(event.data);
  35616. };
  35617. transmuxer.addEventListener('message', listenForEndEvent);
  35618. if (options.data) {
  35619. const isArrayBuffer = options.data instanceof ArrayBuffer;
  35620. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  35621. message.byteLength = options.data.byteLength;
  35622. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  35623. transmuxer.postMessage(message, transfers);
  35624. } else {
  35625. transmuxer.postMessage(message);
  35626. }
  35627. };
  35628. const REQUEST_ERRORS = {
  35629. FAILURE: 2,
  35630. TIMEOUT: -101,
  35631. ABORTED: -102
  35632. };
  35633. /**
  35634. * Abort all requests
  35635. *
  35636. * @param {Object} activeXhrs - an object that tracks all XHR requests
  35637. */
  35638. const abortAll = activeXhrs => {
  35639. activeXhrs.forEach(xhr => {
  35640. xhr.abort();
  35641. });
  35642. };
  35643. /**
  35644. * Gather important bandwidth stats once a request has completed
  35645. *
  35646. * @param {Object} request - the XHR request from which to gather stats
  35647. */
  35648. const getRequestStats = request => {
  35649. return {
  35650. bandwidth: request.bandwidth,
  35651. bytesReceived: request.bytesReceived || 0,
  35652. roundTripTime: request.roundTripTime || 0
  35653. };
  35654. };
  35655. /**
  35656. * If possible gather bandwidth stats as a request is in
  35657. * progress
  35658. *
  35659. * @param {Event} progressEvent - an event object from an XHR's progress event
  35660. */
  35661. const getProgressStats = progressEvent => {
  35662. const request = progressEvent.target;
  35663. const roundTripTime = Date.now() - request.requestTime;
  35664. const stats = {
  35665. bandwidth: Infinity,
  35666. bytesReceived: 0,
  35667. roundTripTime: roundTripTime || 0
  35668. };
  35669. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  35670. // because we should only use bandwidth stats on progress to determine when
  35671. // abort a request early due to insufficient bandwidth
  35672. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  35673. return stats;
  35674. };
  35675. /**
  35676. * Handle all error conditions in one place and return an object
  35677. * with all the information
  35678. *
  35679. * @param {Error|null} error - if non-null signals an error occured with the XHR
  35680. * @param {Object} request - the XHR request that possibly generated the error
  35681. */
  35682. const handleErrors = (error, request) => {
  35683. if (request.timedout) {
  35684. return {
  35685. status: request.status,
  35686. message: 'HLS request timed-out at URL: ' + request.uri,
  35687. code: REQUEST_ERRORS.TIMEOUT,
  35688. xhr: request
  35689. };
  35690. }
  35691. if (request.aborted) {
  35692. return {
  35693. status: request.status,
  35694. message: 'HLS request aborted at URL: ' + request.uri,
  35695. code: REQUEST_ERRORS.ABORTED,
  35696. xhr: request
  35697. };
  35698. }
  35699. if (error) {
  35700. return {
  35701. status: request.status,
  35702. message: 'HLS request errored at URL: ' + request.uri,
  35703. code: REQUEST_ERRORS.FAILURE,
  35704. xhr: request
  35705. };
  35706. }
  35707. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  35708. return {
  35709. status: request.status,
  35710. message: 'Empty HLS response at URL: ' + request.uri,
  35711. code: REQUEST_ERRORS.FAILURE,
  35712. xhr: request
  35713. };
  35714. }
  35715. return null;
  35716. };
  35717. /**
  35718. * Handle responses for key data and convert the key data to the correct format
  35719. * for the decryption step later
  35720. *
  35721. * @param {Object} segment - a simplified copy of the segmentInfo object
  35722. * from SegmentLoader
  35723. * @param {Array} objects - objects to add the key bytes to.
  35724. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35725. * this request
  35726. */
  35727. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  35728. const response = request.response;
  35729. const errorObj = handleErrors(error, request);
  35730. if (errorObj) {
  35731. return finishProcessingFn(errorObj, segment);
  35732. }
  35733. if (response.byteLength !== 16) {
  35734. return finishProcessingFn({
  35735. status: request.status,
  35736. message: 'Invalid HLS key at URL: ' + request.uri,
  35737. code: REQUEST_ERRORS.FAILURE,
  35738. xhr: request
  35739. }, segment);
  35740. }
  35741. const view = new DataView(response);
  35742. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  35743. for (let i = 0; i < objects.length; i++) {
  35744. objects[i].bytes = bytes;
  35745. }
  35746. return finishProcessingFn(null, segment);
  35747. };
  35748. const parseInitSegment = (segment, callback) => {
  35749. const type = containers.detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  35750. // only know how to parse mp4 init segments at the moment
  35751. if (type !== 'mp4') {
  35752. const uri = segment.map.resolvedUri || segment.map.uri;
  35753. return callback({
  35754. internal: true,
  35755. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  35756. code: REQUEST_ERRORS.FAILURE
  35757. });
  35758. }
  35759. workerCallback({
  35760. action: 'probeMp4Tracks',
  35761. data: segment.map.bytes,
  35762. transmuxer: segment.transmuxer,
  35763. callback: ({
  35764. tracks,
  35765. data
  35766. }) => {
  35767. // transfer bytes back to us
  35768. segment.map.bytes = data;
  35769. tracks.forEach(function (track) {
  35770. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  35771. if (segment.map.tracks[track.type]) {
  35772. return;
  35773. }
  35774. segment.map.tracks[track.type] = track;
  35775. if (typeof track.id === 'number' && track.timescale) {
  35776. segment.map.timescales = segment.map.timescales || {};
  35777. segment.map.timescales[track.id] = track.timescale;
  35778. }
  35779. });
  35780. return callback(null);
  35781. }
  35782. });
  35783. };
  35784. /**
  35785. * Handle init-segment responses
  35786. *
  35787. * @param {Object} segment - a simplified copy of the segmentInfo object
  35788. * from SegmentLoader
  35789. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35790. * this request
  35791. */
  35792. const handleInitSegmentResponse = ({
  35793. segment,
  35794. finishProcessingFn
  35795. }) => (error, request) => {
  35796. const errorObj = handleErrors(error, request);
  35797. if (errorObj) {
  35798. return finishProcessingFn(errorObj, segment);
  35799. }
  35800. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  35801. // until the key request is done to decrypt.
  35802. if (segment.map.key) {
  35803. segment.map.encryptedBytes = bytes;
  35804. return finishProcessingFn(null, segment);
  35805. }
  35806. segment.map.bytes = bytes;
  35807. parseInitSegment(segment, function (parseError) {
  35808. if (parseError) {
  35809. parseError.xhr = request;
  35810. parseError.status = request.status;
  35811. return finishProcessingFn(parseError, segment);
  35812. }
  35813. finishProcessingFn(null, segment);
  35814. });
  35815. };
  35816. /**
  35817. * Response handler for segment-requests being sure to set the correct
  35818. * property depending on whether the segment is encryped or not
  35819. * Also records and keeps track of stats that are used for ABR purposes
  35820. *
  35821. * @param {Object} segment - a simplified copy of the segmentInfo object
  35822. * from SegmentLoader
  35823. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35824. * this request
  35825. */
  35826. const handleSegmentResponse = ({
  35827. segment,
  35828. finishProcessingFn,
  35829. responseType
  35830. }) => (error, request) => {
  35831. const errorObj = handleErrors(error, request);
  35832. if (errorObj) {
  35833. return finishProcessingFn(errorObj, segment);
  35834. }
  35835. const newBytes =
  35836. // although responseText "should" exist, this guard serves to prevent an error being
  35837. // thrown for two primary cases:
  35838. // 1. the mime type override stops working, or is not implemented for a specific
  35839. // browser
  35840. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  35841. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  35842. segment.stats = getRequestStats(request);
  35843. if (segment.key) {
  35844. segment.encryptedBytes = new Uint8Array(newBytes);
  35845. } else {
  35846. segment.bytes = new Uint8Array(newBytes);
  35847. }
  35848. return finishProcessingFn(null, segment);
  35849. };
  35850. const transmuxAndNotify = ({
  35851. segment,
  35852. bytes,
  35853. trackInfoFn,
  35854. timingInfoFn,
  35855. videoSegmentTimingInfoFn,
  35856. audioSegmentTimingInfoFn,
  35857. id3Fn,
  35858. captionsFn,
  35859. isEndOfTimeline,
  35860. endedTimelineFn,
  35861. dataFn,
  35862. doneFn,
  35863. onTransmuxerLog
  35864. }) => {
  35865. const fmp4Tracks = segment.map && segment.map.tracks || {};
  35866. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  35867. // One reason for this is that in the case of full segments, we want to trust start
  35868. // times from the probe, rather than the transmuxer.
  35869. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  35870. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  35871. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  35872. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  35873. const finish = () => transmux({
  35874. bytes,
  35875. transmuxer: segment.transmuxer,
  35876. audioAppendStart: segment.audioAppendStart,
  35877. gopsToAlignWith: segment.gopsToAlignWith,
  35878. remux: isMuxed,
  35879. onData: result => {
  35880. result.type = result.type === 'combined' ? 'video' : result.type;
  35881. dataFn(segment, result);
  35882. },
  35883. onTrackInfo: trackInfo => {
  35884. if (trackInfoFn) {
  35885. if (isMuxed) {
  35886. trackInfo.isMuxed = true;
  35887. }
  35888. trackInfoFn(segment, trackInfo);
  35889. }
  35890. },
  35891. onAudioTimingInfo: audioTimingInfo => {
  35892. // we only want the first start value we encounter
  35893. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  35894. audioStartFn(audioTimingInfo.start);
  35895. audioStartFn = null;
  35896. } // we want to continually update the end time
  35897. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  35898. audioEndFn(audioTimingInfo.end);
  35899. }
  35900. },
  35901. onVideoTimingInfo: videoTimingInfo => {
  35902. // we only want the first start value we encounter
  35903. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  35904. videoStartFn(videoTimingInfo.start);
  35905. videoStartFn = null;
  35906. } // we want to continually update the end time
  35907. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  35908. videoEndFn(videoTimingInfo.end);
  35909. }
  35910. },
  35911. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  35912. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  35913. },
  35914. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  35915. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  35916. },
  35917. onId3: (id3Frames, dispatchType) => {
  35918. id3Fn(segment, id3Frames, dispatchType);
  35919. },
  35920. onCaptions: captions => {
  35921. captionsFn(segment, [captions]);
  35922. },
  35923. isEndOfTimeline,
  35924. onEndedTimeline: () => {
  35925. endedTimelineFn();
  35926. },
  35927. onTransmuxerLog,
  35928. onDone: result => {
  35929. if (!doneFn) {
  35930. return;
  35931. }
  35932. result.type = result.type === 'combined' ? 'video' : result.type;
  35933. doneFn(null, segment, result);
  35934. }
  35935. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  35936. // Meaning cached frame data may corrupt our notion of where this segment
  35937. // really starts. To get around this, probe for the info needed.
  35938. workerCallback({
  35939. action: 'probeTs',
  35940. transmuxer: segment.transmuxer,
  35941. data: bytes,
  35942. baseStartTime: segment.baseStartTime,
  35943. callback: data => {
  35944. segment.bytes = bytes = data.data;
  35945. const probeResult = data.result;
  35946. if (probeResult) {
  35947. trackInfoFn(segment, {
  35948. hasAudio: probeResult.hasAudio,
  35949. hasVideo: probeResult.hasVideo,
  35950. isMuxed
  35951. });
  35952. trackInfoFn = null;
  35953. if (probeResult.hasAudio && !isMuxed) {
  35954. audioStartFn(probeResult.audioStart);
  35955. }
  35956. if (probeResult.hasVideo) {
  35957. videoStartFn(probeResult.videoStart);
  35958. }
  35959. audioStartFn = null;
  35960. videoStartFn = null;
  35961. }
  35962. finish();
  35963. }
  35964. });
  35965. };
  35966. const handleSegmentBytes = ({
  35967. segment,
  35968. bytes,
  35969. trackInfoFn,
  35970. timingInfoFn,
  35971. videoSegmentTimingInfoFn,
  35972. audioSegmentTimingInfoFn,
  35973. id3Fn,
  35974. captionsFn,
  35975. isEndOfTimeline,
  35976. endedTimelineFn,
  35977. dataFn,
  35978. doneFn,
  35979. onTransmuxerLog
  35980. }) => {
  35981. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  35982. // We should have a handler that fetches the number of bytes required
  35983. // to check if something is fmp4. This will allow us to save bandwidth
  35984. // because we can only exclude a playlist and abort requests
  35985. // by codec after trackinfo triggers.
  35986. if (containers.isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  35987. segment.isFmp4 = true;
  35988. const {
  35989. tracks
  35990. } = segment.map;
  35991. const trackInfo = {
  35992. isFmp4: true,
  35993. hasVideo: !!tracks.video,
  35994. hasAudio: !!tracks.audio
  35995. }; // if we have a audio track, with a codec that is not set to
  35996. // encrypted audio
  35997. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  35998. trackInfo.audioCodec = tracks.audio.codec;
  35999. } // if we have a video track, with a codec that is not set to
  36000. // encrypted video
  36001. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  36002. trackInfo.videoCodec = tracks.video.codec;
  36003. }
  36004. if (tracks.video && tracks.audio) {
  36005. trackInfo.isMuxed = true;
  36006. } // since we don't support appending fmp4 data on progress, we know we have the full
  36007. // segment here
  36008. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  36009. // time. The end time can be roughly calculated by the receiver using the duration.
  36010. //
  36011. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  36012. // that is the true start of the segment (where the playback engine should begin
  36013. // decoding).
  36014. const finishLoading = captions => {
  36015. // if the track still has audio at this point it is only possible
  36016. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  36017. // above.
  36018. // we make sure to use segment.bytes here as that
  36019. dataFn(segment, {
  36020. data: bytesAsUint8Array,
  36021. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  36022. });
  36023. if (captions && captions.length) {
  36024. captionsFn(segment, captions);
  36025. }
  36026. doneFn(null, segment, {});
  36027. };
  36028. workerCallback({
  36029. action: 'probeMp4StartTime',
  36030. timescales: segment.map.timescales,
  36031. data: bytesAsUint8Array,
  36032. transmuxer: segment.transmuxer,
  36033. callback: ({
  36034. data,
  36035. startTime
  36036. }) => {
  36037. // transfer bytes back to us
  36038. bytes = data.buffer;
  36039. segment.bytes = bytesAsUint8Array = data;
  36040. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  36041. timingInfoFn(segment, 'audio', 'start', startTime);
  36042. }
  36043. if (trackInfo.hasVideo) {
  36044. timingInfoFn(segment, 'video', 'start', startTime);
  36045. } // Run through the CaptionParser in case there are captions.
  36046. // Initialize CaptionParser if it hasn't been yet
  36047. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  36048. finishLoading();
  36049. return;
  36050. }
  36051. workerCallback({
  36052. action: 'pushMp4Captions',
  36053. endAction: 'mp4Captions',
  36054. transmuxer: segment.transmuxer,
  36055. data: bytesAsUint8Array,
  36056. timescales: segment.map.timescales,
  36057. trackIds: [tracks.video.id],
  36058. callback: message => {
  36059. // transfer bytes back to us
  36060. bytes = message.data.buffer;
  36061. segment.bytes = bytesAsUint8Array = message.data;
  36062. message.logs.forEach(function (log) {
  36063. onTransmuxerLog(merge(log, {
  36064. stream: 'mp4CaptionParser'
  36065. }));
  36066. });
  36067. finishLoading(message.captions);
  36068. }
  36069. });
  36070. }
  36071. });
  36072. return;
  36073. } // VTT or other segments that don't need processing
  36074. if (!segment.transmuxer) {
  36075. doneFn(null, segment, {});
  36076. return;
  36077. }
  36078. if (typeof segment.container === 'undefined') {
  36079. segment.container = containers.detectContainerForBytes(bytesAsUint8Array);
  36080. }
  36081. if (segment.container !== 'ts' && segment.container !== 'aac') {
  36082. trackInfoFn(segment, {
  36083. hasAudio: false,
  36084. hasVideo: false
  36085. });
  36086. doneFn(null, segment, {});
  36087. return;
  36088. } // ts or aac
  36089. transmuxAndNotify({
  36090. segment,
  36091. bytes,
  36092. trackInfoFn,
  36093. timingInfoFn,
  36094. videoSegmentTimingInfoFn,
  36095. audioSegmentTimingInfoFn,
  36096. id3Fn,
  36097. captionsFn,
  36098. isEndOfTimeline,
  36099. endedTimelineFn,
  36100. dataFn,
  36101. doneFn,
  36102. onTransmuxerLog
  36103. });
  36104. };
  36105. const decrypt = function ({
  36106. id,
  36107. key,
  36108. encryptedBytes,
  36109. decryptionWorker
  36110. }, callback) {
  36111. const decryptionHandler = event => {
  36112. if (event.data.source === id) {
  36113. decryptionWorker.removeEventListener('message', decryptionHandler);
  36114. const decrypted = event.data.decrypted;
  36115. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  36116. }
  36117. };
  36118. decryptionWorker.addEventListener('message', decryptionHandler);
  36119. let keyBytes;
  36120. if (key.bytes.slice) {
  36121. keyBytes = key.bytes.slice();
  36122. } else {
  36123. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  36124. } // incrementally decrypt the bytes
  36125. decryptionWorker.postMessage(createTransferableMessage({
  36126. source: id,
  36127. encrypted: encryptedBytes,
  36128. key: keyBytes,
  36129. iv: key.iv
  36130. }), [encryptedBytes.buffer, keyBytes.buffer]);
  36131. };
  36132. /**
  36133. * Decrypt the segment via the decryption web worker
  36134. *
  36135. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  36136. * routines
  36137. * @param {Object} segment - a simplified copy of the segmentInfo object
  36138. * from SegmentLoader
  36139. * @param {Function} trackInfoFn - a callback that receives track info
  36140. * @param {Function} timingInfoFn - a callback that receives timing info
  36141. * @param {Function} videoSegmentTimingInfoFn
  36142. * a callback that receives video timing info based on media times and
  36143. * any adjustments made by the transmuxer
  36144. * @param {Function} audioSegmentTimingInfoFn
  36145. * a callback that receives audio timing info based on media times and
  36146. * any adjustments made by the transmuxer
  36147. * @param {boolean} isEndOfTimeline
  36148. * true if this segment represents the last segment in a timeline
  36149. * @param {Function} endedTimelineFn
  36150. * a callback made when a timeline is ended, will only be called if
  36151. * isEndOfTimeline is true
  36152. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36153. * and ready to use
  36154. * @param {Function} doneFn - a callback that is executed after decryption has completed
  36155. */
  36156. const decryptSegment = ({
  36157. decryptionWorker,
  36158. segment,
  36159. trackInfoFn,
  36160. timingInfoFn,
  36161. videoSegmentTimingInfoFn,
  36162. audioSegmentTimingInfoFn,
  36163. id3Fn,
  36164. captionsFn,
  36165. isEndOfTimeline,
  36166. endedTimelineFn,
  36167. dataFn,
  36168. doneFn,
  36169. onTransmuxerLog
  36170. }) => {
  36171. decrypt({
  36172. id: segment.requestId,
  36173. key: segment.key,
  36174. encryptedBytes: segment.encryptedBytes,
  36175. decryptionWorker
  36176. }, decryptedBytes => {
  36177. segment.bytes = decryptedBytes;
  36178. handleSegmentBytes({
  36179. segment,
  36180. bytes: segment.bytes,
  36181. trackInfoFn,
  36182. timingInfoFn,
  36183. videoSegmentTimingInfoFn,
  36184. audioSegmentTimingInfoFn,
  36185. id3Fn,
  36186. captionsFn,
  36187. isEndOfTimeline,
  36188. endedTimelineFn,
  36189. dataFn,
  36190. doneFn,
  36191. onTransmuxerLog
  36192. });
  36193. });
  36194. };
  36195. /**
  36196. * This function waits for all XHRs to finish (with either success or failure)
  36197. * before continueing processing via it's callback. The function gathers errors
  36198. * from each request into a single errors array so that the error status for
  36199. * each request can be examined later.
  36200. *
  36201. * @param {Object} activeXhrs - an object that tracks all XHR requests
  36202. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  36203. * routines
  36204. * @param {Function} trackInfoFn - a callback that receives track info
  36205. * @param {Function} timingInfoFn - a callback that receives timing info
  36206. * @param {Function} videoSegmentTimingInfoFn
  36207. * a callback that receives video timing info based on media times and
  36208. * any adjustments made by the transmuxer
  36209. * @param {Function} audioSegmentTimingInfoFn
  36210. * a callback that receives audio timing info based on media times and
  36211. * any adjustments made by the transmuxer
  36212. * @param {Function} id3Fn - a callback that receives ID3 metadata
  36213. * @param {Function} captionsFn - a callback that receives captions
  36214. * @param {boolean} isEndOfTimeline
  36215. * true if this segment represents the last segment in a timeline
  36216. * @param {Function} endedTimelineFn
  36217. * a callback made when a timeline is ended, will only be called if
  36218. * isEndOfTimeline is true
  36219. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36220. * and ready to use
  36221. * @param {Function} doneFn - a callback that is executed after all resources have been
  36222. * downloaded and any decryption completed
  36223. */
  36224. const waitForCompletion = ({
  36225. activeXhrs,
  36226. decryptionWorker,
  36227. trackInfoFn,
  36228. timingInfoFn,
  36229. videoSegmentTimingInfoFn,
  36230. audioSegmentTimingInfoFn,
  36231. id3Fn,
  36232. captionsFn,
  36233. isEndOfTimeline,
  36234. endedTimelineFn,
  36235. dataFn,
  36236. doneFn,
  36237. onTransmuxerLog
  36238. }) => {
  36239. let count = 0;
  36240. let didError = false;
  36241. return (error, segment) => {
  36242. if (didError) {
  36243. return;
  36244. }
  36245. if (error) {
  36246. didError = true; // If there are errors, we have to abort any outstanding requests
  36247. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  36248. // handle the aborted events from those requests, there are some cases where we may
  36249. // never get an aborted event. For instance, if the network connection is lost and
  36250. // there were two requests, the first may have triggered an error immediately, while
  36251. // the second request remains unsent. In that case, the aborted algorithm will not
  36252. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  36253. //
  36254. // We also can't rely on the ready state of the XHR, since the request that
  36255. // triggered the connection error may also show as a ready state of 0 (unsent).
  36256. // Therefore, we have to finish this group of requests immediately after the first
  36257. // seen error.
  36258. return doneFn(error, segment);
  36259. }
  36260. count += 1;
  36261. if (count === activeXhrs.length) {
  36262. const segmentFinish = function () {
  36263. if (segment.encryptedBytes) {
  36264. return decryptSegment({
  36265. decryptionWorker,
  36266. segment,
  36267. trackInfoFn,
  36268. timingInfoFn,
  36269. videoSegmentTimingInfoFn,
  36270. audioSegmentTimingInfoFn,
  36271. id3Fn,
  36272. captionsFn,
  36273. isEndOfTimeline,
  36274. endedTimelineFn,
  36275. dataFn,
  36276. doneFn,
  36277. onTransmuxerLog
  36278. });
  36279. } // Otherwise, everything is ready just continue
  36280. handleSegmentBytes({
  36281. segment,
  36282. bytes: segment.bytes,
  36283. trackInfoFn,
  36284. timingInfoFn,
  36285. videoSegmentTimingInfoFn,
  36286. audioSegmentTimingInfoFn,
  36287. id3Fn,
  36288. captionsFn,
  36289. isEndOfTimeline,
  36290. endedTimelineFn,
  36291. dataFn,
  36292. doneFn,
  36293. onTransmuxerLog
  36294. });
  36295. }; // Keep track of when *all* of the requests have completed
  36296. segment.endOfAllRequests = Date.now();
  36297. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  36298. return decrypt({
  36299. decryptionWorker,
  36300. // add -init to the "id" to differentiate between segment
  36301. // and init segment decryption, just in case they happen
  36302. // at the same time at some point in the future.
  36303. id: segment.requestId + '-init',
  36304. encryptedBytes: segment.map.encryptedBytes,
  36305. key: segment.map.key
  36306. }, decryptedBytes => {
  36307. segment.map.bytes = decryptedBytes;
  36308. parseInitSegment(segment, parseError => {
  36309. if (parseError) {
  36310. abortAll(activeXhrs);
  36311. return doneFn(parseError, segment);
  36312. }
  36313. segmentFinish();
  36314. });
  36315. });
  36316. }
  36317. segmentFinish();
  36318. }
  36319. };
  36320. };
  36321. /**
  36322. * Calls the abort callback if any request within the batch was aborted. Will only call
  36323. * the callback once per batch of requests, even if multiple were aborted.
  36324. *
  36325. * @param {Object} loadendState - state to check to see if the abort function was called
  36326. * @param {Function} abortFn - callback to call for abort
  36327. */
  36328. const handleLoadEnd = ({
  36329. loadendState,
  36330. abortFn
  36331. }) => event => {
  36332. const request = event.target;
  36333. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  36334. abortFn();
  36335. loadendState.calledAbortFn = true;
  36336. }
  36337. };
  36338. /**
  36339. * Simple progress event callback handler that gathers some stats before
  36340. * executing a provided callback with the `segment` object
  36341. *
  36342. * @param {Object} segment - a simplified copy of the segmentInfo object
  36343. * from SegmentLoader
  36344. * @param {Function} progressFn - a callback that is executed each time a progress event
  36345. * is received
  36346. * @param {Function} trackInfoFn - a callback that receives track info
  36347. * @param {Function} timingInfoFn - a callback that receives timing info
  36348. * @param {Function} videoSegmentTimingInfoFn
  36349. * a callback that receives video timing info based on media times and
  36350. * any adjustments made by the transmuxer
  36351. * @param {Function} audioSegmentTimingInfoFn
  36352. * a callback that receives audio timing info based on media times and
  36353. * any adjustments made by the transmuxer
  36354. * @param {boolean} isEndOfTimeline
  36355. * true if this segment represents the last segment in a timeline
  36356. * @param {Function} endedTimelineFn
  36357. * a callback made when a timeline is ended, will only be called if
  36358. * isEndOfTimeline is true
  36359. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36360. * and ready to use
  36361. * @param {Event} event - the progress event object from XMLHttpRequest
  36362. */
  36363. const handleProgress = ({
  36364. segment,
  36365. progressFn,
  36366. trackInfoFn,
  36367. timingInfoFn,
  36368. videoSegmentTimingInfoFn,
  36369. audioSegmentTimingInfoFn,
  36370. id3Fn,
  36371. captionsFn,
  36372. isEndOfTimeline,
  36373. endedTimelineFn,
  36374. dataFn
  36375. }) => event => {
  36376. const request = event.target;
  36377. if (request.aborted) {
  36378. return;
  36379. }
  36380. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  36381. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  36382. segment.stats.firstBytesReceivedAt = Date.now();
  36383. }
  36384. return progressFn(event, segment);
  36385. };
  36386. /**
  36387. * Load all resources and does any processing necessary for a media-segment
  36388. *
  36389. * Features:
  36390. * decrypts the media-segment if it has a key uri and an iv
  36391. * aborts *all* requests if *any* one request fails
  36392. *
  36393. * The segment object, at minimum, has the following format:
  36394. * {
  36395. * resolvedUri: String,
  36396. * [transmuxer]: Object,
  36397. * [byterange]: {
  36398. * offset: Number,
  36399. * length: Number
  36400. * },
  36401. * [key]: {
  36402. * resolvedUri: String
  36403. * [byterange]: {
  36404. * offset: Number,
  36405. * length: Number
  36406. * },
  36407. * iv: {
  36408. * bytes: Uint32Array
  36409. * }
  36410. * },
  36411. * [map]: {
  36412. * resolvedUri: String,
  36413. * [byterange]: {
  36414. * offset: Number,
  36415. * length: Number
  36416. * },
  36417. * [bytes]: Uint8Array
  36418. * }
  36419. * }
  36420. * ...where [name] denotes optional properties
  36421. *
  36422. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  36423. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  36424. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  36425. * decryption routines
  36426. * @param {Object} segment - a simplified copy of the segmentInfo object
  36427. * from SegmentLoader
  36428. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  36429. * aborted
  36430. * @param {Function} progressFn - a callback that receives progress events from the main
  36431. * segment's xhr request
  36432. * @param {Function} trackInfoFn - a callback that receives track info
  36433. * @param {Function} timingInfoFn - a callback that receives timing info
  36434. * @param {Function} videoSegmentTimingInfoFn
  36435. * a callback that receives video timing info based on media times and
  36436. * any adjustments made by the transmuxer
  36437. * @param {Function} audioSegmentTimingInfoFn
  36438. * a callback that receives audio timing info based on media times and
  36439. * any adjustments made by the transmuxer
  36440. * @param {Function} id3Fn - a callback that receives ID3 metadata
  36441. * @param {Function} captionsFn - a callback that receives captions
  36442. * @param {boolean} isEndOfTimeline
  36443. * true if this segment represents the last segment in a timeline
  36444. * @param {Function} endedTimelineFn
  36445. * a callback made when a timeline is ended, will only be called if
  36446. * isEndOfTimeline is true
  36447. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  36448. * request, transmuxed if needed
  36449. * @param {Function} doneFn - a callback that is executed only once all requests have
  36450. * succeeded or failed
  36451. * @return {Function} a function that, when invoked, immediately aborts all
  36452. * outstanding requests
  36453. */
  36454. const mediaSegmentRequest = ({
  36455. xhr,
  36456. xhrOptions,
  36457. decryptionWorker,
  36458. segment,
  36459. abortFn,
  36460. progressFn,
  36461. trackInfoFn,
  36462. timingInfoFn,
  36463. videoSegmentTimingInfoFn,
  36464. audioSegmentTimingInfoFn,
  36465. id3Fn,
  36466. captionsFn,
  36467. isEndOfTimeline,
  36468. endedTimelineFn,
  36469. dataFn,
  36470. doneFn,
  36471. onTransmuxerLog
  36472. }) => {
  36473. const activeXhrs = [];
  36474. const finishProcessingFn = waitForCompletion({
  36475. activeXhrs,
  36476. decryptionWorker,
  36477. trackInfoFn,
  36478. timingInfoFn,
  36479. videoSegmentTimingInfoFn,
  36480. audioSegmentTimingInfoFn,
  36481. id3Fn,
  36482. captionsFn,
  36483. isEndOfTimeline,
  36484. endedTimelineFn,
  36485. dataFn,
  36486. doneFn,
  36487. onTransmuxerLog
  36488. }); // optionally, request the decryption key
  36489. if (segment.key && !segment.key.bytes) {
  36490. const objects = [segment.key];
  36491. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  36492. objects.push(segment.map.key);
  36493. }
  36494. const keyRequestOptions = merge(xhrOptions, {
  36495. uri: segment.key.resolvedUri,
  36496. responseType: 'arraybuffer'
  36497. });
  36498. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  36499. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  36500. activeXhrs.push(keyXhr);
  36501. } // optionally, request the associated media init segment
  36502. if (segment.map && !segment.map.bytes) {
  36503. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  36504. if (differentMapKey) {
  36505. const mapKeyRequestOptions = merge(xhrOptions, {
  36506. uri: segment.map.key.resolvedUri,
  36507. responseType: 'arraybuffer'
  36508. });
  36509. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  36510. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  36511. activeXhrs.push(mapKeyXhr);
  36512. }
  36513. const initSegmentOptions = merge(xhrOptions, {
  36514. uri: segment.map.resolvedUri,
  36515. responseType: 'arraybuffer',
  36516. headers: segmentXhrHeaders(segment.map)
  36517. });
  36518. const initSegmentRequestCallback = handleInitSegmentResponse({
  36519. segment,
  36520. finishProcessingFn
  36521. });
  36522. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  36523. activeXhrs.push(initSegmentXhr);
  36524. }
  36525. const segmentRequestOptions = merge(xhrOptions, {
  36526. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  36527. responseType: 'arraybuffer',
  36528. headers: segmentXhrHeaders(segment)
  36529. });
  36530. const segmentRequestCallback = handleSegmentResponse({
  36531. segment,
  36532. finishProcessingFn,
  36533. responseType: segmentRequestOptions.responseType
  36534. });
  36535. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  36536. segmentXhr.addEventListener('progress', handleProgress({
  36537. segment,
  36538. progressFn,
  36539. trackInfoFn,
  36540. timingInfoFn,
  36541. videoSegmentTimingInfoFn,
  36542. audioSegmentTimingInfoFn,
  36543. id3Fn,
  36544. captionsFn,
  36545. isEndOfTimeline,
  36546. endedTimelineFn,
  36547. dataFn
  36548. }));
  36549. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  36550. // multiple times, provide a shared state object
  36551. const loadendState = {};
  36552. activeXhrs.forEach(activeXhr => {
  36553. activeXhr.addEventListener('loadend', handleLoadEnd({
  36554. loadendState,
  36555. abortFn
  36556. }));
  36557. });
  36558. return () => abortAll(activeXhrs);
  36559. };
  36560. /**
  36561. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  36562. * codec strings, or translating codec strings into objects that can be examined.
  36563. */
  36564. const logFn$1 = logger('CodecUtils');
  36565. /**
  36566. * Returns a set of codec strings parsed from the playlist or the default
  36567. * codec strings if no codecs were specified in the playlist
  36568. *
  36569. * @param {Playlist} media the current media playlist
  36570. * @return {Object} an object with the video and audio codecs
  36571. */
  36572. const getCodecs = function (media) {
  36573. // if the codecs were explicitly specified, use them instead of the
  36574. // defaults
  36575. const mediaAttributes = media.attributes || {};
  36576. if (mediaAttributes.CODECS) {
  36577. return codecs_js.parseCodecs(mediaAttributes.CODECS);
  36578. }
  36579. };
  36580. const isMaat = (main, media) => {
  36581. const mediaAttributes = media.attributes || {};
  36582. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36583. };
  36584. const isMuxed = (main, media) => {
  36585. if (!isMaat(main, media)) {
  36586. return true;
  36587. }
  36588. const mediaAttributes = media.attributes || {};
  36589. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36590. for (const groupId in audioGroup) {
  36591. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  36592. // or there are listed playlists (the case for DASH, as the manifest will have already
  36593. // provided all of the details necessary to generate the audio playlist, as opposed to
  36594. // HLS' externally requested playlists), then the content is demuxed.
  36595. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  36596. return true;
  36597. }
  36598. }
  36599. return false;
  36600. };
  36601. const unwrapCodecList = function (codecList) {
  36602. const codecs = {};
  36603. codecList.forEach(({
  36604. mediaType,
  36605. type,
  36606. details
  36607. }) => {
  36608. codecs[mediaType] = codecs[mediaType] || [];
  36609. codecs[mediaType].push(codecs_js.translateLegacyCodec(`${type}${details}`));
  36610. });
  36611. Object.keys(codecs).forEach(function (mediaType) {
  36612. if (codecs[mediaType].length > 1) {
  36613. logFn$1(`multiple ${mediaType} codecs found as attributes: ${codecs[mediaType].join(', ')}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`);
  36614. codecs[mediaType] = null;
  36615. return;
  36616. }
  36617. codecs[mediaType] = codecs[mediaType][0];
  36618. });
  36619. return codecs;
  36620. };
  36621. const codecCount = function (codecObj) {
  36622. let count = 0;
  36623. if (codecObj.audio) {
  36624. count++;
  36625. }
  36626. if (codecObj.video) {
  36627. count++;
  36628. }
  36629. return count;
  36630. };
  36631. /**
  36632. * Calculates the codec strings for a working configuration of
  36633. * SourceBuffers to play variant streams in a main playlist. If
  36634. * there is no possible working configuration, an empty object will be
  36635. * returned.
  36636. *
  36637. * @param main {Object} the m3u8 object for the main playlist
  36638. * @param media {Object} the m3u8 object for the variant playlist
  36639. * @return {Object} the codec strings.
  36640. *
  36641. * @private
  36642. */
  36643. const codecsForPlaylist = function (main, media) {
  36644. const mediaAttributes = media.attributes || {};
  36645. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  36646. // Put another way, there is no way to have a video-only multiple-audio HLS!
  36647. if (isMaat(main, media) && !codecInfo.audio) {
  36648. if (!isMuxed(main, media)) {
  36649. // It is possible for codecs to be specified on the audio media group playlist but
  36650. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  36651. // video are always separate (and separately specified).
  36652. const defaultCodecs = unwrapCodecList(codecs_js.codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  36653. if (defaultCodecs.audio) {
  36654. codecInfo.audio = defaultCodecs.audio;
  36655. }
  36656. }
  36657. }
  36658. return codecInfo;
  36659. };
  36660. const logFn = logger('PlaylistSelector');
  36661. const representationToString = function (representation) {
  36662. if (!representation || !representation.playlist) {
  36663. return;
  36664. }
  36665. const playlist = representation.playlist;
  36666. return JSON.stringify({
  36667. id: playlist.id,
  36668. bandwidth: representation.bandwidth,
  36669. width: representation.width,
  36670. height: representation.height,
  36671. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  36672. });
  36673. }; // Utilities
  36674. /**
  36675. * Returns the CSS value for the specified property on an element
  36676. * using `getComputedStyle`. Firefox has a long-standing issue where
  36677. * getComputedStyle() may return null when running in an iframe with
  36678. * `display: none`.
  36679. *
  36680. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  36681. * @param {HTMLElement} el the htmlelement to work on
  36682. * @param {string} the proprety to get the style for
  36683. */
  36684. const safeGetComputedStyle = function (el, property) {
  36685. if (!el) {
  36686. return '';
  36687. }
  36688. const result = window__default["default"].getComputedStyle(el);
  36689. if (!result) {
  36690. return '';
  36691. }
  36692. return result[property];
  36693. };
  36694. /**
  36695. * Resuable stable sort function
  36696. *
  36697. * @param {Playlists} array
  36698. * @param {Function} sortFn Different comparators
  36699. * @function stableSort
  36700. */
  36701. const stableSort = function (array, sortFn) {
  36702. const newArray = array.slice();
  36703. array.sort(function (left, right) {
  36704. const cmp = sortFn(left, right);
  36705. if (cmp === 0) {
  36706. return newArray.indexOf(left) - newArray.indexOf(right);
  36707. }
  36708. return cmp;
  36709. });
  36710. };
  36711. /**
  36712. * A comparator function to sort two playlist object by bandwidth.
  36713. *
  36714. * @param {Object} left a media playlist object
  36715. * @param {Object} right a media playlist object
  36716. * @return {number} Greater than zero if the bandwidth attribute of
  36717. * left is greater than the corresponding attribute of right. Less
  36718. * than zero if the bandwidth of right is greater than left and
  36719. * exactly zero if the two are equal.
  36720. */
  36721. const comparePlaylistBandwidth = function (left, right) {
  36722. let leftBandwidth;
  36723. let rightBandwidth;
  36724. if (left.attributes.BANDWIDTH) {
  36725. leftBandwidth = left.attributes.BANDWIDTH;
  36726. }
  36727. leftBandwidth = leftBandwidth || window__default["default"].Number.MAX_VALUE;
  36728. if (right.attributes.BANDWIDTH) {
  36729. rightBandwidth = right.attributes.BANDWIDTH;
  36730. }
  36731. rightBandwidth = rightBandwidth || window__default["default"].Number.MAX_VALUE;
  36732. return leftBandwidth - rightBandwidth;
  36733. };
  36734. /**
  36735. * A comparator function to sort two playlist object by resolution (width).
  36736. *
  36737. * @param {Object} left a media playlist object
  36738. * @param {Object} right a media playlist object
  36739. * @return {number} Greater than zero if the resolution.width attribute of
  36740. * left is greater than the corresponding attribute of right. Less
  36741. * than zero if the resolution.width of right is greater than left and
  36742. * exactly zero if the two are equal.
  36743. */
  36744. const comparePlaylistResolution = function (left, right) {
  36745. let leftWidth;
  36746. let rightWidth;
  36747. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  36748. leftWidth = left.attributes.RESOLUTION.width;
  36749. }
  36750. leftWidth = leftWidth || window__default["default"].Number.MAX_VALUE;
  36751. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  36752. rightWidth = right.attributes.RESOLUTION.width;
  36753. }
  36754. rightWidth = rightWidth || window__default["default"].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  36755. // have the same media dimensions/ resolution
  36756. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  36757. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  36758. }
  36759. return leftWidth - rightWidth;
  36760. };
  36761. /**
  36762. * Chooses the appropriate media playlist based on bandwidth and player size
  36763. *
  36764. * @param {Object} main
  36765. * Object representation of the main manifest
  36766. * @param {number} playerBandwidth
  36767. * Current calculated bandwidth of the player
  36768. * @param {number} playerWidth
  36769. * Current width of the player element (should account for the device pixel ratio)
  36770. * @param {number} playerHeight
  36771. * Current height of the player element (should account for the device pixel ratio)
  36772. * @param {boolean} limitRenditionByPlayerDimensions
  36773. * True if the player width and height should be used during the selection, false otherwise
  36774. * @param {Object} playlistController
  36775. * the current playlistController object
  36776. * @return {Playlist} the highest bitrate playlist less than the
  36777. * currently detected bandwidth, accounting for some amount of
  36778. * bandwidth variance
  36779. */
  36780. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  36781. // If we end up getting called before `main` is available, exit early
  36782. if (!main) {
  36783. return;
  36784. }
  36785. const options = {
  36786. bandwidth: playerBandwidth,
  36787. width: playerWidth,
  36788. height: playerHeight,
  36789. limitRenditionByPlayerDimensions
  36790. };
  36791. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  36792. if (Playlist.isAudioOnly(main)) {
  36793. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  36794. // at the buttom of this function for debugging.
  36795. options.audioOnly = true;
  36796. } // convert the playlists to an intermediary representation to make comparisons easier
  36797. let sortedPlaylistReps = playlists.map(playlist => {
  36798. let bandwidth;
  36799. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  36800. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  36801. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  36802. bandwidth = bandwidth || window__default["default"].Number.MAX_VALUE;
  36803. return {
  36804. bandwidth,
  36805. width,
  36806. height,
  36807. playlist
  36808. };
  36809. });
  36810. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  36811. // incompatible configurations
  36812. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  36813. // api or excluded temporarily due to playback errors.
  36814. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  36815. if (!enabledPlaylistReps.length) {
  36816. // if there are no enabled playlists, then they have all been excluded or disabled
  36817. // by the user through the representations api. In this case, ignore exclusion and
  36818. // fallback to what the user wants by using playlists the user has not disabled.
  36819. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  36820. } // filter out any variant that has greater effective bitrate
  36821. // than the current estimated bandwidth
  36822. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  36823. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  36824. // and then taking the very first element
  36825. const bandwidthBestRep = bandwidthPlaylistReps.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0]; // if we're not going to limit renditions by player size, make an early decision.
  36826. if (limitRenditionByPlayerDimensions === false) {
  36827. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36828. if (chosenRep && chosenRep.playlist) {
  36829. let type = 'sortedPlaylistReps';
  36830. if (bandwidthBestRep) {
  36831. type = 'bandwidthBestRep';
  36832. }
  36833. if (enabledPlaylistReps[0]) {
  36834. type = 'enabledPlaylistReps';
  36835. }
  36836. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  36837. return chosenRep.playlist;
  36838. }
  36839. logFn('could not choose a playlist with options', options);
  36840. return null;
  36841. } // filter out playlists without resolution information
  36842. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  36843. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  36844. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  36845. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  36846. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  36847. let resolutionPlusOneList;
  36848. let resolutionPlusOneSmallest;
  36849. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  36850. // if there is no match of exact resolution
  36851. if (!resolutionBestRep) {
  36852. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  36853. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  36854. // is just-larger-than the video player
  36855. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  36856. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  36857. }
  36858. let leastPixelDiffRep; // If this selector proves to be better than others,
  36859. // resolutionPlusOneRep and resolutionBestRep and all
  36860. // the code involving them should be removed.
  36861. if (playlistController.leastPixelDiffSelector) {
  36862. // find the variant that is closest to the player's pixel size
  36863. const leastPixelDiffList = haveResolution.map(rep => {
  36864. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  36865. return rep;
  36866. }); // get the highest bandwidth, closest resolution playlist
  36867. stableSort(leastPixelDiffList, (left, right) => {
  36868. // sort by highest bandwidth if pixelDiff is the same
  36869. if (left.pixelDiff === right.pixelDiff) {
  36870. return right.bandwidth - left.bandwidth;
  36871. }
  36872. return left.pixelDiff - right.pixelDiff;
  36873. });
  36874. leastPixelDiffRep = leastPixelDiffList[0];
  36875. } // fallback chain of variants
  36876. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36877. if (chosenRep && chosenRep.playlist) {
  36878. let type = 'sortedPlaylistReps';
  36879. if (leastPixelDiffRep) {
  36880. type = 'leastPixelDiffRep';
  36881. } else if (resolutionPlusOneRep) {
  36882. type = 'resolutionPlusOneRep';
  36883. } else if (resolutionBestRep) {
  36884. type = 'resolutionBestRep';
  36885. } else if (bandwidthBestRep) {
  36886. type = 'bandwidthBestRep';
  36887. } else if (enabledPlaylistReps[0]) {
  36888. type = 'enabledPlaylistReps';
  36889. }
  36890. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  36891. return chosenRep.playlist;
  36892. }
  36893. logFn('could not choose a playlist with options', options);
  36894. return null;
  36895. };
  36896. /**
  36897. * Chooses the appropriate media playlist based on the most recent
  36898. * bandwidth estimate and the player size.
  36899. *
  36900. * Expects to be called within the context of an instance of VhsHandler
  36901. *
  36902. * @return {Playlist} the highest bitrate playlist less than the
  36903. * currently detected bandwidth, accounting for some amount of
  36904. * bandwidth variance
  36905. */
  36906. const lastBandwidthSelector = function () {
  36907. const pixelRatio = this.useDevicePixelRatio ? window__default["default"].devicePixelRatio || 1 : 1;
  36908. return simpleSelector(this.playlists.main, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  36909. };
  36910. /**
  36911. * Chooses the appropriate media playlist based on an
  36912. * exponential-weighted moving average of the bandwidth after
  36913. * filtering for player size.
  36914. *
  36915. * Expects to be called within the context of an instance of VhsHandler
  36916. *
  36917. * @param {number} decay - a number between 0 and 1. Higher values of
  36918. * this parameter will cause previous bandwidth estimates to lose
  36919. * significance more quickly.
  36920. * @return {Function} a function which can be invoked to create a new
  36921. * playlist selector function.
  36922. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  36923. */
  36924. const movingAverageBandwidthSelector = function (decay) {
  36925. let average = -1;
  36926. let lastSystemBandwidth = -1;
  36927. if (decay < 0 || decay > 1) {
  36928. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  36929. }
  36930. return function () {
  36931. const pixelRatio = this.useDevicePixelRatio ? window__default["default"].devicePixelRatio || 1 : 1;
  36932. if (average < 0) {
  36933. average = this.systemBandwidth;
  36934. lastSystemBandwidth = this.systemBandwidth;
  36935. } // stop the average value from decaying for every 250ms
  36936. // when the systemBandwidth is constant
  36937. // and
  36938. // stop average from setting to a very low value when the
  36939. // systemBandwidth becomes 0 in case of chunk cancellation
  36940. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  36941. average = decay * this.systemBandwidth + (1 - decay) * average;
  36942. lastSystemBandwidth = this.systemBandwidth;
  36943. }
  36944. return simpleSelector(this.playlists.main, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  36945. };
  36946. };
  36947. /**
  36948. * Chooses the appropriate media playlist based on the potential to rebuffer
  36949. *
  36950. * @param {Object} settings
  36951. * Object of information required to use this selector
  36952. * @param {Object} settings.main
  36953. * Object representation of the main manifest
  36954. * @param {number} settings.currentTime
  36955. * The current time of the player
  36956. * @param {number} settings.bandwidth
  36957. * Current measured bandwidth
  36958. * @param {number} settings.duration
  36959. * Duration of the media
  36960. * @param {number} settings.segmentDuration
  36961. * Segment duration to be used in round trip time calculations
  36962. * @param {number} settings.timeUntilRebuffer
  36963. * Time left in seconds until the player has to rebuffer
  36964. * @param {number} settings.currentTimeline
  36965. * The current timeline segments are being loaded from
  36966. * @param {SyncController} settings.syncController
  36967. * SyncController for determining if we have a sync point for a given playlist
  36968. * @return {Object|null}
  36969. * {Object} return.playlist
  36970. * The highest bandwidth playlist with the least amount of rebuffering
  36971. * {Number} return.rebufferingImpact
  36972. * The amount of time in seconds switching to this playlist will rebuffer. A
  36973. * negative value means that switching will cause zero rebuffering.
  36974. */
  36975. const minRebufferMaxBandwidthSelector = function (settings) {
  36976. const {
  36977. main,
  36978. currentTime,
  36979. bandwidth,
  36980. duration,
  36981. segmentDuration,
  36982. timeUntilRebuffer,
  36983. currentTimeline,
  36984. syncController
  36985. } = settings; // filter out any playlists that have been excluded due to
  36986. // incompatible configurations
  36987. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  36988. // api or excluded temporarily due to playback errors.
  36989. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  36990. if (!enabledPlaylists.length) {
  36991. // if there are no enabled playlists, then they have all been excluded or disabled
  36992. // by the user through the representations api. In this case, ignore exclusion and
  36993. // fallback to what the user wants by using playlists the user has not disabled.
  36994. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  36995. }
  36996. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  36997. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  36998. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  36999. // sync request first. This will double the request time
  37000. const numRequests = syncPoint ? 1 : 2;
  37001. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  37002. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  37003. return {
  37004. playlist,
  37005. rebufferingImpact
  37006. };
  37007. });
  37008. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  37009. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  37010. if (noRebufferingPlaylists.length) {
  37011. return noRebufferingPlaylists[0];
  37012. }
  37013. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  37014. return rebufferingEstimates[0] || null;
  37015. };
  37016. /**
  37017. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  37018. * one with video. If no renditions with video exist, return the lowest audio rendition.
  37019. *
  37020. * Expects to be called within the context of an instance of VhsHandler
  37021. *
  37022. * @return {Object|null}
  37023. * {Object} return.playlist
  37024. * The lowest bitrate playlist that contains a video codec. If no such rendition
  37025. * exists pick the lowest audio rendition.
  37026. */
  37027. const lowestBitrateCompatibleVariantSelector = function () {
  37028. // filter out any playlists that have been excluded due to
  37029. // incompatible configurations or playback errors
  37030. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  37031. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  37032. // (this is not necessarily true, although it is generally true).
  37033. //
  37034. // If an entire manifest has no valid videos everything will get filtered
  37035. // out.
  37036. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  37037. return playlistsWithVideo[0] || null;
  37038. };
  37039. /**
  37040. * Combine all segments into a single Uint8Array
  37041. *
  37042. * @param {Object} segmentObj
  37043. * @return {Uint8Array} concatenated bytes
  37044. * @private
  37045. */
  37046. const concatSegments = segmentObj => {
  37047. let offset = 0;
  37048. let tempBuffer;
  37049. if (segmentObj.bytes) {
  37050. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  37051. segmentObj.segments.forEach(segment => {
  37052. tempBuffer.set(segment, offset);
  37053. offset += segment.byteLength;
  37054. });
  37055. }
  37056. return tempBuffer;
  37057. };
  37058. /**
  37059. * @file text-tracks.js
  37060. */
  37061. /**
  37062. * Create captions text tracks on video.js if they do not exist
  37063. *
  37064. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  37065. * @param {Object} tech the video.js tech
  37066. * @param {Object} captionStream the caption stream to create
  37067. * @private
  37068. */
  37069. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  37070. if (!inbandTextTracks[captionStream]) {
  37071. tech.trigger({
  37072. type: 'usage',
  37073. name: 'vhs-608'
  37074. });
  37075. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  37076. if (/^cc708_/.test(captionStream)) {
  37077. instreamId = 'SERVICE' + captionStream.split('_')[1];
  37078. }
  37079. const track = tech.textTracks().getTrackById(instreamId);
  37080. if (track) {
  37081. // Resuse an existing track with a CC# id because this was
  37082. // very likely created by videojs-contrib-hls from information
  37083. // in the m3u8 for us to use
  37084. inbandTextTracks[captionStream] = track;
  37085. } else {
  37086. // This section gets called when we have caption services that aren't specified in the manifest.
  37087. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  37088. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  37089. let label = captionStream;
  37090. let language = captionStream;
  37091. let def = false;
  37092. const captionService = captionServices[instreamId];
  37093. if (captionService) {
  37094. label = captionService.label;
  37095. language = captionService.language;
  37096. def = captionService.default;
  37097. } // Otherwise, create a track with the default `CC#` label and
  37098. // without a language
  37099. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  37100. kind: 'captions',
  37101. id: instreamId,
  37102. // TODO: investigate why this doesn't seem to turn the caption on by default
  37103. default: def,
  37104. label,
  37105. language
  37106. }, false).track;
  37107. }
  37108. }
  37109. };
  37110. /**
  37111. * Add caption text track data to a source handler given an array of captions
  37112. *
  37113. * @param {Object}
  37114. * @param {Object} inbandTextTracks the inband text tracks
  37115. * @param {number} timestampOffset the timestamp offset of the source buffer
  37116. * @param {Array} captionArray an array of caption data
  37117. * @private
  37118. */
  37119. const addCaptionData = function ({
  37120. inbandTextTracks,
  37121. captionArray,
  37122. timestampOffset
  37123. }) {
  37124. if (!captionArray) {
  37125. return;
  37126. }
  37127. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  37128. captionArray.forEach(caption => {
  37129. const track = caption.stream;
  37130. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  37131. });
  37132. };
  37133. /**
  37134. * Define properties on a cue for backwards compatability,
  37135. * but warn the user that the way that they are using it
  37136. * is depricated and will be removed at a later date.
  37137. *
  37138. * @param {Cue} cue the cue to add the properties on
  37139. * @private
  37140. */
  37141. const deprecateOldCue = function (cue) {
  37142. Object.defineProperties(cue.frame, {
  37143. id: {
  37144. get() {
  37145. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  37146. return cue.value.key;
  37147. }
  37148. },
  37149. value: {
  37150. get() {
  37151. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  37152. return cue.value.data;
  37153. }
  37154. },
  37155. privateData: {
  37156. get() {
  37157. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  37158. return cue.value.data;
  37159. }
  37160. }
  37161. });
  37162. };
  37163. /**
  37164. * Add metadata text track data to a source handler given an array of metadata
  37165. *
  37166. * @param {Object}
  37167. * @param {Object} inbandTextTracks the inband text tracks
  37168. * @param {Array} metadataArray an array of meta data
  37169. * @param {number} timestampOffset the timestamp offset of the source buffer
  37170. * @param {number} videoDuration the duration of the video
  37171. * @private
  37172. */
  37173. const addMetadata = ({
  37174. inbandTextTracks,
  37175. metadataArray,
  37176. timestampOffset,
  37177. videoDuration
  37178. }) => {
  37179. if (!metadataArray) {
  37180. return;
  37181. }
  37182. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  37183. const metadataTrack = inbandTextTracks.metadataTrack_;
  37184. if (!metadataTrack) {
  37185. return;
  37186. }
  37187. metadataArray.forEach(metadata => {
  37188. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  37189. // ignore this bit of metadata.
  37190. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  37191. // which is the "Title/Songname/Content description" frame
  37192. if (typeof time !== 'number' || window__default["default"].isNaN(time) || time < 0 || !(time < Infinity)) {
  37193. return;
  37194. }
  37195. metadata.frames.forEach(frame => {
  37196. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  37197. cue.frame = frame;
  37198. cue.value = frame;
  37199. deprecateOldCue(cue);
  37200. metadataTrack.addCue(cue);
  37201. });
  37202. });
  37203. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  37204. return;
  37205. } // Updating the metadeta cues so that
  37206. // the endTime of each cue is the startTime of the next cue
  37207. // the endTime of last cue is the duration of the video
  37208. const cues = metadataTrack.cues;
  37209. const cuesArray = []; // Create a copy of the TextTrackCueList...
  37210. // ...disregarding cues with a falsey value
  37211. for (let i = 0; i < cues.length; i++) {
  37212. if (cues[i]) {
  37213. cuesArray.push(cues[i]);
  37214. }
  37215. } // Group cues by their startTime value
  37216. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  37217. const timeSlot = obj[cue.startTime] || [];
  37218. timeSlot.push(cue);
  37219. obj[cue.startTime] = timeSlot;
  37220. return obj;
  37221. }, {}); // Sort startTimes by ascending order
  37222. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  37223. sortedStartTimes.forEach((startTime, idx) => {
  37224. const cueGroup = cuesGroupedByStartTime[startTime];
  37225. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  37226. cueGroup.forEach(cue => {
  37227. cue.endTime = nextTime;
  37228. });
  37229. });
  37230. };
  37231. /**
  37232. * Create metadata text track on video.js if it does not exist
  37233. *
  37234. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  37235. * @param {string} dispatchType the inband metadata track dispatch type
  37236. * @param {Object} tech the video.js tech
  37237. * @private
  37238. */
  37239. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  37240. if (inbandTextTracks.metadataTrack_) {
  37241. return;
  37242. }
  37243. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  37244. kind: 'metadata',
  37245. label: 'Timed Metadata'
  37246. }, false).track;
  37247. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  37248. };
  37249. /**
  37250. * Remove cues from a track on video.js.
  37251. *
  37252. * @param {Double} start start of where we should remove the cue
  37253. * @param {Double} end end of where the we should remove the cue
  37254. * @param {Object} track the text track to remove the cues from
  37255. * @private
  37256. */
  37257. const removeCuesFromTrack = function (start, end, track) {
  37258. let i;
  37259. let cue;
  37260. if (!track) {
  37261. return;
  37262. }
  37263. if (!track.cues) {
  37264. return;
  37265. }
  37266. i = track.cues.length;
  37267. while (i--) {
  37268. cue = track.cues[i]; // Remove any cue within the provided start and end time
  37269. if (cue.startTime >= start && cue.endTime <= end) {
  37270. track.removeCue(cue);
  37271. }
  37272. }
  37273. };
  37274. /**
  37275. * Remove duplicate cues from a track on video.js (a cue is considered a
  37276. * duplicate if it has the same time interval and text as another)
  37277. *
  37278. * @param {Object} track the text track to remove the duplicate cues from
  37279. * @private
  37280. */
  37281. const removeDuplicateCuesFromTrack = function (track) {
  37282. const cues = track.cues;
  37283. if (!cues) {
  37284. return;
  37285. }
  37286. for (let i = 0; i < cues.length; i++) {
  37287. const duplicates = [];
  37288. let occurrences = 0;
  37289. for (let j = 0; j < cues.length; j++) {
  37290. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  37291. occurrences++;
  37292. if (occurrences > 1) {
  37293. duplicates.push(cues[j]);
  37294. }
  37295. }
  37296. }
  37297. if (duplicates.length) {
  37298. duplicates.forEach(dupe => track.removeCue(dupe));
  37299. }
  37300. }
  37301. };
  37302. /**
  37303. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  37304. * front of current time.
  37305. *
  37306. * @param {Array} buffer
  37307. * The current buffer of gop information
  37308. * @param {number} currentTime
  37309. * The current time
  37310. * @param {Double} mapping
  37311. * Offset to map display time to stream presentation time
  37312. * @return {Array}
  37313. * List of gops considered safe to append over
  37314. */
  37315. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  37316. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  37317. return [];
  37318. } // pts value for current time + 3 seconds to give a bit more wiggle room
  37319. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  37320. let i;
  37321. for (i = 0; i < buffer.length; i++) {
  37322. if (buffer[i].pts > currentTimePts) {
  37323. break;
  37324. }
  37325. }
  37326. return buffer.slice(i);
  37327. };
  37328. /**
  37329. * Appends gop information (timing and byteLength) received by the transmuxer for the
  37330. * gops appended in the last call to appendBuffer
  37331. *
  37332. * @param {Array} buffer
  37333. * The current buffer of gop information
  37334. * @param {Array} gops
  37335. * List of new gop information
  37336. * @param {boolean} replace
  37337. * If true, replace the buffer with the new gop information. If false, append the
  37338. * new gop information to the buffer in the right location of time.
  37339. * @return {Array}
  37340. * Updated list of gop information
  37341. */
  37342. const updateGopBuffer = (buffer, gops, replace) => {
  37343. if (!gops.length) {
  37344. return buffer;
  37345. }
  37346. if (replace) {
  37347. // If we are in safe append mode, then completely overwrite the gop buffer
  37348. // with the most recent appeneded data. This will make sure that when appending
  37349. // future segments, we only try to align with gops that are both ahead of current
  37350. // time and in the last segment appended.
  37351. return gops.slice();
  37352. }
  37353. const start = gops[0].pts;
  37354. let i = 0;
  37355. for (i; i < buffer.length; i++) {
  37356. if (buffer[i].pts >= start) {
  37357. break;
  37358. }
  37359. }
  37360. return buffer.slice(0, i).concat(gops);
  37361. };
  37362. /**
  37363. * Removes gop information in buffer that overlaps with provided start and end
  37364. *
  37365. * @param {Array} buffer
  37366. * The current buffer of gop information
  37367. * @param {Double} start
  37368. * position to start the remove at
  37369. * @param {Double} end
  37370. * position to end the remove at
  37371. * @param {Double} mapping
  37372. * Offset to map display time to stream presentation time
  37373. */
  37374. const removeGopBuffer = (buffer, start, end, mapping) => {
  37375. const startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  37376. const endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  37377. const updatedBuffer = buffer.slice();
  37378. let i = buffer.length;
  37379. while (i--) {
  37380. if (buffer[i].pts <= endPts) {
  37381. break;
  37382. }
  37383. }
  37384. if (i === -1) {
  37385. // no removal because end of remove range is before start of buffer
  37386. return updatedBuffer;
  37387. }
  37388. let j = i + 1;
  37389. while (j--) {
  37390. if (buffer[j].pts <= startPts) {
  37391. break;
  37392. }
  37393. } // clamp remove range start to 0 index
  37394. j = Math.max(j, 0);
  37395. updatedBuffer.splice(j, i - j + 1);
  37396. return updatedBuffer;
  37397. };
  37398. const shallowEqual = function (a, b) {
  37399. // if both are undefined
  37400. // or one or the other is undefined
  37401. // they are not equal
  37402. if (!a && !b || !a && b || a && !b) {
  37403. return false;
  37404. } // they are the same object and thus, equal
  37405. if (a === b) {
  37406. return true;
  37407. } // sort keys so we can make sure they have
  37408. // all the same keys later.
  37409. const akeys = Object.keys(a).sort();
  37410. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  37411. if (akeys.length !== bkeys.length) {
  37412. return false;
  37413. }
  37414. for (let i = 0; i < akeys.length; i++) {
  37415. const key = akeys[i]; // different sorted keys, not equal
  37416. if (key !== bkeys[i]) {
  37417. return false;
  37418. } // different values, not equal
  37419. if (a[key] !== b[key]) {
  37420. return false;
  37421. }
  37422. }
  37423. return true;
  37424. };
  37425. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  37426. const QUOTA_EXCEEDED_ERR = 22;
  37427. /**
  37428. * The segment loader has no recourse except to fetch a segment in the
  37429. * current playlist and use the internal timestamps in that segment to
  37430. * generate a syncPoint. This function returns a good candidate index
  37431. * for that process.
  37432. *
  37433. * @param {Array} segments - the segments array from a playlist.
  37434. * @return {number} An index of a segment from the playlist to load
  37435. */
  37436. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  37437. segments = segments || [];
  37438. const timelineSegments = [];
  37439. let time = 0;
  37440. for (let i = 0; i < segments.length; i++) {
  37441. const segment = segments[i];
  37442. if (currentTimeline === segment.timeline) {
  37443. timelineSegments.push(i);
  37444. time += segment.duration;
  37445. if (time > targetTime) {
  37446. return i;
  37447. }
  37448. }
  37449. }
  37450. if (timelineSegments.length === 0) {
  37451. return 0;
  37452. } // default to the last timeline segment
  37453. return timelineSegments[timelineSegments.length - 1];
  37454. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  37455. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  37456. // as a start to prevent any potential issues with removing content too close to the
  37457. // playhead.
  37458. const MIN_BACK_BUFFER = 1; // in ms
  37459. const CHECK_BUFFER_DELAY = 500;
  37460. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  37461. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  37462. // not accurately reflect the rest of the content.
  37463. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  37464. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  37465. // Although these checks should most likely cover non 'main' types, for now it narrows
  37466. // the scope of our checks.
  37467. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  37468. return null;
  37469. }
  37470. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  37471. return 'Neither audio nor video found in segment.';
  37472. }
  37473. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  37474. return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
  37475. }
  37476. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  37477. return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
  37478. }
  37479. return null;
  37480. };
  37481. /**
  37482. * Calculates a time value that is safe to remove from the back buffer without interrupting
  37483. * playback.
  37484. *
  37485. * @param {TimeRange} seekable
  37486. * The current seekable range
  37487. * @param {number} currentTime
  37488. * The current time of the player
  37489. * @param {number} targetDuration
  37490. * The target duration of the current playlist
  37491. * @return {number}
  37492. * Time that is safe to remove from the back buffer without interrupting playback
  37493. */
  37494. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  37495. // 30 seconds before the playhead provides a safe default for trimming.
  37496. //
  37497. // Choosing a reasonable default is particularly important for high bitrate content and
  37498. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  37499. // throw an APPEND_BUFFER_ERR.
  37500. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  37501. if (seekable.length) {
  37502. // Some live playlists may have a shorter window of content than the full allowed back
  37503. // buffer. For these playlists, don't save content that's no longer within the window.
  37504. trimTime = Math.max(trimTime, seekable.start(0));
  37505. } // Don't remove within target duration of the current time to avoid the possibility of
  37506. // removing the GOP currently being played, as removing it can cause playback stalls.
  37507. const maxTrimTime = currentTime - targetDuration;
  37508. return Math.min(maxTrimTime, trimTime);
  37509. };
  37510. const segmentInfoString = segmentInfo => {
  37511. const {
  37512. startOfSegment,
  37513. duration,
  37514. segment,
  37515. part,
  37516. playlist: {
  37517. mediaSequence: seq,
  37518. id,
  37519. segments = []
  37520. },
  37521. mediaIndex: index,
  37522. partIndex,
  37523. timeline
  37524. } = segmentInfo;
  37525. const segmentLen = segments.length - 1;
  37526. let selection = 'mediaIndex/partIndex increment';
  37527. if (segmentInfo.getMediaInfoForTime) {
  37528. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  37529. } else if (segmentInfo.isSyncRequest) {
  37530. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  37531. }
  37532. if (segmentInfo.independent) {
  37533. selection += ` with independent ${segmentInfo.independent}`;
  37534. }
  37535. const hasPartIndex = typeof partIndex === 'number';
  37536. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  37537. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  37538. preloadSegment: segment
  37539. }) - 1 : 0;
  37540. return `${name} [${seq + index}/${seq + segmentLen}]` + (hasPartIndex ? ` part [${partIndex}/${zeroBasedPartCount}]` : '') + ` segment start/end [${segment.start} => ${segment.end}]` + (hasPartIndex ? ` part start/end [${part.start} => ${part.end}]` : '') + ` startOfSegment [${startOfSegment}]` + ` duration [${duration}]` + ` timeline [${timeline}]` + ` selected by [${selection}]` + ` playlist [${id}]`;
  37541. };
  37542. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  37543. /**
  37544. * Returns the timestamp offset to use for the segment.
  37545. *
  37546. * @param {number} segmentTimeline
  37547. * The timeline of the segment
  37548. * @param {number} currentTimeline
  37549. * The timeline currently being followed by the loader
  37550. * @param {number} startOfSegment
  37551. * The estimated segment start
  37552. * @param {TimeRange[]} buffered
  37553. * The loader's buffer
  37554. * @param {boolean} overrideCheck
  37555. * If true, no checks are made to see if the timestamp offset value should be set,
  37556. * but sets it directly to a value.
  37557. *
  37558. * @return {number|null}
  37559. * Either a number representing a new timestamp offset, or null if the segment is
  37560. * part of the same timeline
  37561. */
  37562. const timestampOffsetForSegment = ({
  37563. segmentTimeline,
  37564. currentTimeline,
  37565. startOfSegment,
  37566. buffered,
  37567. overrideCheck
  37568. }) => {
  37569. // Check to see if we are crossing a discontinuity to see if we need to set the
  37570. // timestamp offset on the transmuxer and source buffer.
  37571. //
  37572. // Previously, we changed the timestampOffset if the start of this segment was less than
  37573. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  37574. // behavior, especially around long running live streams.
  37575. if (!overrideCheck && segmentTimeline === currentTimeline) {
  37576. return null;
  37577. } // When changing renditions, it's possible to request a segment on an older timeline. For
  37578. // instance, given two renditions with the following:
  37579. //
  37580. // #EXTINF:10
  37581. // segment1
  37582. // #EXT-X-DISCONTINUITY
  37583. // #EXTINF:10
  37584. // segment2
  37585. // #EXTINF:10
  37586. // segment3
  37587. //
  37588. // And the current player state:
  37589. //
  37590. // current time: 8
  37591. // buffer: 0 => 20
  37592. //
  37593. // The next segment on the current rendition would be segment3, filling the buffer from
  37594. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  37595. // then the next segment to be requested will be segment1 from the new rendition in
  37596. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  37597. // content (since it would position segment1 of the new rendition starting at 20s). This
  37598. // case can be identified when the new segment's timeline is a prior value. Instead of
  37599. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  37600. // more accurate to the actual start time of the segment.
  37601. if (segmentTimeline < currentTimeline) {
  37602. return startOfSegment;
  37603. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  37604. // value uses the end of the last segment if it is available. While this value
  37605. // should often be correct, it's better to rely on the buffered end, as the new
  37606. // content post discontinuity should line up with the buffered end as if it were
  37607. // time 0 for the new content.
  37608. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  37609. };
  37610. /**
  37611. * Returns whether or not the loader should wait for a timeline change from the timeline
  37612. * change controller before processing the segment.
  37613. *
  37614. * Primary timing in VHS goes by video. This is different from most media players, as
  37615. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  37616. * will continue to use video as the primary timing source, due to the current logic and
  37617. * expectations built around it.
  37618. * Since the timing follows video, in order to maintain sync, the video loader is
  37619. * responsible for setting both audio and video source buffer timestamp offsets.
  37620. *
  37621. * Setting different values for audio and video source buffers could lead to
  37622. * desyncing. The following examples demonstrate some of the situations where this
  37623. * distinction is important. Note that all of these cases involve demuxed content. When
  37624. * content is muxed, the audio and video are packaged together, therefore syncing
  37625. * separate media playlists is not an issue.
  37626. *
  37627. * CASE 1: Audio prepares to load a new timeline before video:
  37628. *
  37629. * Timeline: 0 1
  37630. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37631. * Audio Loader: ^
  37632. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37633. * Video Loader ^
  37634. *
  37635. * In the above example, the audio loader is preparing to load the 6th segment, the first
  37636. * after a discontinuity, while the video loader is still loading the 5th segment, before
  37637. * the discontinuity.
  37638. *
  37639. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  37640. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  37641. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  37642. * the audio loader must provide the audioAppendStart value to trim the content in the
  37643. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  37644. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  37645. * segment until that value is provided.
  37646. *
  37647. * CASE 2: Video prepares to load a new timeline before audio:
  37648. *
  37649. * Timeline: 0 1
  37650. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37651. * Audio Loader: ^
  37652. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37653. * Video Loader ^
  37654. *
  37655. * In the above example, the video loader is preparing to load the 6th segment, the first
  37656. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  37657. * the discontinuity.
  37658. *
  37659. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  37660. * segment is loaded and processed, both the video and audio timestamp offsets will be
  37661. * set, since video is used as the primary timing source. This is to ensure content lines
  37662. * up appropriately, as any modifications to the video timing are reflected by audio when
  37663. * the video loader sets the audio and video timestamp offsets to the same value. However,
  37664. * setting the timestamp offset for audio before audio has had a chance to change
  37665. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  37666. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  37667. *
  37668. * CASE 3: When seeking, audio prepares to load a new timeline before video
  37669. *
  37670. * Timeline: 0 1
  37671. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37672. * Audio Loader: ^
  37673. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37674. * Video Loader ^
  37675. *
  37676. * In the above example, both audio and video loaders are loading segments from timeline
  37677. * 0, but imagine that the seek originated from timeline 1.
  37678. *
  37679. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  37680. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  37681. * must wait for the video loader to load its segment and update both the audio and video
  37682. * timestamp offsets before it may load and append its own segment. This is the case
  37683. * whether the seek results in a mismatched segment request (e.g., the audio loader
  37684. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  37685. * loaders choose to load the same segment index from each playlist, as the segments may
  37686. * not be aligned perfectly, even for matching segment indexes.
  37687. *
  37688. * @param {Object} timelinechangeController
  37689. * @param {number} currentTimeline
  37690. * The timeline currently being followed by the loader
  37691. * @param {number} segmentTimeline
  37692. * The timeline of the segment being loaded
  37693. * @param {('main'|'audio')} loaderType
  37694. * The loader type
  37695. * @param {boolean} audioDisabled
  37696. * Whether the audio is disabled for the loader. This should only be true when the
  37697. * loader may have muxed audio in its segment, but should not append it, e.g., for
  37698. * the main loader when an alternate audio playlist is active.
  37699. *
  37700. * @return {boolean}
  37701. * Whether the loader should wait for a timeline change from the timeline change
  37702. * controller before processing the segment
  37703. */
  37704. const shouldWaitForTimelineChange = ({
  37705. timelineChangeController,
  37706. currentTimeline,
  37707. segmentTimeline,
  37708. loaderType,
  37709. audioDisabled
  37710. }) => {
  37711. if (currentTimeline === segmentTimeline) {
  37712. return false;
  37713. }
  37714. if (loaderType === 'audio') {
  37715. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  37716. type: 'main'
  37717. }); // Audio loader should wait if:
  37718. //
  37719. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  37720. // * main hasn't yet changed to the timeline audio is looking to load
  37721. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  37722. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  37723. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  37724. // loader's segments (or the content is audio/video only and handled by the main
  37725. // loader).
  37726. if (loaderType === 'main' && audioDisabled) {
  37727. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  37728. type: 'audio'
  37729. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  37730. // change to the current timeline.
  37731. //
  37732. // Since the main loader is responsible for setting the timestamp offset for both
  37733. // audio and video, the main loader must wait for audio to be about to change to its
  37734. // timeline before setting the offset, otherwise, if audio is behind in loading,
  37735. // segments from the previous timeline would be adjusted by the new timestamp offset.
  37736. //
  37737. // This requirement means that video will not cross a timeline until the audio is
  37738. // about to cross to it, so that way audio and video will always cross the timeline
  37739. // together.
  37740. //
  37741. // In addition to normal timeline changes, these rules also apply to the start of a
  37742. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  37743. // that these rules apply to the first timeline change because if they did not, it's
  37744. // possible that the main loader will cross two timelines before the audio loader has
  37745. // crossed one. Logic may be implemented to handle the startup as a special case, but
  37746. // it's easier to simply treat all timeline changes the same.
  37747. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  37748. return false;
  37749. }
  37750. return true;
  37751. }
  37752. return false;
  37753. };
  37754. const mediaDuration = timingInfos => {
  37755. let maxDuration = 0;
  37756. ['video', 'audio'].forEach(function (type) {
  37757. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  37758. if (!typeTimingInfo) {
  37759. return;
  37760. }
  37761. const {
  37762. start,
  37763. end
  37764. } = typeTimingInfo;
  37765. let duration;
  37766. if (typeof start === 'bigint' || typeof end === 'bigint') {
  37767. duration = window__default["default"].BigInt(end) - window__default["default"].BigInt(start);
  37768. } else if (typeof start === 'number' && typeof end === 'number') {
  37769. duration = end - start;
  37770. }
  37771. if (typeof duration !== 'undefined' && duration > maxDuration) {
  37772. maxDuration = duration;
  37773. }
  37774. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  37775. // as we only need BigInt when we are above that.
  37776. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  37777. maxDuration = Number(maxDuration);
  37778. }
  37779. return maxDuration;
  37780. };
  37781. const segmentTooLong = ({
  37782. segmentDuration,
  37783. maxDuration
  37784. }) => {
  37785. // 0 duration segments are most likely due to metadata only segments or a lack of
  37786. // information.
  37787. if (!segmentDuration) {
  37788. return false;
  37789. } // For HLS:
  37790. //
  37791. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  37792. // The EXTINF duration of each Media Segment in the Playlist
  37793. // file, when rounded to the nearest integer, MUST be less than or equal
  37794. // to the target duration; longer segments can trigger playback stalls
  37795. // or other errors.
  37796. //
  37797. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  37798. // duration. Although that reported duration is occasionally approximate (i.e., not
  37799. // exact), a strict check may report that a segment is too long more often in DASH.
  37800. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  37801. };
  37802. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  37803. // Right now we aren't following DASH's timing model exactly, so only perform
  37804. // this check for HLS content.
  37805. if (sourceType !== 'hls') {
  37806. return null;
  37807. }
  37808. const segmentDuration = mediaDuration({
  37809. audioTimingInfo: segmentInfo.audioTimingInfo,
  37810. videoTimingInfo: segmentInfo.videoTimingInfo
  37811. }); // Don't report if we lack information.
  37812. //
  37813. // If the segment has a duration of 0 it is either a lack of information or a
  37814. // metadata only segment and shouldn't be reported here.
  37815. if (!segmentDuration) {
  37816. return null;
  37817. }
  37818. const targetDuration = segmentInfo.playlist.targetDuration;
  37819. const isSegmentWayTooLong = segmentTooLong({
  37820. segmentDuration,
  37821. maxDuration: targetDuration * 2
  37822. });
  37823. const isSegmentSlightlyTooLong = segmentTooLong({
  37824. segmentDuration,
  37825. maxDuration: targetDuration
  37826. });
  37827. const segmentTooLongMessage = `Segment with index ${segmentInfo.mediaIndex} ` + `from playlist ${segmentInfo.playlist.id} ` + `has a duration of ${segmentDuration} ` + `when the reported duration is ${segmentInfo.duration} ` + `and the target duration is ${targetDuration}. ` + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
  37828. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  37829. return {
  37830. severity: isSegmentWayTooLong ? 'warn' : 'info',
  37831. message: segmentTooLongMessage
  37832. };
  37833. }
  37834. return null;
  37835. };
  37836. /**
  37837. * An object that manages segment loading and appending.
  37838. *
  37839. * @class SegmentLoader
  37840. * @param {Object} options required and optional options
  37841. * @extends videojs.EventTarget
  37842. */
  37843. class SegmentLoader extends videojs.EventTarget {
  37844. constructor(settings, options = {}) {
  37845. super(); // check pre-conditions
  37846. if (!settings) {
  37847. throw new TypeError('Initialization settings are required');
  37848. }
  37849. if (typeof settings.currentTime !== 'function') {
  37850. throw new TypeError('No currentTime getter specified');
  37851. }
  37852. if (!settings.mediaSource) {
  37853. throw new TypeError('No MediaSource specified');
  37854. } // public properties
  37855. this.bandwidth = settings.bandwidth;
  37856. this.throughput = {
  37857. rate: 0,
  37858. count: 0
  37859. };
  37860. this.roundTrip = NaN;
  37861. this.resetStats_();
  37862. this.mediaIndex = null;
  37863. this.partIndex = null; // private settings
  37864. this.hasPlayed_ = settings.hasPlayed;
  37865. this.currentTime_ = settings.currentTime;
  37866. this.seekable_ = settings.seekable;
  37867. this.seeking_ = settings.seeking;
  37868. this.duration_ = settings.duration;
  37869. this.mediaSource_ = settings.mediaSource;
  37870. this.vhs_ = settings.vhs;
  37871. this.loaderType_ = settings.loaderType;
  37872. this.currentMediaInfo_ = void 0;
  37873. this.startingMediaInfo_ = void 0;
  37874. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  37875. this.goalBufferLength_ = settings.goalBufferLength;
  37876. this.sourceType_ = settings.sourceType;
  37877. this.sourceUpdater_ = settings.sourceUpdater;
  37878. this.inbandTextTracks_ = settings.inbandTextTracks;
  37879. this.state_ = 'INIT';
  37880. this.timelineChangeController_ = settings.timelineChangeController;
  37881. this.shouldSaveSegmentTimingInfo_ = true;
  37882. this.parse708captions_ = settings.parse708captions;
  37883. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  37884. this.captionServices_ = settings.captionServices;
  37885. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  37886. this.checkBufferTimeout_ = null;
  37887. this.error_ = void 0;
  37888. this.currentTimeline_ = -1;
  37889. this.pendingSegment_ = null;
  37890. this.xhrOptions_ = null;
  37891. this.pendingSegments_ = [];
  37892. this.audioDisabled_ = false;
  37893. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  37894. this.gopBuffer_ = [];
  37895. this.timeMapping_ = 0;
  37896. this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  37897. this.appendInitSegment_ = {
  37898. audio: true,
  37899. video: true
  37900. };
  37901. this.playlistOfLastInitSegment_ = {
  37902. audio: null,
  37903. video: null
  37904. };
  37905. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  37906. // information yet to start the loading process (e.g., if the audio loader wants to
  37907. // load a segment from the next timeline but the main loader hasn't yet crossed that
  37908. // timeline), then the load call will be added to the queue until it is ready to be
  37909. // processed.
  37910. this.loadQueue_ = [];
  37911. this.metadataQueue_ = {
  37912. id3: [],
  37913. caption: []
  37914. };
  37915. this.waitingOnRemove_ = false;
  37916. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  37917. this.activeInitSegmentId_ = null;
  37918. this.initSegments_ = {}; // HLSe playback
  37919. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  37920. this.keyCache_ = {};
  37921. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  37922. // between a time in the display time and a segment index within
  37923. // a playlist
  37924. this.syncController_ = settings.syncController;
  37925. this.syncPoint_ = {
  37926. segmentIndex: 0,
  37927. time: 0
  37928. };
  37929. this.transmuxer_ = this.createTransmuxer_();
  37930. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  37931. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  37932. this.mediaSource_.addEventListener('sourceopen', () => {
  37933. if (!this.isEndOfStream_()) {
  37934. this.ended_ = false;
  37935. }
  37936. }); // ...for determining the fetch location
  37937. this.fetchAtBuffer_ = false;
  37938. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  37939. Object.defineProperty(this, 'state', {
  37940. get() {
  37941. return this.state_;
  37942. },
  37943. set(newState) {
  37944. if (newState !== this.state_) {
  37945. this.logger_(`${this.state_} -> ${newState}`);
  37946. this.state_ = newState;
  37947. this.trigger('statechange');
  37948. }
  37949. }
  37950. });
  37951. this.sourceUpdater_.on('ready', () => {
  37952. if (this.hasEnoughInfoToAppend_()) {
  37953. this.processCallQueue_();
  37954. }
  37955. }); // Only the main loader needs to listen for pending timeline changes, as the main
  37956. // loader should wait for audio to be ready to change its timeline so that both main
  37957. // and audio timelines change together. For more details, see the
  37958. // shouldWaitForTimelineChange function.
  37959. if (this.loaderType_ === 'main') {
  37960. this.timelineChangeController_.on('pendingtimelinechange', () => {
  37961. if (this.hasEnoughInfoToAppend_()) {
  37962. this.processCallQueue_();
  37963. }
  37964. });
  37965. } // The main loader only listens on pending timeline changes, but the audio loader,
  37966. // since its loads follow main, needs to listen on timeline changes. For more details,
  37967. // see the shouldWaitForTimelineChange function.
  37968. if (this.loaderType_ === 'audio') {
  37969. this.timelineChangeController_.on('timelinechange', () => {
  37970. if (this.hasEnoughInfoToLoad_()) {
  37971. this.processLoadQueue_();
  37972. }
  37973. if (this.hasEnoughInfoToAppend_()) {
  37974. this.processCallQueue_();
  37975. }
  37976. });
  37977. }
  37978. }
  37979. createTransmuxer_() {
  37980. return segmentTransmuxer.createTransmuxer({
  37981. remux: false,
  37982. alignGopsAtEnd: this.safeAppend_,
  37983. keepOriginalTimestamps: true,
  37984. parse708captions: this.parse708captions_,
  37985. captionServices: this.captionServices_
  37986. });
  37987. }
  37988. /**
  37989. * reset all of our media stats
  37990. *
  37991. * @private
  37992. */
  37993. resetStats_() {
  37994. this.mediaBytesTransferred = 0;
  37995. this.mediaRequests = 0;
  37996. this.mediaRequestsAborted = 0;
  37997. this.mediaRequestsTimedout = 0;
  37998. this.mediaRequestsErrored = 0;
  37999. this.mediaTransferDuration = 0;
  38000. this.mediaSecondsLoaded = 0;
  38001. this.mediaAppends = 0;
  38002. }
  38003. /**
  38004. * dispose of the SegmentLoader and reset to the default state
  38005. */
  38006. dispose() {
  38007. this.trigger('dispose');
  38008. this.state = 'DISPOSED';
  38009. this.pause();
  38010. this.abort_();
  38011. if (this.transmuxer_) {
  38012. this.transmuxer_.terminate();
  38013. }
  38014. this.resetStats_();
  38015. if (this.checkBufferTimeout_) {
  38016. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  38017. }
  38018. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  38019. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  38020. }
  38021. this.off();
  38022. }
  38023. setAudio(enable) {
  38024. this.audioDisabled_ = !enable;
  38025. if (enable) {
  38026. this.appendInitSegment_.audio = true;
  38027. } else {
  38028. // remove current track audio if it gets disabled
  38029. this.sourceUpdater_.removeAudio(0, this.duration_());
  38030. }
  38031. }
  38032. /**
  38033. * abort anything that is currently doing on with the SegmentLoader
  38034. * and reset to a default state
  38035. */
  38036. abort() {
  38037. if (this.state !== 'WAITING') {
  38038. if (this.pendingSegment_) {
  38039. this.pendingSegment_ = null;
  38040. }
  38041. return;
  38042. }
  38043. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  38044. // since we are no longer "waiting" on any requests. XHR callback is not always run
  38045. // when the request is aborted. This will prevent the loader from being stuck in the
  38046. // WAITING state indefinitely.
  38047. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  38048. // next segment
  38049. if (!this.paused()) {
  38050. this.monitorBuffer_();
  38051. }
  38052. }
  38053. /**
  38054. * abort all pending xhr requests and null any pending segements
  38055. *
  38056. * @private
  38057. */
  38058. abort_() {
  38059. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  38060. this.pendingSegment_.abortRequests();
  38061. } // clear out the segment being processed
  38062. this.pendingSegment_ = null;
  38063. this.callQueue_ = [];
  38064. this.loadQueue_ = [];
  38065. this.metadataQueue_.id3 = [];
  38066. this.metadataQueue_.caption = [];
  38067. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  38068. this.waitingOnRemove_ = false;
  38069. window__default["default"].clearTimeout(this.quotaExceededErrorRetryTimeout_);
  38070. this.quotaExceededErrorRetryTimeout_ = null;
  38071. }
  38072. checkForAbort_(requestId) {
  38073. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  38074. // callback that happens should reset the state to READY so that loading can continue.
  38075. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  38076. this.state = 'READY';
  38077. return true;
  38078. }
  38079. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  38080. return true;
  38081. }
  38082. return false;
  38083. }
  38084. /**
  38085. * set an error on the segment loader and null out any pending segements
  38086. *
  38087. * @param {Error} error the error to set on the SegmentLoader
  38088. * @return {Error} the error that was set or that is currently set
  38089. */
  38090. error(error) {
  38091. if (typeof error !== 'undefined') {
  38092. this.logger_('error occurred:', error);
  38093. this.error_ = error;
  38094. }
  38095. this.pendingSegment_ = null;
  38096. return this.error_;
  38097. }
  38098. endOfStream() {
  38099. this.ended_ = true;
  38100. if (this.transmuxer_) {
  38101. // need to clear out any cached data to prepare for the new segment
  38102. segmentTransmuxer.reset(this.transmuxer_);
  38103. }
  38104. this.gopBuffer_.length = 0;
  38105. this.pause();
  38106. this.trigger('ended');
  38107. }
  38108. /**
  38109. * Indicates which time ranges are buffered
  38110. *
  38111. * @return {TimeRange}
  38112. * TimeRange object representing the current buffered ranges
  38113. */
  38114. buffered_() {
  38115. const trackInfo = this.getMediaInfo_();
  38116. if (!this.sourceUpdater_ || !trackInfo) {
  38117. return createTimeRanges();
  38118. }
  38119. if (this.loaderType_ === 'main') {
  38120. const {
  38121. hasAudio,
  38122. hasVideo,
  38123. isMuxed
  38124. } = trackInfo;
  38125. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  38126. return this.sourceUpdater_.buffered();
  38127. }
  38128. if (hasVideo) {
  38129. return this.sourceUpdater_.videoBuffered();
  38130. }
  38131. } // One case that can be ignored for now is audio only with alt audio,
  38132. // as we don't yet have proper support for that.
  38133. return this.sourceUpdater_.audioBuffered();
  38134. }
  38135. /**
  38136. * Gets and sets init segment for the provided map
  38137. *
  38138. * @param {Object} map
  38139. * The map object representing the init segment to get or set
  38140. * @param {boolean=} set
  38141. * If true, the init segment for the provided map should be saved
  38142. * @return {Object}
  38143. * map object for desired init segment
  38144. */
  38145. initSegmentForMap(map, set = false) {
  38146. if (!map) {
  38147. return null;
  38148. }
  38149. const id = initSegmentId(map);
  38150. let storedMap = this.initSegments_[id];
  38151. if (set && !storedMap && map.bytes) {
  38152. this.initSegments_[id] = storedMap = {
  38153. resolvedUri: map.resolvedUri,
  38154. byterange: map.byterange,
  38155. bytes: map.bytes,
  38156. tracks: map.tracks,
  38157. timescales: map.timescales
  38158. };
  38159. }
  38160. return storedMap || map;
  38161. }
  38162. /**
  38163. * Gets and sets key for the provided key
  38164. *
  38165. * @param {Object} key
  38166. * The key object representing the key to get or set
  38167. * @param {boolean=} set
  38168. * If true, the key for the provided key should be saved
  38169. * @return {Object}
  38170. * Key object for desired key
  38171. */
  38172. segmentKey(key, set = false) {
  38173. if (!key) {
  38174. return null;
  38175. }
  38176. const id = segmentKeyId(key);
  38177. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  38178. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  38179. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  38180. this.keyCache_[id] = storedKey = {
  38181. resolvedUri: key.resolvedUri,
  38182. bytes: key.bytes
  38183. };
  38184. }
  38185. const result = {
  38186. resolvedUri: (storedKey || key).resolvedUri
  38187. };
  38188. if (storedKey) {
  38189. result.bytes = storedKey.bytes;
  38190. }
  38191. return result;
  38192. }
  38193. /**
  38194. * Returns true if all configuration required for loading is present, otherwise false.
  38195. *
  38196. * @return {boolean} True if the all configuration is ready for loading
  38197. * @private
  38198. */
  38199. couldBeginLoading_() {
  38200. return this.playlist_ && !this.paused();
  38201. }
  38202. /**
  38203. * load a playlist and start to fill the buffer
  38204. */
  38205. load() {
  38206. // un-pause
  38207. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  38208. // specified
  38209. if (!this.playlist_) {
  38210. return;
  38211. } // if all the configuration is ready, initialize and begin loading
  38212. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  38213. return this.init_();
  38214. } // if we're in the middle of processing a segment already, don't
  38215. // kick off an additional segment request
  38216. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  38217. return;
  38218. }
  38219. this.state = 'READY';
  38220. }
  38221. /**
  38222. * Once all the starting parameters have been specified, begin
  38223. * operation. This method should only be invoked from the INIT
  38224. * state.
  38225. *
  38226. * @private
  38227. */
  38228. init_() {
  38229. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  38230. // audio data from the muxed content should be removed
  38231. this.resetEverything();
  38232. return this.monitorBuffer_();
  38233. }
  38234. /**
  38235. * set a playlist on the segment loader
  38236. *
  38237. * @param {PlaylistLoader} media the playlist to set on the segment loader
  38238. */
  38239. playlist(newPlaylist, options = {}) {
  38240. if (!newPlaylist) {
  38241. return;
  38242. }
  38243. const oldPlaylist = this.playlist_;
  38244. const segmentInfo = this.pendingSegment_;
  38245. this.playlist_ = newPlaylist;
  38246. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  38247. // is always our zero-time so force a sync update each time the playlist
  38248. // is refreshed from the server
  38249. //
  38250. // Use the INIT state to determine if playback has started, as the playlist sync info
  38251. // should be fixed once requests begin (as sync points are generated based on sync
  38252. // info), but not before then.
  38253. if (this.state === 'INIT') {
  38254. newPlaylist.syncInfo = {
  38255. mediaSequence: newPlaylist.mediaSequence,
  38256. time: 0
  38257. }; // Setting the date time mapping means mapping the program date time (if available)
  38258. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  38259. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  38260. // be updated as the playlist is refreshed before the loader starts loading, the
  38261. // program date time mapping needs to be updated as well.
  38262. //
  38263. // This mapping is only done for the main loader because a program date time should
  38264. // map equivalently between playlists.
  38265. if (this.loaderType_ === 'main') {
  38266. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  38267. }
  38268. }
  38269. let oldId = null;
  38270. if (oldPlaylist) {
  38271. if (oldPlaylist.id) {
  38272. oldId = oldPlaylist.id;
  38273. } else if (oldPlaylist.uri) {
  38274. oldId = oldPlaylist.uri;
  38275. }
  38276. }
  38277. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  38278. // in LIVE, we always want to update with new playlists (including refreshes)
  38279. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  38280. // buffering now
  38281. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  38282. return this.init_();
  38283. }
  38284. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  38285. if (this.mediaIndex !== null) {
  38286. // we must reset/resync the segment loader when we switch renditions and
  38287. // the segment loader is already synced to the previous rendition
  38288. // on playlist changes we want it to be possible to fetch
  38289. // at the buffer for vod but not for live. So we use resetLoader
  38290. // for live and resyncLoader for vod. We want this because
  38291. // if a playlist uses independent and non-independent segments/parts the
  38292. // buffer may not accurately reflect the next segment that we should try
  38293. // downloading.
  38294. if (!newPlaylist.endList) {
  38295. this.resetLoader();
  38296. } else {
  38297. this.resyncLoader();
  38298. }
  38299. }
  38300. this.currentMediaInfo_ = void 0;
  38301. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  38302. return;
  38303. } // we reloaded the same playlist so we are in a live scenario
  38304. // and we will likely need to adjust the mediaIndex
  38305. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  38306. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  38307. // this is important because we can abort a request and this value must be
  38308. // equal to the last appended mediaIndex
  38309. if (this.mediaIndex !== null) {
  38310. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  38311. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  38312. // new playlist was incremented by 1.
  38313. if (this.mediaIndex < 0) {
  38314. this.mediaIndex = null;
  38315. this.partIndex = null;
  38316. } else {
  38317. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  38318. // unless parts fell off of the playlist for this segment.
  38319. // In that case we need to reset partIndex and resync
  38320. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  38321. const mediaIndex = this.mediaIndex;
  38322. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  38323. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  38324. // as the part was dropped from our current playlists segment.
  38325. // The mediaIndex will still be valid so keep that around.
  38326. this.mediaIndex = mediaIndex;
  38327. }
  38328. }
  38329. } // update the mediaIndex on the SegmentInfo object
  38330. // this is important because we will update this.mediaIndex with this value
  38331. // in `handleAppendsDone_` after the segment has been successfully appended
  38332. if (segmentInfo) {
  38333. segmentInfo.mediaIndex -= mediaSequenceDiff;
  38334. if (segmentInfo.mediaIndex < 0) {
  38335. segmentInfo.mediaIndex = null;
  38336. segmentInfo.partIndex = null;
  38337. } else {
  38338. // we need to update the referenced segment so that timing information is
  38339. // saved for the new playlist's segment, however, if the segment fell off the
  38340. // playlist, we can leave the old reference and just lose the timing info
  38341. if (segmentInfo.mediaIndex >= 0) {
  38342. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  38343. }
  38344. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  38345. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  38346. }
  38347. }
  38348. }
  38349. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  38350. }
  38351. /**
  38352. * Prevent the loader from fetching additional segments. If there
  38353. * is a segment request outstanding, it will finish processing
  38354. * before the loader halts. A segment loader can be unpaused by
  38355. * calling load().
  38356. */
  38357. pause() {
  38358. if (this.checkBufferTimeout_) {
  38359. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  38360. this.checkBufferTimeout_ = null;
  38361. }
  38362. }
  38363. /**
  38364. * Returns whether the segment loader is fetching additional
  38365. * segments when given the opportunity. This property can be
  38366. * modified through calls to pause() and load().
  38367. */
  38368. paused() {
  38369. return this.checkBufferTimeout_ === null;
  38370. }
  38371. /**
  38372. * Delete all the buffered data and reset the SegmentLoader
  38373. *
  38374. * @param {Function} [done] an optional callback to be executed when the remove
  38375. * operation is complete
  38376. */
  38377. resetEverything(done) {
  38378. this.ended_ = false;
  38379. this.activeInitSegmentId_ = null;
  38380. this.appendInitSegment_ = {
  38381. audio: true,
  38382. video: true
  38383. };
  38384. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  38385. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  38386. // we then clamp the value to duration if necessary.
  38387. this.remove(0, Infinity, done); // clears fmp4 captions
  38388. if (this.transmuxer_) {
  38389. this.transmuxer_.postMessage({
  38390. action: 'clearAllMp4Captions'
  38391. }); // reset the cache in the transmuxer
  38392. this.transmuxer_.postMessage({
  38393. action: 'reset'
  38394. });
  38395. }
  38396. }
  38397. /**
  38398. * Force the SegmentLoader to resync and start loading around the currentTime instead
  38399. * of starting at the end of the buffer
  38400. *
  38401. * Useful for fast quality changes
  38402. */
  38403. resetLoader() {
  38404. this.fetchAtBuffer_ = false;
  38405. this.resyncLoader();
  38406. }
  38407. /**
  38408. * Force the SegmentLoader to restart synchronization and make a conservative guess
  38409. * before returning to the simple walk-forward method
  38410. */
  38411. resyncLoader() {
  38412. if (this.transmuxer_) {
  38413. // need to clear out any cached data to prepare for the new segment
  38414. segmentTransmuxer.reset(this.transmuxer_);
  38415. }
  38416. this.mediaIndex = null;
  38417. this.partIndex = null;
  38418. this.syncPoint_ = null;
  38419. this.isPendingTimestampOffset_ = false;
  38420. this.callQueue_ = [];
  38421. this.loadQueue_ = [];
  38422. this.metadataQueue_.id3 = [];
  38423. this.metadataQueue_.caption = [];
  38424. this.abort();
  38425. if (this.transmuxer_) {
  38426. this.transmuxer_.postMessage({
  38427. action: 'clearParsedMp4Captions'
  38428. });
  38429. }
  38430. }
  38431. /**
  38432. * Remove any data in the source buffer between start and end times
  38433. *
  38434. * @param {number} start - the start time of the region to remove from the buffer
  38435. * @param {number} end - the end time of the region to remove from the buffer
  38436. * @param {Function} [done] - an optional callback to be executed when the remove
  38437. * @param {boolean} force - force all remove operations to happen
  38438. * operation is complete
  38439. */
  38440. remove(start, end, done = () => {}, force = false) {
  38441. // clamp end to duration if we need to remove everything.
  38442. // This is due to a browser bug that causes issues if we remove to Infinity.
  38443. // videojs/videojs-contrib-hls#1225
  38444. if (end === Infinity) {
  38445. end = this.duration_();
  38446. } // skip removes that would throw an error
  38447. // commonly happens during a rendition switch at the start of a video
  38448. // from start 0 to end 0
  38449. if (end <= start) {
  38450. this.logger_('skipping remove because end ${end} is <= start ${start}');
  38451. return;
  38452. }
  38453. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  38454. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  38455. return;
  38456. } // set it to one to complete this function's removes
  38457. let removesRemaining = 1;
  38458. const removeFinished = () => {
  38459. removesRemaining--;
  38460. if (removesRemaining === 0) {
  38461. done();
  38462. }
  38463. };
  38464. if (force || !this.audioDisabled_) {
  38465. removesRemaining++;
  38466. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  38467. } // While it would be better to only remove video if the main loader has video, this
  38468. // should be safe with audio only as removeVideo will call back even if there's no
  38469. // video buffer.
  38470. //
  38471. // In theory we can check to see if there's video before calling the remove, but in
  38472. // the event that we're switching between renditions and from video to audio only
  38473. // (when we add support for that), we may need to clear the video contents despite
  38474. // what the new media will contain.
  38475. if (force || this.loaderType_ === 'main') {
  38476. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  38477. removesRemaining++;
  38478. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  38479. } // remove any captions and ID3 tags
  38480. for (const track in this.inbandTextTracks_) {
  38481. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  38482. }
  38483. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  38484. removeFinished();
  38485. }
  38486. /**
  38487. * (re-)schedule monitorBufferTick_ to run as soon as possible
  38488. *
  38489. * @private
  38490. */
  38491. monitorBuffer_() {
  38492. if (this.checkBufferTimeout_) {
  38493. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  38494. }
  38495. this.checkBufferTimeout_ = window__default["default"].setTimeout(this.monitorBufferTick_.bind(this), 1);
  38496. }
  38497. /**
  38498. * As long as the SegmentLoader is in the READY state, periodically
  38499. * invoke fillBuffer_().
  38500. *
  38501. * @private
  38502. */
  38503. monitorBufferTick_() {
  38504. if (this.state === 'READY') {
  38505. this.fillBuffer_();
  38506. }
  38507. if (this.checkBufferTimeout_) {
  38508. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  38509. }
  38510. this.checkBufferTimeout_ = window__default["default"].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  38511. }
  38512. /**
  38513. * fill the buffer with segements unless the sourceBuffers are
  38514. * currently updating
  38515. *
  38516. * Note: this function should only ever be called by monitorBuffer_
  38517. * and never directly
  38518. *
  38519. * @private
  38520. */
  38521. fillBuffer_() {
  38522. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  38523. // except when we're ready for the next segment, this check can most likely be removed
  38524. if (this.sourceUpdater_.updating()) {
  38525. return;
  38526. } // see if we need to begin loading immediately
  38527. const segmentInfo = this.chooseNextRequest_();
  38528. if (!segmentInfo) {
  38529. return;
  38530. }
  38531. if (typeof segmentInfo.timestampOffset === 'number') {
  38532. this.isPendingTimestampOffset_ = false;
  38533. this.timelineChangeController_.pendingTimelineChange({
  38534. type: this.loaderType_,
  38535. from: this.currentTimeline_,
  38536. to: segmentInfo.timeline
  38537. });
  38538. }
  38539. this.loadSegment_(segmentInfo);
  38540. }
  38541. /**
  38542. * Determines if we should call endOfStream on the media source based
  38543. * on the state of the buffer or if appened segment was the final
  38544. * segment in the playlist.
  38545. *
  38546. * @param {number} [mediaIndex] the media index of segment we last appended
  38547. * @param {Object} [playlist] a media playlist object
  38548. * @return {boolean} do we need to call endOfStream on the MediaSource
  38549. */
  38550. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  38551. if (!playlist || !this.mediaSource_) {
  38552. return false;
  38553. }
  38554. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  38555. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  38556. const appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
  38557. // so that MediaSources can trigger the `ended` event when it runs out of
  38558. // buffered data instead of waiting for me
  38559. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  38560. }
  38561. /**
  38562. * Determines what request should be made given current segment loader state.
  38563. *
  38564. * @return {Object} a request object that describes the segment/part to load
  38565. */
  38566. chooseNextRequest_() {
  38567. const buffered = this.buffered_();
  38568. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  38569. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  38570. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  38571. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  38572. const segments = this.playlist_.segments; // return no segment if:
  38573. // 1. we don't have segments
  38574. // 2. The video has not yet played and we already downloaded a segment
  38575. // 3. we already have enough buffered time
  38576. if (!segments.length || preloaded || haveEnoughBuffer) {
  38577. return null;
  38578. }
  38579. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  38580. const next = {
  38581. partIndex: null,
  38582. mediaIndex: null,
  38583. startOfSegment: null,
  38584. playlist: this.playlist_,
  38585. isSyncRequest: Boolean(!this.syncPoint_)
  38586. };
  38587. if (next.isSyncRequest) {
  38588. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  38589. } else if (this.mediaIndex !== null) {
  38590. const segment = segments[this.mediaIndex];
  38591. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  38592. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  38593. if (segment.parts && segment.parts[partIndex + 1]) {
  38594. next.mediaIndex = this.mediaIndex;
  38595. next.partIndex = partIndex + 1;
  38596. } else {
  38597. next.mediaIndex = this.mediaIndex + 1;
  38598. }
  38599. } else {
  38600. // Find the segment containing the end of the buffer or current time.
  38601. const {
  38602. segmentIndex,
  38603. startTime,
  38604. partIndex
  38605. } = Playlist.getMediaInfoForTime({
  38606. exactManifestTimings: this.exactManifestTimings,
  38607. playlist: this.playlist_,
  38608. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  38609. startingPartIndex: this.syncPoint_.partIndex,
  38610. startingSegmentIndex: this.syncPoint_.segmentIndex,
  38611. startTime: this.syncPoint_.time
  38612. });
  38613. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  38614. next.mediaIndex = segmentIndex;
  38615. next.startOfSegment = startTime;
  38616. next.partIndex = partIndex;
  38617. }
  38618. const nextSegment = segments[next.mediaIndex];
  38619. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  38620. // the next partIndex is invalid do not choose a next segment.
  38621. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  38622. return null;
  38623. } // if the next segment has parts, and we don't have a partIndex.
  38624. // Set partIndex to 0
  38625. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  38626. next.partIndex = 0;
  38627. nextPart = nextSegment.parts[0];
  38628. } // if we have no buffered data then we need to make sure
  38629. // that the next part we append is "independent" if possible.
  38630. // So we check if the previous part is independent, and request
  38631. // it if it is.
  38632. if (!bufferedTime && nextPart && !nextPart.independent) {
  38633. if (next.partIndex === 0) {
  38634. const lastSegment = segments[next.mediaIndex - 1];
  38635. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  38636. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  38637. next.mediaIndex -= 1;
  38638. next.partIndex = lastSegment.parts.length - 1;
  38639. next.independent = 'previous segment';
  38640. }
  38641. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  38642. next.partIndex -= 1;
  38643. next.independent = 'previous part';
  38644. }
  38645. }
  38646. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  38647. // 1. this is the last segment in the playlist
  38648. // 2. end of stream has been called on the media source already
  38649. // 3. the player is not seeking
  38650. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  38651. return null;
  38652. }
  38653. return this.generateSegmentInfo_(next);
  38654. }
  38655. generateSegmentInfo_(options) {
  38656. const {
  38657. independent,
  38658. playlist,
  38659. mediaIndex,
  38660. startOfSegment,
  38661. isSyncRequest,
  38662. partIndex,
  38663. forceTimestampOffset,
  38664. getMediaInfoForTime
  38665. } = options;
  38666. const segment = playlist.segments[mediaIndex];
  38667. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  38668. const segmentInfo = {
  38669. requestId: 'segment-loader-' + Math.random(),
  38670. // resolve the segment URL relative to the playlist
  38671. uri: part && part.resolvedUri || segment.resolvedUri,
  38672. // the segment's mediaIndex at the time it was requested
  38673. mediaIndex,
  38674. partIndex: part ? partIndex : null,
  38675. // whether or not to update the SegmentLoader's state with this
  38676. // segment's mediaIndex
  38677. isSyncRequest,
  38678. startOfSegment,
  38679. // the segment's playlist
  38680. playlist,
  38681. // unencrypted bytes of the segment
  38682. bytes: null,
  38683. // when a key is defined for this segment, the encrypted bytes
  38684. encryptedBytes: null,
  38685. // The target timestampOffset for this segment when we append it
  38686. // to the source buffer
  38687. timestampOffset: null,
  38688. // The timeline that the segment is in
  38689. timeline: segment.timeline,
  38690. // The expected duration of the segment in seconds
  38691. duration: part && part.duration || segment.duration,
  38692. // retain the segment in case the playlist updates while doing an async process
  38693. segment,
  38694. part,
  38695. byteLength: 0,
  38696. transmuxer: this.transmuxer_,
  38697. // type of getMediaInfoForTime that was used to get this segment
  38698. getMediaInfoForTime,
  38699. independent
  38700. };
  38701. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  38702. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  38703. segmentTimeline: segment.timeline,
  38704. currentTimeline: this.currentTimeline_,
  38705. startOfSegment,
  38706. buffered: this.buffered_(),
  38707. overrideCheck
  38708. });
  38709. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  38710. if (typeof audioBufferedEnd === 'number') {
  38711. // since the transmuxer is using the actual timing values, but the buffer is
  38712. // adjusted by the timestamp offset, we must adjust the value here
  38713. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  38714. }
  38715. if (this.sourceUpdater_.videoBuffered().length) {
  38716. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_,
  38717. // since the transmuxer is using the actual timing values, but the time is
  38718. // adjusted by the timestmap offset, we must adjust the value here
  38719. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  38720. }
  38721. return segmentInfo;
  38722. } // get the timestampoffset for a segment,
  38723. // added so that vtt segment loader can override and prevent
  38724. // adding timestamp offsets.
  38725. timestampOffsetForSegment_(options) {
  38726. return timestampOffsetForSegment(options);
  38727. }
  38728. /**
  38729. * Determines if the network has enough bandwidth to complete the current segment
  38730. * request in a timely manner. If not, the request will be aborted early and bandwidth
  38731. * updated to trigger a playlist switch.
  38732. *
  38733. * @param {Object} stats
  38734. * Object containing stats about the request timing and size
  38735. * @private
  38736. */
  38737. earlyAbortWhenNeeded_(stats) {
  38738. if (this.vhs_.tech_.paused() ||
  38739. // Don't abort if the current playlist is on the lowestEnabledRendition
  38740. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  38741. // the lowestEnabledRendition.
  38742. !this.xhrOptions_.timeout ||
  38743. // Don't abort if we have no bandwidth information to estimate segment sizes
  38744. !this.playlist_.attributes.BANDWIDTH) {
  38745. return;
  38746. } // Wait at least 1 second since the first byte of data has been received before
  38747. // using the calculated bandwidth from the progress event to allow the bitrate
  38748. // to stabilize
  38749. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  38750. return;
  38751. }
  38752. const currentTime = this.currentTime_();
  38753. const measuredBandwidth = stats.bandwidth;
  38754. const segmentDuration = this.pendingSegment_.duration;
  38755. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  38756. // if we are only left with less than 1 second when the request completes.
  38757. // A negative timeUntilRebuffering indicates we are already rebuffering
  38758. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  38759. // is larger than the estimated time until the player runs out of forward buffer
  38760. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  38761. return;
  38762. }
  38763. const switchCandidate = minRebufferMaxBandwidthSelector({
  38764. main: this.vhs_.playlists.main,
  38765. currentTime,
  38766. bandwidth: measuredBandwidth,
  38767. duration: this.duration_(),
  38768. segmentDuration,
  38769. timeUntilRebuffer: timeUntilRebuffer$1,
  38770. currentTimeline: this.currentTimeline_,
  38771. syncController: this.syncController_
  38772. });
  38773. if (!switchCandidate) {
  38774. return;
  38775. }
  38776. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  38777. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  38778. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  38779. // potential round trip time of the new request so that we are not too aggressive
  38780. // with switching to a playlist that might save us a fraction of a second.
  38781. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  38782. minimumTimeSaving = 1;
  38783. }
  38784. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  38785. return;
  38786. } // set the bandwidth to that of the desired playlist being sure to scale by
  38787. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  38788. // don't trigger a bandwidthupdate as the bandwidth is artifial
  38789. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  38790. this.trigger('earlyabort');
  38791. }
  38792. handleAbort_(segmentInfo) {
  38793. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  38794. this.mediaRequestsAborted += 1;
  38795. }
  38796. /**
  38797. * XHR `progress` event handler
  38798. *
  38799. * @param {Event}
  38800. * The XHR `progress` event
  38801. * @param {Object} simpleSegment
  38802. * A simplified segment object copy
  38803. * @private
  38804. */
  38805. handleProgress_(event, simpleSegment) {
  38806. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38807. if (this.checkForAbort_(simpleSegment.requestId)) {
  38808. return;
  38809. }
  38810. this.trigger('progress');
  38811. }
  38812. handleTrackInfo_(simpleSegment, trackInfo) {
  38813. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38814. if (this.checkForAbort_(simpleSegment.requestId)) {
  38815. return;
  38816. }
  38817. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  38818. return;
  38819. }
  38820. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  38821. // Guard against cases where we're not getting track info at all until we are
  38822. // certain that all streams will provide it.
  38823. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  38824. this.appendInitSegment_ = {
  38825. audio: true,
  38826. video: true
  38827. };
  38828. this.startingMediaInfo_ = trackInfo;
  38829. this.currentMediaInfo_ = trackInfo;
  38830. this.logger_('trackinfo update', trackInfo);
  38831. this.trigger('trackinfo');
  38832. } // trackinfo may cause an abort if the trackinfo
  38833. // causes a codec change to an unsupported codec.
  38834. if (this.checkForAbort_(simpleSegment.requestId)) {
  38835. return;
  38836. } // set trackinfo on the pending segment so that
  38837. // it can append.
  38838. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  38839. if (this.hasEnoughInfoToAppend_()) {
  38840. this.processCallQueue_();
  38841. }
  38842. }
  38843. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  38844. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38845. if (this.checkForAbort_(simpleSegment.requestId)) {
  38846. return;
  38847. }
  38848. const segmentInfo = this.pendingSegment_;
  38849. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  38850. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  38851. segmentInfo[timingInfoProperty][timeType] = time;
  38852. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  38853. if (this.hasEnoughInfoToAppend_()) {
  38854. this.processCallQueue_();
  38855. }
  38856. }
  38857. handleCaptions_(simpleSegment, captionData) {
  38858. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38859. if (this.checkForAbort_(simpleSegment.requestId)) {
  38860. return;
  38861. } // This could only happen with fmp4 segments, but
  38862. // should still not happen in general
  38863. if (captionData.length === 0) {
  38864. this.logger_('SegmentLoader received no captions from a caption event');
  38865. return;
  38866. }
  38867. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  38868. // can be adjusted by the timestamp offset
  38869. if (!segmentInfo.hasAppendedData_) {
  38870. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  38871. return;
  38872. }
  38873. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  38874. const captionTracks = {}; // get total start/end and captions for each track/stream
  38875. captionData.forEach(caption => {
  38876. // caption.stream is actually a track name...
  38877. // set to the existing values in tracks or default values
  38878. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  38879. // Infinity, as any other value will be less than this
  38880. startTime: Infinity,
  38881. captions: [],
  38882. // 0 as an other value will be more than this
  38883. endTime: 0
  38884. };
  38885. const captionTrack = captionTracks[caption.stream];
  38886. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  38887. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  38888. captionTrack.captions.push(caption);
  38889. });
  38890. Object.keys(captionTracks).forEach(trackName => {
  38891. const {
  38892. startTime,
  38893. endTime,
  38894. captions
  38895. } = captionTracks[trackName];
  38896. const inbandTextTracks = this.inbandTextTracks_;
  38897. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  38898. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  38899. // We do this because a rendition change that also changes the timescale for captions
  38900. // will result in captions being re-parsed for certain segments. If we add them again
  38901. // without clearing we will have two of the same captions visible.
  38902. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  38903. addCaptionData({
  38904. captionArray: captions,
  38905. inbandTextTracks,
  38906. timestampOffset
  38907. });
  38908. }); // Reset stored captions since we added parsed
  38909. // captions to a text track at this point
  38910. if (this.transmuxer_) {
  38911. this.transmuxer_.postMessage({
  38912. action: 'clearParsedMp4Captions'
  38913. });
  38914. }
  38915. }
  38916. handleId3_(simpleSegment, id3Frames, dispatchType) {
  38917. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38918. if (this.checkForAbort_(simpleSegment.requestId)) {
  38919. return;
  38920. }
  38921. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  38922. if (!segmentInfo.hasAppendedData_) {
  38923. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  38924. return;
  38925. }
  38926. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  38927. // audio/video source with a metadata track, and an alt audio with a metadata track.
  38928. // However, this probably won't happen, and if it does it can be handled then.
  38929. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  38930. addMetadata({
  38931. inbandTextTracks: this.inbandTextTracks_,
  38932. metadataArray: id3Frames,
  38933. timestampOffset,
  38934. videoDuration: this.duration_()
  38935. });
  38936. }
  38937. processMetadataQueue_() {
  38938. this.metadataQueue_.id3.forEach(fn => fn());
  38939. this.metadataQueue_.caption.forEach(fn => fn());
  38940. this.metadataQueue_.id3 = [];
  38941. this.metadataQueue_.caption = [];
  38942. }
  38943. processCallQueue_() {
  38944. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  38945. // functions may check the length of the load queue and default to pushing themselves
  38946. // back onto the queue.
  38947. this.callQueue_ = [];
  38948. callQueue.forEach(fun => fun());
  38949. }
  38950. processLoadQueue_() {
  38951. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  38952. // functions may check the length of the load queue and default to pushing themselves
  38953. // back onto the queue.
  38954. this.loadQueue_ = [];
  38955. loadQueue.forEach(fun => fun());
  38956. }
  38957. /**
  38958. * Determines whether the loader has enough info to load the next segment.
  38959. *
  38960. * @return {boolean}
  38961. * Whether or not the loader has enough info to load the next segment
  38962. */
  38963. hasEnoughInfoToLoad_() {
  38964. // Since primary timing goes by video, only the audio loader potentially needs to wait
  38965. // to load.
  38966. if (this.loaderType_ !== 'audio') {
  38967. return true;
  38968. }
  38969. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  38970. // enough info to load.
  38971. if (!segmentInfo) {
  38972. return false;
  38973. } // The first segment can and should be loaded immediately so that source buffers are
  38974. // created together (before appending). Source buffer creation uses the presence of
  38975. // audio and video data to determine whether to create audio/video source buffers, and
  38976. // uses processed (transmuxed or parsed) media to determine the types required.
  38977. if (!this.getCurrentMediaInfo_()) {
  38978. return true;
  38979. }
  38980. if (
  38981. // Technically, instead of waiting to load a segment on timeline changes, a segment
  38982. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  38983. // But in practice, there are a few reasons why it is better to wait until a loader
  38984. // is ready to append that segment before requesting and downloading:
  38985. //
  38986. // 1. Because audio and main loaders cross discontinuities together, if this loader
  38987. // is waiting for the other to catch up, then instead of requesting another
  38988. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  38989. // allotted to the loader currently behind.
  38990. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  38991. // is ready to be processed or not, isolating the queueing behavior to the loader.
  38992. // 3. The audio loader bases some of its segment properties on timing information
  38993. // provided by the main loader, meaning that, if the logic for waiting on
  38994. // processing was in media-segment-request, then it would also need to know how
  38995. // to re-generate the segment information after the main loader caught up.
  38996. shouldWaitForTimelineChange({
  38997. timelineChangeController: this.timelineChangeController_,
  38998. currentTimeline: this.currentTimeline_,
  38999. segmentTimeline: segmentInfo.timeline,
  39000. loaderType: this.loaderType_,
  39001. audioDisabled: this.audioDisabled_
  39002. })) {
  39003. return false;
  39004. }
  39005. return true;
  39006. }
  39007. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  39008. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  39009. }
  39010. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  39011. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  39012. }
  39013. getPendingSegmentPlaylist() {
  39014. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  39015. }
  39016. hasEnoughInfoToAppend_() {
  39017. if (!this.sourceUpdater_.ready()) {
  39018. return false;
  39019. } // If content needs to be removed or the loader is waiting on an append reattempt,
  39020. // then no additional content should be appended until the prior append is resolved.
  39021. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  39022. return false;
  39023. }
  39024. const segmentInfo = this.pendingSegment_;
  39025. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  39026. // we do not have information on this specific
  39027. // segment yet
  39028. if (!segmentInfo || !trackInfo) {
  39029. return false;
  39030. }
  39031. const {
  39032. hasAudio,
  39033. hasVideo,
  39034. isMuxed
  39035. } = trackInfo;
  39036. if (hasVideo && !segmentInfo.videoTimingInfo) {
  39037. return false;
  39038. } // muxed content only relies on video timing information for now.
  39039. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  39040. return false;
  39041. }
  39042. if (shouldWaitForTimelineChange({
  39043. timelineChangeController: this.timelineChangeController_,
  39044. currentTimeline: this.currentTimeline_,
  39045. segmentTimeline: segmentInfo.timeline,
  39046. loaderType: this.loaderType_,
  39047. audioDisabled: this.audioDisabled_
  39048. })) {
  39049. return false;
  39050. }
  39051. return true;
  39052. }
  39053. handleData_(simpleSegment, result) {
  39054. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  39055. if (this.checkForAbort_(simpleSegment.requestId)) {
  39056. return;
  39057. } // If there's anything in the call queue, then this data came later and should be
  39058. // executed after the calls currently queued.
  39059. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  39060. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  39061. return;
  39062. }
  39063. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  39064. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  39065. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  39066. // logic may change behavior depending on the state, and changing state too early may
  39067. // inflate our estimates of bandwidth. In the future this should be re-examined to
  39068. // note more granular states.
  39069. // don't process and append data if the mediaSource is closed
  39070. if (this.mediaSource_.readyState === 'closed') {
  39071. return;
  39072. } // if this request included an initialization segment, save that data
  39073. // to the initSegment cache
  39074. if (simpleSegment.map) {
  39075. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  39076. segmentInfo.segment.map = simpleSegment.map;
  39077. } // if this request included a segment key, save that data in the cache
  39078. if (simpleSegment.key) {
  39079. this.segmentKey(simpleSegment.key, true);
  39080. }
  39081. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  39082. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  39083. if (segmentInfo.isFmp4) {
  39084. this.trigger('fmp4');
  39085. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  39086. } else {
  39087. const trackInfo = this.getCurrentMediaInfo_();
  39088. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  39089. let firstVideoFrameTimeForData;
  39090. if (useVideoTimingInfo) {
  39091. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  39092. } // Segment loader knows more about segment timing than the transmuxer (in certain
  39093. // aspects), so make any changes required for a more accurate start time.
  39094. // Don't set the end time yet, as the segment may not be finished processing.
  39095. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  39096. currentStart: segmentInfo.timingInfo.start,
  39097. playlist: segmentInfo.playlist,
  39098. mediaIndex: segmentInfo.mediaIndex,
  39099. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  39100. useVideoTimingInfo,
  39101. firstVideoFrameTimeForData,
  39102. videoTimingInfo: segmentInfo.videoTimingInfo,
  39103. audioTimingInfo: segmentInfo.audioTimingInfo
  39104. });
  39105. } // Init segments for audio and video only need to be appended in certain cases. Now
  39106. // that data is about to be appended, we can check the final cases to determine
  39107. // whether we should append an init segment.
  39108. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  39109. // as we use the start of the segment to offset the best guess (playlist provided)
  39110. // timestamp offset.
  39111. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  39112. // be appended or not.
  39113. if (segmentInfo.isSyncRequest) {
  39114. // first save/update our timing info for this segment.
  39115. // this is what allows us to choose an accurate segment
  39116. // and the main reason we make a sync request.
  39117. this.updateTimingInfoEnd_(segmentInfo);
  39118. this.syncController_.saveSegmentTimingInfo({
  39119. segmentInfo,
  39120. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  39121. });
  39122. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  39123. // after taking into account its timing info, do not append it.
  39124. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  39125. this.logger_('sync segment was incorrect, not appending');
  39126. return;
  39127. } // otherwise append it like any other segment as our guess was correct.
  39128. this.logger_('sync segment was correct, appending');
  39129. } // Save some state so that in the future anything waiting on first append (and/or
  39130. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  39131. // we need some notion of whether the timestamp offset or other relevant information
  39132. // has had a chance to be set.
  39133. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  39134. this.processMetadataQueue_();
  39135. this.appendData_(segmentInfo, result);
  39136. }
  39137. updateAppendInitSegmentStatus(segmentInfo, type) {
  39138. // alt audio doesn't manage timestamp offset
  39139. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' &&
  39140. // in the case that we're handling partial data, we don't want to append an init
  39141. // segment for each chunk
  39142. !segmentInfo.changedTimestampOffset) {
  39143. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  39144. // append init segments
  39145. this.appendInitSegment_ = {
  39146. audio: true,
  39147. video: true
  39148. };
  39149. }
  39150. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  39151. // make sure we append init segment on playlist changes, in case the media config
  39152. // changed
  39153. this.appendInitSegment_[type] = true;
  39154. }
  39155. }
  39156. getInitSegmentAndUpdateState_({
  39157. type,
  39158. initSegment,
  39159. map,
  39160. playlist
  39161. }) {
  39162. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  39163. // (Section 3) required to parse the applicable Media Segments. It applies to every
  39164. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  39165. // or until the end of the playlist."
  39166. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  39167. if (map) {
  39168. const id = initSegmentId(map);
  39169. if (this.activeInitSegmentId_ === id) {
  39170. // don't need to re-append the init segment if the ID matches
  39171. return null;
  39172. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  39173. // obtained) init segment
  39174. //
  39175. // this also caches the init segment for later use
  39176. initSegment = this.initSegmentForMap(map, true).bytes;
  39177. this.activeInitSegmentId_ = id;
  39178. } // We used to always prepend init segments for video, however, that shouldn't be
  39179. // necessary. Instead, we should only append on changes, similar to what we've always
  39180. // done for audio. This is more important (though may not be that important) for
  39181. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  39182. // appends.
  39183. if (initSegment && this.appendInitSegment_[type]) {
  39184. // Make sure we track the playlist that we last used for the init segment, so that
  39185. // we can re-append the init segment in the event that we get data from a new
  39186. // playlist. Discontinuities and track changes are handled in other sections.
  39187. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  39188. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  39189. // we are appending the muxer init segment
  39190. this.activeInitSegmentId_ = null;
  39191. return initSegment;
  39192. }
  39193. return null;
  39194. }
  39195. handleQuotaExceededError_({
  39196. segmentInfo,
  39197. type,
  39198. bytes
  39199. }, error) {
  39200. const audioBuffered = this.sourceUpdater_.audioBuffered();
  39201. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  39202. // should be cleared out during the buffer removals. However, log in case it helps
  39203. // debug.
  39204. if (audioBuffered.length > 1) {
  39205. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  39206. }
  39207. if (videoBuffered.length > 1) {
  39208. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  39209. }
  39210. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  39211. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  39212. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  39213. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  39214. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  39215. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  39216. // allow for appends of segments this size). In the future, it may be possible to
  39217. // split up the segment and append in pieces, but for now, error out this playlist
  39218. // in an attempt to switch to a more manageable rendition.
  39219. this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + `Appended byte length: ${bytes.byteLength}, ` + `audio buffer: ${timeRangesToArray(audioBuffered).join(', ')}, ` + `video buffer: ${timeRangesToArray(videoBuffered).join(', ')}, `);
  39220. this.error({
  39221. message: 'Quota exceeded error with append of a single segment of content',
  39222. excludeUntil: Infinity
  39223. });
  39224. this.trigger('error');
  39225. return;
  39226. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  39227. // that the segment-loader should block on future events until this one is handled, so
  39228. // that it doesn't keep moving onto further segments. Adding the call to the call
  39229. // queue will prevent further appends until waitingOnRemove_ and
  39230. // quotaExceededErrorRetryTimeout_ are cleared.
  39231. //
  39232. // Note that this will only block the current loader. In the case of demuxed content,
  39233. // the other load may keep filling as fast as possible. In practice, this should be
  39234. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  39235. // source buffer, or video fills without enough room for audio to append (and without
  39236. // the availability of clearing out seconds of back buffer to make room for audio).
  39237. // But it might still be good to handle this case in the future as a TODO.
  39238. this.waitingOnRemove_ = true;
  39239. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  39240. segmentInfo,
  39241. type,
  39242. bytes
  39243. }));
  39244. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  39245. // before retrying.
  39246. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  39247. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  39248. this.remove(0, timeToRemoveUntil, () => {
  39249. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  39250. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  39251. // attempts (since we can't clear less than the minimum)
  39252. this.quotaExceededErrorRetryTimeout_ = window__default["default"].setTimeout(() => {
  39253. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  39254. this.quotaExceededErrorRetryTimeout_ = null;
  39255. this.processCallQueue_();
  39256. }, MIN_BACK_BUFFER * 1000);
  39257. }, true);
  39258. }
  39259. handleAppendError_({
  39260. segmentInfo,
  39261. type,
  39262. bytes
  39263. }, error) {
  39264. // if there's no error, nothing to do
  39265. if (!error) {
  39266. return;
  39267. }
  39268. if (error.code === QUOTA_EXCEEDED_ERR) {
  39269. this.handleQuotaExceededError_({
  39270. segmentInfo,
  39271. type,
  39272. bytes
  39273. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  39274. // to trigger an append error.
  39275. return;
  39276. }
  39277. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  39278. this.error(`${type} append of ${bytes.length}b failed for segment ` + `#${segmentInfo.mediaIndex} in playlist ${segmentInfo.playlist.id}`); // If an append errors, we often can't recover.
  39279. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  39280. //
  39281. // Trigger a special error so that it can be handled separately from normal,
  39282. // recoverable errors.
  39283. this.trigger('appenderror');
  39284. }
  39285. appendToSourceBuffer_({
  39286. segmentInfo,
  39287. type,
  39288. initSegment,
  39289. data,
  39290. bytes
  39291. }) {
  39292. // If this is a re-append, bytes were already created and don't need to be recreated
  39293. if (!bytes) {
  39294. const segments = [data];
  39295. let byteLength = data.byteLength;
  39296. if (initSegment) {
  39297. // if the media initialization segment is changing, append it before the content
  39298. // segment
  39299. segments.unshift(initSegment);
  39300. byteLength += initSegment.byteLength;
  39301. } // Technically we should be OK appending the init segment separately, however, we
  39302. // haven't yet tested that, and prepending is how we have always done things.
  39303. bytes = concatSegments({
  39304. bytes: byteLength,
  39305. segments
  39306. });
  39307. }
  39308. this.sourceUpdater_.appendBuffer({
  39309. segmentInfo,
  39310. type,
  39311. bytes
  39312. }, this.handleAppendError_.bind(this, {
  39313. segmentInfo,
  39314. type,
  39315. bytes
  39316. }));
  39317. }
  39318. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  39319. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  39320. return;
  39321. }
  39322. const segment = this.pendingSegment_.segment;
  39323. const timingInfoProperty = `${type}TimingInfo`;
  39324. if (!segment[timingInfoProperty]) {
  39325. segment[timingInfoProperty] = {};
  39326. }
  39327. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  39328. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  39329. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  39330. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  39331. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  39332. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  39333. }
  39334. appendData_(segmentInfo, result) {
  39335. const {
  39336. type,
  39337. data
  39338. } = result;
  39339. if (!data || !data.byteLength) {
  39340. return;
  39341. }
  39342. if (type === 'audio' && this.audioDisabled_) {
  39343. return;
  39344. }
  39345. const initSegment = this.getInitSegmentAndUpdateState_({
  39346. type,
  39347. initSegment: result.initSegment,
  39348. playlist: segmentInfo.playlist,
  39349. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  39350. });
  39351. this.appendToSourceBuffer_({
  39352. segmentInfo,
  39353. type,
  39354. initSegment,
  39355. data
  39356. });
  39357. }
  39358. /**
  39359. * load a specific segment from a request into the buffer
  39360. *
  39361. * @private
  39362. */
  39363. loadSegment_(segmentInfo) {
  39364. this.state = 'WAITING';
  39365. this.pendingSegment_ = segmentInfo;
  39366. this.trimBackBuffer_(segmentInfo);
  39367. if (typeof segmentInfo.timestampOffset === 'number') {
  39368. if (this.transmuxer_) {
  39369. this.transmuxer_.postMessage({
  39370. action: 'clearAllMp4Captions'
  39371. });
  39372. }
  39373. }
  39374. if (!this.hasEnoughInfoToLoad_()) {
  39375. this.loadQueue_.push(() => {
  39376. // regenerate the audioAppendStart, timestampOffset, etc as they
  39377. // may have changed since this function was added to the queue.
  39378. const options = _extends__default["default"]({}, segmentInfo, {
  39379. forceTimestampOffset: true
  39380. });
  39381. _extends__default["default"](segmentInfo, this.generateSegmentInfo_(options));
  39382. this.isPendingTimestampOffset_ = false;
  39383. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  39384. });
  39385. return;
  39386. }
  39387. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  39388. }
  39389. updateTransmuxerAndRequestSegment_(segmentInfo) {
  39390. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  39391. // the transmuxer still needs to be updated before then.
  39392. //
  39393. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  39394. // offset must be passed to the transmuxer for stream correcting adjustments.
  39395. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  39396. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  39397. segmentInfo.gopsToAlignWith = [];
  39398. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  39399. this.transmuxer_.postMessage({
  39400. action: 'reset'
  39401. });
  39402. this.transmuxer_.postMessage({
  39403. action: 'setTimestampOffset',
  39404. timestampOffset: segmentInfo.timestampOffset
  39405. });
  39406. }
  39407. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  39408. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  39409. const isWalkingForward = this.mediaIndex !== null;
  39410. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ &&
  39411. // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  39412. // the first timeline
  39413. segmentInfo.timeline > 0;
  39414. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  39415. this.logger_(`Requesting ${segmentInfoString(segmentInfo)}`); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
  39416. // then this init segment has never been seen before and should be appended.
  39417. //
  39418. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  39419. // both to true and leave the decision of whether to append the init segment to append time.
  39420. if (simpleSegment.map && !simpleSegment.map.bytes) {
  39421. this.logger_('going to request init segment.');
  39422. this.appendInitSegment_ = {
  39423. video: true,
  39424. audio: true
  39425. };
  39426. }
  39427. segmentInfo.abortRequests = mediaSegmentRequest({
  39428. xhr: this.vhs_.xhr,
  39429. xhrOptions: this.xhrOptions_,
  39430. decryptionWorker: this.decrypter_,
  39431. segment: simpleSegment,
  39432. abortFn: this.handleAbort_.bind(this, segmentInfo),
  39433. progressFn: this.handleProgress_.bind(this),
  39434. trackInfoFn: this.handleTrackInfo_.bind(this),
  39435. timingInfoFn: this.handleTimingInfo_.bind(this),
  39436. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  39437. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  39438. captionsFn: this.handleCaptions_.bind(this),
  39439. isEndOfTimeline,
  39440. endedTimelineFn: () => {
  39441. this.logger_('received endedtimeline callback');
  39442. },
  39443. id3Fn: this.handleId3_.bind(this),
  39444. dataFn: this.handleData_.bind(this),
  39445. doneFn: this.segmentRequestFinished_.bind(this),
  39446. onTransmuxerLog: ({
  39447. message,
  39448. level,
  39449. stream
  39450. }) => {
  39451. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  39452. }
  39453. });
  39454. }
  39455. /**
  39456. * trim the back buffer so that we don't have too much data
  39457. * in the source buffer
  39458. *
  39459. * @private
  39460. *
  39461. * @param {Object} segmentInfo - the current segment
  39462. */
  39463. trimBackBuffer_(segmentInfo) {
  39464. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  39465. // buffer and a very conservative "garbage collector"
  39466. // We manually clear out the old buffer to ensure
  39467. // we don't trigger the QuotaExceeded error
  39468. // on the source buffer during subsequent appends
  39469. if (removeToTime > 0) {
  39470. this.remove(0, removeToTime);
  39471. }
  39472. }
  39473. /**
  39474. * created a simplified copy of the segment object with just the
  39475. * information necessary to perform the XHR and decryption
  39476. *
  39477. * @private
  39478. *
  39479. * @param {Object} segmentInfo - the current segment
  39480. * @return {Object} a simplified segment object copy
  39481. */
  39482. createSimplifiedSegmentObj_(segmentInfo) {
  39483. const segment = segmentInfo.segment;
  39484. const part = segmentInfo.part;
  39485. const simpleSegment = {
  39486. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  39487. byterange: part ? part.byterange : segment.byterange,
  39488. requestId: segmentInfo.requestId,
  39489. transmuxer: segmentInfo.transmuxer,
  39490. audioAppendStart: segmentInfo.audioAppendStart,
  39491. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  39492. part: segmentInfo.part
  39493. };
  39494. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  39495. if (previousSegment && previousSegment.timeline === segment.timeline) {
  39496. // The baseStartTime of a segment is used to handle rollover when probing the TS
  39497. // segment to retrieve timing information. Since the probe only looks at the media's
  39498. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  39499. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  39500. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  39501. // seconds of media time, so should be used here. The previous segment is used since
  39502. // the end of the previous segment should represent the beginning of the current
  39503. // segment, so long as they are on the same timeline.
  39504. if (previousSegment.videoTimingInfo) {
  39505. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  39506. } else if (previousSegment.audioTimingInfo) {
  39507. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  39508. }
  39509. }
  39510. if (segment.key) {
  39511. // if the media sequence is greater than 2^32, the IV will be incorrect
  39512. // assuming 10s segments, that would be about 1300 years
  39513. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  39514. simpleSegment.key = this.segmentKey(segment.key);
  39515. simpleSegment.key.iv = iv;
  39516. }
  39517. if (segment.map) {
  39518. simpleSegment.map = this.initSegmentForMap(segment.map);
  39519. }
  39520. return simpleSegment;
  39521. }
  39522. saveTransferStats_(stats) {
  39523. // every request counts as a media request even if it has been aborted
  39524. // or canceled due to a timeout
  39525. this.mediaRequests += 1;
  39526. if (stats) {
  39527. this.mediaBytesTransferred += stats.bytesReceived;
  39528. this.mediaTransferDuration += stats.roundTripTime;
  39529. }
  39530. }
  39531. saveBandwidthRelatedStats_(duration, stats) {
  39532. // byteLength will be used for throughput, and should be based on bytes receieved,
  39533. // which we only know at the end of the request and should reflect total bytes
  39534. // downloaded rather than just bytes processed from components of the segment
  39535. this.pendingSegment_.byteLength = stats.bytesReceived;
  39536. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39537. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  39538. return;
  39539. }
  39540. this.bandwidth = stats.bandwidth;
  39541. this.roundTrip = stats.roundTripTime;
  39542. }
  39543. handleTimeout_() {
  39544. // although the VTT segment loader bandwidth isn't really used, it's good to
  39545. // maintain functinality between segment loaders
  39546. this.mediaRequestsTimedout += 1;
  39547. this.bandwidth = 1;
  39548. this.roundTrip = NaN;
  39549. this.trigger('bandwidthupdate');
  39550. this.trigger('timeout');
  39551. }
  39552. /**
  39553. * Handle the callback from the segmentRequest function and set the
  39554. * associated SegmentLoader state and errors if necessary
  39555. *
  39556. * @private
  39557. */
  39558. segmentRequestFinished_(error, simpleSegment, result) {
  39559. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  39560. // check the call queue directly since this function doesn't need to deal with any
  39561. // data, and can continue even if the source buffers are not set up and we didn't get
  39562. // any data from the segment
  39563. if (this.callQueue_.length) {
  39564. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  39565. return;
  39566. }
  39567. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  39568. if (!this.pendingSegment_) {
  39569. return;
  39570. } // the request was aborted and the SegmentLoader has already started
  39571. // another request. this can happen when the timeout for an aborted
  39572. // request triggers due to a limitation in the XHR library
  39573. // do not count this as any sort of request or we risk double-counting
  39574. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  39575. return;
  39576. } // an error occurred from the active pendingSegment_ so reset everything
  39577. if (error) {
  39578. this.pendingSegment_ = null;
  39579. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  39580. if (error.code === REQUEST_ERRORS.ABORTED) {
  39581. return;
  39582. }
  39583. this.pause(); // the error is really just that at least one of the requests timed-out
  39584. // set the bandwidth to a very low value and trigger an ABR switch to
  39585. // take emergency action
  39586. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  39587. this.handleTimeout_();
  39588. return;
  39589. } // if control-flow has arrived here, then the error is real
  39590. // emit an error event to exclude the current playlist
  39591. this.mediaRequestsErrored += 1;
  39592. this.error(error);
  39593. this.trigger('error');
  39594. return;
  39595. }
  39596. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  39597. // generated for ABR purposes
  39598. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  39599. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  39600. if (result.gopInfo) {
  39601. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  39602. } // Although we may have already started appending on progress, we shouldn't switch the
  39603. // state away from loading until we are officially done loading the segment data.
  39604. this.state = 'APPENDING'; // used for testing
  39605. this.trigger('appending');
  39606. this.waitForAppendsToComplete_(segmentInfo);
  39607. }
  39608. setTimeMapping_(timeline) {
  39609. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  39610. if (timelineMapping !== null) {
  39611. this.timeMapping_ = timelineMapping;
  39612. }
  39613. }
  39614. updateMediaSecondsLoaded_(segment) {
  39615. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  39616. this.mediaSecondsLoaded += segment.end - segment.start;
  39617. } else {
  39618. this.mediaSecondsLoaded += segment.duration;
  39619. }
  39620. }
  39621. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  39622. if (timestampOffset === null) {
  39623. return false;
  39624. } // note that we're potentially using the same timestamp offset for both video and
  39625. // audio
  39626. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39627. return true;
  39628. }
  39629. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39630. return true;
  39631. }
  39632. return false;
  39633. }
  39634. trueSegmentStart_({
  39635. currentStart,
  39636. playlist,
  39637. mediaIndex,
  39638. firstVideoFrameTimeForData,
  39639. currentVideoTimestampOffset,
  39640. useVideoTimingInfo,
  39641. videoTimingInfo,
  39642. audioTimingInfo
  39643. }) {
  39644. if (typeof currentStart !== 'undefined') {
  39645. // if start was set once, keep using it
  39646. return currentStart;
  39647. }
  39648. if (!useVideoTimingInfo) {
  39649. return audioTimingInfo.start;
  39650. }
  39651. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  39652. // within that segment. Since the transmuxer maintains a cache of incomplete data
  39653. // from and/or the last frame seen, the start time may reflect a frame that starts
  39654. // in the previous segment. Check for that case and ensure the start time is
  39655. // accurate for the segment.
  39656. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  39657. return firstVideoFrameTimeForData;
  39658. }
  39659. return videoTimingInfo.start;
  39660. }
  39661. waitForAppendsToComplete_(segmentInfo) {
  39662. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  39663. if (!trackInfo) {
  39664. this.error({
  39665. message: 'No starting media returned, likely due to an unsupported media format.',
  39666. playlistExclusionDuration: Infinity
  39667. });
  39668. this.trigger('error');
  39669. return;
  39670. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  39671. // on each queue this loader is responsible for to ensure that the appends are
  39672. // complete.
  39673. const {
  39674. hasAudio,
  39675. hasVideo,
  39676. isMuxed
  39677. } = trackInfo;
  39678. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  39679. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  39680. segmentInfo.waitingOnAppends = 0; // segments with no data
  39681. if (!segmentInfo.hasAppendedData_) {
  39682. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  39683. // When there's no audio or video data in the segment, there's no audio or video
  39684. // timing information.
  39685. //
  39686. // If there's no audio or video timing information, then the timestamp offset
  39687. // can't be adjusted to the appropriate value for the transmuxer and source
  39688. // buffers.
  39689. //
  39690. // Therefore, the next segment should be used to set the timestamp offset.
  39691. this.isPendingTimestampOffset_ = true;
  39692. } // override settings for metadata only segments
  39693. segmentInfo.timingInfo = {
  39694. start: 0
  39695. };
  39696. segmentInfo.waitingOnAppends++;
  39697. if (!this.isPendingTimestampOffset_) {
  39698. // update the timestampoffset
  39699. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  39700. // no video/audio data.
  39701. this.processMetadataQueue_();
  39702. } // append is "done" instantly with no data.
  39703. this.checkAppendsDone_(segmentInfo);
  39704. return;
  39705. } // Since source updater could call back synchronously, do the increments first.
  39706. if (waitForVideo) {
  39707. segmentInfo.waitingOnAppends++;
  39708. }
  39709. if (waitForAudio) {
  39710. segmentInfo.waitingOnAppends++;
  39711. }
  39712. if (waitForVideo) {
  39713. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39714. }
  39715. if (waitForAudio) {
  39716. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39717. }
  39718. }
  39719. checkAppendsDone_(segmentInfo) {
  39720. if (this.checkForAbort_(segmentInfo.requestId)) {
  39721. return;
  39722. }
  39723. segmentInfo.waitingOnAppends--;
  39724. if (segmentInfo.waitingOnAppends === 0) {
  39725. this.handleAppendsDone_();
  39726. }
  39727. }
  39728. checkForIllegalMediaSwitch(trackInfo) {
  39729. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  39730. if (illegalMediaSwitchError) {
  39731. this.error({
  39732. message: illegalMediaSwitchError,
  39733. playlistExclusionDuration: Infinity
  39734. });
  39735. this.trigger('error');
  39736. return true;
  39737. }
  39738. return false;
  39739. }
  39740. updateSourceBufferTimestampOffset_(segmentInfo) {
  39741. if (segmentInfo.timestampOffset === null ||
  39742. // we don't yet have the start for whatever media type (video or audio) has
  39743. // priority, timing-wise, so we must wait
  39744. typeof segmentInfo.timingInfo.start !== 'number' ||
  39745. // already updated the timestamp offset for this segment
  39746. segmentInfo.changedTimestampOffset ||
  39747. // the alt audio loader should not be responsible for setting the timestamp offset
  39748. this.loaderType_ !== 'main') {
  39749. return;
  39750. }
  39751. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  39752. // the timing info here comes from video. In the event that the audio is longer than
  39753. // the video, this will trim the start of the audio.
  39754. // This also trims any offset from 0 at the beginning of the media
  39755. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  39756. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  39757. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  39758. timingInfo: segmentInfo.timingInfo
  39759. }); // In the event that there are part segment downloads, each will try to update the
  39760. // timestamp offset. Retaining this bit of state prevents us from updating in the
  39761. // future (within the same segment), however, there may be a better way to handle it.
  39762. segmentInfo.changedTimestampOffset = true;
  39763. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39764. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  39765. didChange = true;
  39766. }
  39767. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39768. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  39769. didChange = true;
  39770. }
  39771. if (didChange) {
  39772. this.trigger('timestampoffset');
  39773. }
  39774. }
  39775. getSegmentStartTimeForTimestampOffsetCalculation_({
  39776. videoTimingInfo,
  39777. audioTimingInfo,
  39778. timingInfo
  39779. }) {
  39780. if (!this.useDtsForTimestampOffset_) {
  39781. return timingInfo.start;
  39782. }
  39783. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  39784. return videoTimingInfo.transmuxedDecodeStart;
  39785. } // handle audio only
  39786. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  39787. return audioTimingInfo.transmuxedDecodeStart;
  39788. } // handle content not transmuxed (e.g., MP4)
  39789. return timingInfo.start;
  39790. }
  39791. updateTimingInfoEnd_(segmentInfo) {
  39792. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  39793. const trackInfo = this.getMediaInfo_();
  39794. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  39795. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  39796. if (!prioritizedTimingInfo) {
  39797. return;
  39798. }
  39799. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ?
  39800. // End time may not exist in a case where we aren't parsing the full segment (one
  39801. // current example is the case of fmp4), so use the rough duration to calculate an
  39802. // end time.
  39803. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  39804. }
  39805. /**
  39806. * callback to run when appendBuffer is finished. detects if we are
  39807. * in a good state to do things with the data we got, or if we need
  39808. * to wait for more
  39809. *
  39810. * @private
  39811. */
  39812. handleAppendsDone_() {
  39813. // appendsdone can cause an abort
  39814. if (this.pendingSegment_) {
  39815. this.trigger('appendsdone');
  39816. }
  39817. if (!this.pendingSegment_) {
  39818. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  39819. // all appending cases?
  39820. if (!this.paused()) {
  39821. this.monitorBuffer_();
  39822. }
  39823. return;
  39824. }
  39825. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  39826. // best to wait until all appends are done so we're sure that the primary media is
  39827. // finished (and we have its end time).
  39828. this.updateTimingInfoEnd_(segmentInfo);
  39829. if (this.shouldSaveSegmentTimingInfo_) {
  39830. // Timeline mappings should only be saved for the main loader. This is for multiple
  39831. // reasons:
  39832. //
  39833. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  39834. // and the main loader try to save the timeline mapping, whichever comes later
  39835. // will overwrite the first. In theory this is OK, as the mappings should be the
  39836. // same, however, it breaks for (2)
  39837. // 2) In the event of a live stream, the initial live point will make for a somewhat
  39838. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  39839. // the mapping will be off for one of the streams, dependent on which one was
  39840. // first saved (see (1)).
  39841. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  39842. //
  39843. // Since the audio loader will wait for the main loader to load the first segment,
  39844. // the main loader will save the first timeline mapping, and ensure that there won't
  39845. // be a case where audio loads two segments without saving a mapping (thus leading
  39846. // to missing segment timing info).
  39847. this.syncController_.saveSegmentTimingInfo({
  39848. segmentInfo,
  39849. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  39850. });
  39851. }
  39852. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  39853. if (segmentDurationMessage) {
  39854. if (segmentDurationMessage.severity === 'warn') {
  39855. videojs.log.warn(segmentDurationMessage.message);
  39856. } else {
  39857. this.logger_(segmentDurationMessage.message);
  39858. }
  39859. }
  39860. this.recordThroughput_(segmentInfo);
  39861. this.pendingSegment_ = null;
  39862. this.state = 'READY';
  39863. if (segmentInfo.isSyncRequest) {
  39864. this.trigger('syncinfoupdate'); // if the sync request was not appended
  39865. // then it was not the correct segment.
  39866. // throw it away and use the data it gave us
  39867. // to get the correct one.
  39868. if (!segmentInfo.hasAppendedData_) {
  39869. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  39870. return;
  39871. }
  39872. }
  39873. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  39874. this.addSegmentMetadataCue_(segmentInfo);
  39875. this.fetchAtBuffer_ = true;
  39876. if (this.currentTimeline_ !== segmentInfo.timeline) {
  39877. this.timelineChangeController_.lastTimelineChange({
  39878. type: this.loaderType_,
  39879. from: this.currentTimeline_,
  39880. to: segmentInfo.timeline
  39881. }); // If audio is not disabled, the main segment loader is responsible for updating
  39882. // the audio timeline as well. If the content is video only, this won't have any
  39883. // impact.
  39884. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  39885. this.timelineChangeController_.lastTimelineChange({
  39886. type: 'audio',
  39887. from: this.currentTimeline_,
  39888. to: segmentInfo.timeline
  39889. });
  39890. }
  39891. }
  39892. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  39893. // the following conditional otherwise it may consider this a bad "guess"
  39894. // and attempt to resync when the post-update seekable window and live
  39895. // point would mean that this was the perfect segment to fetch
  39896. this.trigger('syncinfoupdate');
  39897. const segment = segmentInfo.segment;
  39898. const part = segmentInfo.part;
  39899. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  39900. const badPartGuess = part && part.end && this.currentTime_() - part.end > segmentInfo.playlist.partTargetDuration * 3; // If we previously appended a segment/part that ends more than 3 part/targetDurations before
  39901. // the currentTime_ that means that our conservative guess was too conservative.
  39902. // In that case, reset the loader state so that we try to use any information gained
  39903. // from the previous request to create a new, more accurate, sync-point.
  39904. if (badSegmentGuess || badPartGuess) {
  39905. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  39906. this.resetEverything();
  39907. return;
  39908. }
  39909. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  39910. // and conservatively guess
  39911. if (isWalkingForward) {
  39912. this.trigger('bandwidthupdate');
  39913. }
  39914. this.trigger('progress');
  39915. this.mediaIndex = segmentInfo.mediaIndex;
  39916. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  39917. // buffer, end the stream. this ensures the "ended" event will
  39918. // fire if playback reaches that point.
  39919. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  39920. this.endOfStream();
  39921. } // used for testing
  39922. this.trigger('appended');
  39923. if (segmentInfo.hasAppendedData_) {
  39924. this.mediaAppends++;
  39925. }
  39926. if (!this.paused()) {
  39927. this.monitorBuffer_();
  39928. }
  39929. }
  39930. /**
  39931. * Records the current throughput of the decrypt, transmux, and append
  39932. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  39933. * moving average of the throughput. `throughput.count` is the number of
  39934. * data points in the average.
  39935. *
  39936. * @private
  39937. * @param {Object} segmentInfo the object returned by loadSegment
  39938. */
  39939. recordThroughput_(segmentInfo) {
  39940. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39941. this.logger_(`Ignoring segment's throughput because its duration of ${segmentInfo.duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  39942. return;
  39943. }
  39944. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  39945. // by zero in the case where the throughput is ridiculously high
  39946. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  39947. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  39948. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  39949. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  39950. }
  39951. /**
  39952. * Adds a cue to the segment-metadata track with some metadata information about the
  39953. * segment
  39954. *
  39955. * @private
  39956. * @param {Object} segmentInfo
  39957. * the object returned by loadSegment
  39958. * @method addSegmentMetadataCue_
  39959. */
  39960. addSegmentMetadataCue_(segmentInfo) {
  39961. if (!this.segmentMetadataTrack_) {
  39962. return;
  39963. }
  39964. const segment = segmentInfo.segment;
  39965. const start = segment.start;
  39966. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  39967. if (!finite(start) || !finite(end)) {
  39968. return;
  39969. }
  39970. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  39971. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  39972. const value = {
  39973. custom: segment.custom,
  39974. dateTimeObject: segment.dateTimeObject,
  39975. dateTimeString: segment.dateTimeString,
  39976. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  39977. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  39978. codecs: segmentInfo.playlist.attributes.CODECS,
  39979. byteLength: segmentInfo.byteLength,
  39980. uri: segmentInfo.uri,
  39981. timeline: segmentInfo.timeline,
  39982. playlist: segmentInfo.playlist.id,
  39983. start,
  39984. end
  39985. };
  39986. const data = JSON.stringify(value);
  39987. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  39988. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  39989. cue.value = value;
  39990. this.segmentMetadataTrack_.addCue(cue);
  39991. }
  39992. }
  39993. function noop() {}
  39994. const toTitleCase = function (string) {
  39995. if (typeof string !== 'string') {
  39996. return string;
  39997. }
  39998. return string.replace(/./, w => w.toUpperCase());
  39999. };
  40000. /**
  40001. * @file source-updater.js
  40002. */
  40003. const bufferTypes = ['video', 'audio'];
  40004. const updating = (type, sourceUpdater) => {
  40005. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  40006. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  40007. };
  40008. const nextQueueIndexOfType = (type, queue) => {
  40009. for (let i = 0; i < queue.length; i++) {
  40010. const queueEntry = queue[i];
  40011. if (queueEntry.type === 'mediaSource') {
  40012. // If the next entry is a media source entry (uses multiple source buffers), block
  40013. // processing to allow it to go through first.
  40014. return null;
  40015. }
  40016. if (queueEntry.type === type) {
  40017. return i;
  40018. }
  40019. }
  40020. return null;
  40021. };
  40022. const shiftQueue = (type, sourceUpdater) => {
  40023. if (sourceUpdater.queue.length === 0) {
  40024. return;
  40025. }
  40026. let queueIndex = 0;
  40027. let queueEntry = sourceUpdater.queue[queueIndex];
  40028. if (queueEntry.type === 'mediaSource') {
  40029. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  40030. sourceUpdater.queue.shift();
  40031. queueEntry.action(sourceUpdater);
  40032. if (queueEntry.doneFn) {
  40033. queueEntry.doneFn();
  40034. } // Only specific source buffer actions must wait for async updateend events. Media
  40035. // Source actions process synchronously. Therefore, both audio and video source
  40036. // buffers are now clear to process the next queue entries.
  40037. shiftQueue('audio', sourceUpdater);
  40038. shiftQueue('video', sourceUpdater);
  40039. } // Media Source actions require both source buffers, so if the media source action
  40040. // couldn't process yet (because one or both source buffers are busy), block other
  40041. // queue actions until both are available and the media source action can process.
  40042. return;
  40043. }
  40044. if (type === 'mediaSource') {
  40045. // If the queue was shifted by a media source action (this happens when pushing a
  40046. // media source action onto the queue), then it wasn't from an updateend event from an
  40047. // audio or video source buffer, so there's no change from previous state, and no
  40048. // processing should be done.
  40049. return;
  40050. } // Media source queue entries don't need to consider whether the source updater is
  40051. // started (i.e., source buffers are created) as they don't need the source buffers, but
  40052. // source buffer queue entries do.
  40053. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  40054. return;
  40055. }
  40056. if (queueEntry.type !== type) {
  40057. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  40058. if (queueIndex === null) {
  40059. // Either there's no queue entry that uses this source buffer type in the queue, or
  40060. // there's a media source queue entry before the next entry of this type, in which
  40061. // case wait for that action to process first.
  40062. return;
  40063. }
  40064. queueEntry = sourceUpdater.queue[queueIndex];
  40065. }
  40066. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  40067. //
  40068. // The queue pending operation must be set before the action is performed in the event
  40069. // that the action results in a synchronous event that is acted upon. For instance, if
  40070. // an exception is thrown that can be handled, it's possible that new actions will be
  40071. // appended to an empty queue and immediately executed, but would not have the correct
  40072. // pending information if this property was set after the action was performed.
  40073. sourceUpdater.queuePending[type] = queueEntry;
  40074. queueEntry.action(type, sourceUpdater);
  40075. if (!queueEntry.doneFn) {
  40076. // synchronous operation, process next entry
  40077. sourceUpdater.queuePending[type] = null;
  40078. shiftQueue(type, sourceUpdater);
  40079. return;
  40080. }
  40081. };
  40082. const cleanupBuffer = (type, sourceUpdater) => {
  40083. const buffer = sourceUpdater[`${type}Buffer`];
  40084. const titleType = toTitleCase(type);
  40085. if (!buffer) {
  40086. return;
  40087. }
  40088. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  40089. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  40090. sourceUpdater.codecs[type] = null;
  40091. sourceUpdater[`${type}Buffer`] = null;
  40092. };
  40093. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  40094. const actions = {
  40095. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  40096. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40097. // or the media source does not contain this source buffer.
  40098. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40099. return;
  40100. }
  40101. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  40102. try {
  40103. sourceBuffer.appendBuffer(bytes);
  40104. } catch (e) {
  40105. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  40106. sourceUpdater.queuePending[type] = null;
  40107. onError(e);
  40108. }
  40109. },
  40110. remove: (start, end) => (type, sourceUpdater) => {
  40111. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40112. // or the media source does not contain this source buffer.
  40113. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40114. return;
  40115. }
  40116. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  40117. try {
  40118. sourceBuffer.remove(start, end);
  40119. } catch (e) {
  40120. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  40121. }
  40122. },
  40123. timestampOffset: offset => (type, sourceUpdater) => {
  40124. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40125. // or the media source does not contain this source buffer.
  40126. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40127. return;
  40128. }
  40129. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  40130. sourceBuffer.timestampOffset = offset;
  40131. },
  40132. callback: callback => (type, sourceUpdater) => {
  40133. callback();
  40134. },
  40135. endOfStream: error => sourceUpdater => {
  40136. if (sourceUpdater.mediaSource.readyState !== 'open') {
  40137. return;
  40138. }
  40139. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  40140. try {
  40141. sourceUpdater.mediaSource.endOfStream(error);
  40142. } catch (e) {
  40143. videojs.log.warn('Failed to call media source endOfStream', e);
  40144. }
  40145. },
  40146. duration: duration => sourceUpdater => {
  40147. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  40148. try {
  40149. sourceUpdater.mediaSource.duration = duration;
  40150. } catch (e) {
  40151. videojs.log.warn('Failed to set media source duration', e);
  40152. }
  40153. },
  40154. abort: () => (type, sourceUpdater) => {
  40155. if (sourceUpdater.mediaSource.readyState !== 'open') {
  40156. return;
  40157. }
  40158. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  40159. // or the media source does not contain this source buffer.
  40160. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40161. return;
  40162. }
  40163. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  40164. try {
  40165. sourceBuffer.abort();
  40166. } catch (e) {
  40167. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  40168. }
  40169. },
  40170. addSourceBuffer: (type, codec) => sourceUpdater => {
  40171. const titleType = toTitleCase(type);
  40172. const mime = codecs_js.getMimeForCodec(codec);
  40173. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  40174. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  40175. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  40176. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  40177. sourceUpdater.codecs[type] = codec;
  40178. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  40179. },
  40180. removeSourceBuffer: type => sourceUpdater => {
  40181. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  40182. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  40183. // or the media source does not contain this source buffer.
  40184. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40185. return;
  40186. }
  40187. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  40188. try {
  40189. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  40190. } catch (e) {
  40191. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  40192. }
  40193. },
  40194. changeType: codec => (type, sourceUpdater) => {
  40195. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  40196. const mime = codecs_js.getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  40197. // or the media source does not contain this source buffer.
  40198. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  40199. return;
  40200. } // do not update codec if we don't need to.
  40201. if (sourceUpdater.codecs[type] === codec) {
  40202. return;
  40203. }
  40204. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  40205. sourceBuffer.changeType(mime);
  40206. sourceUpdater.codecs[type] = codec;
  40207. }
  40208. };
  40209. const pushQueue = ({
  40210. type,
  40211. sourceUpdater,
  40212. action,
  40213. doneFn,
  40214. name
  40215. }) => {
  40216. sourceUpdater.queue.push({
  40217. type,
  40218. action,
  40219. doneFn,
  40220. name
  40221. });
  40222. shiftQueue(type, sourceUpdater);
  40223. };
  40224. const onUpdateend = (type, sourceUpdater) => e => {
  40225. // Although there should, in theory, be a pending action for any updateend receieved,
  40226. // there are some actions that may trigger updateend events without set definitions in
  40227. // the w3c spec. For instance, setting the duration on the media source may trigger
  40228. // updateend events on source buffers. This does not appear to be in the spec. As such,
  40229. // if we encounter an updateend without a corresponding pending action from our queue
  40230. // for that source buffer type, process the next action.
  40231. if (sourceUpdater.queuePending[type]) {
  40232. const doneFn = sourceUpdater.queuePending[type].doneFn;
  40233. sourceUpdater.queuePending[type] = null;
  40234. if (doneFn) {
  40235. // if there's an error, report it
  40236. doneFn(sourceUpdater[`${type}Error_`]);
  40237. }
  40238. }
  40239. shiftQueue(type, sourceUpdater);
  40240. };
  40241. /**
  40242. * A queue of callbacks to be serialized and applied when a
  40243. * MediaSource and its associated SourceBuffers are not in the
  40244. * updating state. It is used by the segment loader to update the
  40245. * underlying SourceBuffers when new data is loaded, for instance.
  40246. *
  40247. * @class SourceUpdater
  40248. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  40249. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  40250. */
  40251. class SourceUpdater extends videojs.EventTarget {
  40252. constructor(mediaSource) {
  40253. super();
  40254. this.mediaSource = mediaSource;
  40255. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  40256. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  40257. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  40258. this.audioTimestampOffset_ = 0;
  40259. this.videoTimestampOffset_ = 0;
  40260. this.queue = [];
  40261. this.queuePending = {
  40262. audio: null,
  40263. video: null
  40264. };
  40265. this.delayedAudioAppendQueue_ = [];
  40266. this.videoAppendQueued_ = false;
  40267. this.codecs = {};
  40268. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  40269. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  40270. this.onVideoError_ = e => {
  40271. // used for debugging
  40272. this.videoError_ = e;
  40273. };
  40274. this.onAudioError_ = e => {
  40275. // used for debugging
  40276. this.audioError_ = e;
  40277. };
  40278. this.createdSourceBuffers_ = false;
  40279. this.initializedEme_ = false;
  40280. this.triggeredReady_ = false;
  40281. }
  40282. initializedEme() {
  40283. this.initializedEme_ = true;
  40284. this.triggerReady();
  40285. }
  40286. hasCreatedSourceBuffers() {
  40287. // if false, likely waiting on one of the segment loaders to get enough data to create
  40288. // source buffers
  40289. return this.createdSourceBuffers_;
  40290. }
  40291. hasInitializedAnyEme() {
  40292. return this.initializedEme_;
  40293. }
  40294. ready() {
  40295. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  40296. }
  40297. createSourceBuffers(codecs) {
  40298. if (this.hasCreatedSourceBuffers()) {
  40299. // already created them before
  40300. return;
  40301. } // the intial addOrChangeSourceBuffers will always be
  40302. // two add buffers.
  40303. this.addOrChangeSourceBuffers(codecs);
  40304. this.createdSourceBuffers_ = true;
  40305. this.trigger('createdsourcebuffers');
  40306. this.triggerReady();
  40307. }
  40308. triggerReady() {
  40309. // only allow ready to be triggered once, this prevents the case
  40310. // where:
  40311. // 1. we trigger createdsourcebuffers
  40312. // 2. ie 11 synchronously initializates eme
  40313. // 3. the synchronous initialization causes us to trigger ready
  40314. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  40315. if (this.ready() && !this.triggeredReady_) {
  40316. this.triggeredReady_ = true;
  40317. this.trigger('ready');
  40318. }
  40319. }
  40320. /**
  40321. * Add a type of source buffer to the media source.
  40322. *
  40323. * @param {string} type
  40324. * The type of source buffer to add.
  40325. *
  40326. * @param {string} codec
  40327. * The codec to add the source buffer with.
  40328. */
  40329. addSourceBuffer(type, codec) {
  40330. pushQueue({
  40331. type: 'mediaSource',
  40332. sourceUpdater: this,
  40333. action: actions.addSourceBuffer(type, codec),
  40334. name: 'addSourceBuffer'
  40335. });
  40336. }
  40337. /**
  40338. * call abort on a source buffer.
  40339. *
  40340. * @param {string} type
  40341. * The type of source buffer to call abort on.
  40342. */
  40343. abort(type) {
  40344. pushQueue({
  40345. type,
  40346. sourceUpdater: this,
  40347. action: actions.abort(type),
  40348. name: 'abort'
  40349. });
  40350. }
  40351. /**
  40352. * Call removeSourceBuffer and remove a specific type
  40353. * of source buffer on the mediaSource.
  40354. *
  40355. * @param {string} type
  40356. * The type of source buffer to remove.
  40357. */
  40358. removeSourceBuffer(type) {
  40359. if (!this.canRemoveSourceBuffer()) {
  40360. videojs.log.error('removeSourceBuffer is not supported!');
  40361. return;
  40362. }
  40363. pushQueue({
  40364. type: 'mediaSource',
  40365. sourceUpdater: this,
  40366. action: actions.removeSourceBuffer(type),
  40367. name: 'removeSourceBuffer'
  40368. });
  40369. }
  40370. /**
  40371. * Whether or not the removeSourceBuffer function is supported
  40372. * on the mediaSource.
  40373. *
  40374. * @return {boolean}
  40375. * if removeSourceBuffer can be called.
  40376. */
  40377. canRemoveSourceBuffer() {
  40378. // IE reports that it supports removeSourceBuffer, but often throws
  40379. // errors when attempting to use the function. So we report that it
  40380. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  40381. // throws errors, so we report that it does not support this as well.
  40382. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window__default["default"].MediaSource && window__default["default"].MediaSource.prototype && typeof window__default["default"].MediaSource.prototype.removeSourceBuffer === 'function';
  40383. }
  40384. /**
  40385. * Whether or not the changeType function is supported
  40386. * on our SourceBuffers.
  40387. *
  40388. * @return {boolean}
  40389. * if changeType can be called.
  40390. */
  40391. static canChangeType() {
  40392. return window__default["default"].SourceBuffer && window__default["default"].SourceBuffer.prototype && typeof window__default["default"].SourceBuffer.prototype.changeType === 'function';
  40393. }
  40394. /**
  40395. * Whether or not the changeType function is supported
  40396. * on our SourceBuffers.
  40397. *
  40398. * @return {boolean}
  40399. * if changeType can be called.
  40400. */
  40401. canChangeType() {
  40402. return this.constructor.canChangeType();
  40403. }
  40404. /**
  40405. * Call the changeType function on a source buffer, given the code and type.
  40406. *
  40407. * @param {string} type
  40408. * The type of source buffer to call changeType on.
  40409. *
  40410. * @param {string} codec
  40411. * The codec string to change type with on the source buffer.
  40412. */
  40413. changeType(type, codec) {
  40414. if (!this.canChangeType()) {
  40415. videojs.log.error('changeType is not supported!');
  40416. return;
  40417. }
  40418. pushQueue({
  40419. type,
  40420. sourceUpdater: this,
  40421. action: actions.changeType(codec),
  40422. name: 'changeType'
  40423. });
  40424. }
  40425. /**
  40426. * Add source buffers with a codec or, if they are already created,
  40427. * call changeType on source buffers using changeType.
  40428. *
  40429. * @param {Object} codecs
  40430. * Codecs to switch to
  40431. */
  40432. addOrChangeSourceBuffers(codecs) {
  40433. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  40434. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  40435. }
  40436. Object.keys(codecs).forEach(type => {
  40437. const codec = codecs[type];
  40438. if (!this.hasCreatedSourceBuffers()) {
  40439. return this.addSourceBuffer(type, codec);
  40440. }
  40441. if (this.canChangeType()) {
  40442. this.changeType(type, codec);
  40443. }
  40444. });
  40445. }
  40446. /**
  40447. * Queue an update to append an ArrayBuffer.
  40448. *
  40449. * @param {MediaObject} object containing audioBytes and/or videoBytes
  40450. * @param {Function} done the function to call when done
  40451. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  40452. */
  40453. appendBuffer(options, doneFn) {
  40454. const {
  40455. segmentInfo,
  40456. type,
  40457. bytes
  40458. } = options;
  40459. this.processedAppend_ = true;
  40460. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  40461. this.delayedAudioAppendQueue_.push([options, doneFn]);
  40462. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  40463. return;
  40464. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  40465. // not be fired. This means that the queue will be blocked until the next action
  40466. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  40467. // these errors by calling the doneFn with the specific error.
  40468. const onError = doneFn;
  40469. pushQueue({
  40470. type,
  40471. sourceUpdater: this,
  40472. action: actions.appendBuffer(bytes, segmentInfo || {
  40473. mediaIndex: -1
  40474. }, onError),
  40475. doneFn,
  40476. name: 'appendBuffer'
  40477. });
  40478. if (type === 'video') {
  40479. this.videoAppendQueued_ = true;
  40480. if (!this.delayedAudioAppendQueue_.length) {
  40481. return;
  40482. }
  40483. const queue = this.delayedAudioAppendQueue_.slice();
  40484. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  40485. this.delayedAudioAppendQueue_.length = 0;
  40486. queue.forEach(que => {
  40487. this.appendBuffer.apply(this, que);
  40488. });
  40489. }
  40490. }
  40491. /**
  40492. * Get the audio buffer's buffered timerange.
  40493. *
  40494. * @return {TimeRange}
  40495. * The audio buffer's buffered time range
  40496. */
  40497. audioBuffered() {
  40498. // no media source/source buffer or it isn't in the media sources
  40499. // source buffer list
  40500. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  40501. return createTimeRanges();
  40502. }
  40503. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  40504. }
  40505. /**
  40506. * Get the video buffer's buffered timerange.
  40507. *
  40508. * @return {TimeRange}
  40509. * The video buffer's buffered time range
  40510. */
  40511. videoBuffered() {
  40512. // no media source/source buffer or it isn't in the media sources
  40513. // source buffer list
  40514. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  40515. return createTimeRanges();
  40516. }
  40517. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  40518. }
  40519. /**
  40520. * Get a combined video/audio buffer's buffered timerange.
  40521. *
  40522. * @return {TimeRange}
  40523. * the combined time range
  40524. */
  40525. buffered() {
  40526. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  40527. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  40528. if (audio && !video) {
  40529. return this.audioBuffered();
  40530. }
  40531. if (video && !audio) {
  40532. return this.videoBuffered();
  40533. }
  40534. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  40535. }
  40536. /**
  40537. * Add a callback to the queue that will set duration on the mediaSource.
  40538. *
  40539. * @param {number} duration
  40540. * The duration to set
  40541. *
  40542. * @param {Function} [doneFn]
  40543. * function to run after duration has been set.
  40544. */
  40545. setDuration(duration, doneFn = noop) {
  40546. // In order to set the duration on the media source, it's necessary to wait for all
  40547. // source buffers to no longer be updating. "If the updating attribute equals true on
  40548. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40549. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40550. pushQueue({
  40551. type: 'mediaSource',
  40552. sourceUpdater: this,
  40553. action: actions.duration(duration),
  40554. name: 'duration',
  40555. doneFn
  40556. });
  40557. }
  40558. /**
  40559. * Add a mediaSource endOfStream call to the queue
  40560. *
  40561. * @param {Error} [error]
  40562. * Call endOfStream with an error
  40563. *
  40564. * @param {Function} [doneFn]
  40565. * A function that should be called when the
  40566. * endOfStream call has finished.
  40567. */
  40568. endOfStream(error = null, doneFn = noop) {
  40569. if (typeof error !== 'string') {
  40570. error = undefined;
  40571. } // In order to set the duration on the media source, it's necessary to wait for all
  40572. // source buffers to no longer be updating. "If the updating attribute equals true on
  40573. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40574. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40575. pushQueue({
  40576. type: 'mediaSource',
  40577. sourceUpdater: this,
  40578. action: actions.endOfStream(error),
  40579. name: 'endOfStream',
  40580. doneFn
  40581. });
  40582. }
  40583. /**
  40584. * Queue an update to remove a time range from the buffer.
  40585. *
  40586. * @param {number} start where to start the removal
  40587. * @param {number} end where to end the removal
  40588. * @param {Function} [done=noop] optional callback to be executed when the remove
  40589. * operation is complete
  40590. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40591. */
  40592. removeAudio(start, end, done = noop) {
  40593. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  40594. done();
  40595. return;
  40596. }
  40597. pushQueue({
  40598. type: 'audio',
  40599. sourceUpdater: this,
  40600. action: actions.remove(start, end),
  40601. doneFn: done,
  40602. name: 'remove'
  40603. });
  40604. }
  40605. /**
  40606. * Queue an update to remove a time range from the buffer.
  40607. *
  40608. * @param {number} start where to start the removal
  40609. * @param {number} end where to end the removal
  40610. * @param {Function} [done=noop] optional callback to be executed when the remove
  40611. * operation is complete
  40612. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40613. */
  40614. removeVideo(start, end, done = noop) {
  40615. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  40616. done();
  40617. return;
  40618. }
  40619. pushQueue({
  40620. type: 'video',
  40621. sourceUpdater: this,
  40622. action: actions.remove(start, end),
  40623. doneFn: done,
  40624. name: 'remove'
  40625. });
  40626. }
  40627. /**
  40628. * Whether the underlying sourceBuffer is updating or not
  40629. *
  40630. * @return {boolean} the updating status of the SourceBuffer
  40631. */
  40632. updating() {
  40633. // the audio/video source buffer is updating
  40634. if (updating('audio', this) || updating('video', this)) {
  40635. return true;
  40636. }
  40637. return false;
  40638. }
  40639. /**
  40640. * Set/get the timestampoffset on the audio SourceBuffer
  40641. *
  40642. * @return {number} the timestamp offset
  40643. */
  40644. audioTimestampOffset(offset) {
  40645. if (typeof offset !== 'undefined' && this.audioBuffer &&
  40646. // no point in updating if it's the same
  40647. this.audioTimestampOffset_ !== offset) {
  40648. pushQueue({
  40649. type: 'audio',
  40650. sourceUpdater: this,
  40651. action: actions.timestampOffset(offset),
  40652. name: 'timestampOffset'
  40653. });
  40654. this.audioTimestampOffset_ = offset;
  40655. }
  40656. return this.audioTimestampOffset_;
  40657. }
  40658. /**
  40659. * Set/get the timestampoffset on the video SourceBuffer
  40660. *
  40661. * @return {number} the timestamp offset
  40662. */
  40663. videoTimestampOffset(offset) {
  40664. if (typeof offset !== 'undefined' && this.videoBuffer &&
  40665. // no point in updating if it's the same
  40666. this.videoTimestampOffset !== offset) {
  40667. pushQueue({
  40668. type: 'video',
  40669. sourceUpdater: this,
  40670. action: actions.timestampOffset(offset),
  40671. name: 'timestampOffset'
  40672. });
  40673. this.videoTimestampOffset_ = offset;
  40674. }
  40675. return this.videoTimestampOffset_;
  40676. }
  40677. /**
  40678. * Add a function to the queue that will be called
  40679. * when it is its turn to run in the audio queue.
  40680. *
  40681. * @param {Function} callback
  40682. * The callback to queue.
  40683. */
  40684. audioQueueCallback(callback) {
  40685. if (!this.audioBuffer) {
  40686. return;
  40687. }
  40688. pushQueue({
  40689. type: 'audio',
  40690. sourceUpdater: this,
  40691. action: actions.callback(callback),
  40692. name: 'callback'
  40693. });
  40694. }
  40695. /**
  40696. * Add a function to the queue that will be called
  40697. * when it is its turn to run in the video queue.
  40698. *
  40699. * @param {Function} callback
  40700. * The callback to queue.
  40701. */
  40702. videoQueueCallback(callback) {
  40703. if (!this.videoBuffer) {
  40704. return;
  40705. }
  40706. pushQueue({
  40707. type: 'video',
  40708. sourceUpdater: this,
  40709. action: actions.callback(callback),
  40710. name: 'callback'
  40711. });
  40712. }
  40713. /**
  40714. * dispose of the source updater and the underlying sourceBuffer
  40715. */
  40716. dispose() {
  40717. this.trigger('dispose');
  40718. bufferTypes.forEach(type => {
  40719. this.abort(type);
  40720. if (this.canRemoveSourceBuffer()) {
  40721. this.removeSourceBuffer(type);
  40722. } else {
  40723. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  40724. }
  40725. });
  40726. this.videoAppendQueued_ = false;
  40727. this.delayedAudioAppendQueue_.length = 0;
  40728. if (this.sourceopenListener_) {
  40729. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  40730. }
  40731. this.off();
  40732. }
  40733. }
  40734. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  40735. /**
  40736. * @file vtt-segment-loader.js
  40737. */
  40738. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  40739. class NoVttJsError extends Error {
  40740. constructor() {
  40741. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  40742. }
  40743. }
  40744. /**
  40745. * An object that manages segment loading and appending.
  40746. *
  40747. * @class VTTSegmentLoader
  40748. * @param {Object} options required and optional options
  40749. * @extends videojs.EventTarget
  40750. */
  40751. class VTTSegmentLoader extends SegmentLoader {
  40752. constructor(settings, options = {}) {
  40753. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  40754. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  40755. this.mediaSource_ = null;
  40756. this.subtitlesTrack_ = null;
  40757. this.loaderType_ = 'subtitle';
  40758. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  40759. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  40760. // the sync controller leads to improper behavior.
  40761. this.shouldSaveSegmentTimingInfo_ = false;
  40762. }
  40763. createTransmuxer_() {
  40764. // don't need to transmux any subtitles
  40765. return null;
  40766. }
  40767. /**
  40768. * Indicates which time ranges are buffered
  40769. *
  40770. * @return {TimeRange}
  40771. * TimeRange object representing the current buffered ranges
  40772. */
  40773. buffered_() {
  40774. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  40775. return createTimeRanges();
  40776. }
  40777. const cues = this.subtitlesTrack_.cues;
  40778. const start = cues[0].startTime;
  40779. const end = cues[cues.length - 1].startTime;
  40780. return createTimeRanges([[start, end]]);
  40781. }
  40782. /**
  40783. * Gets and sets init segment for the provided map
  40784. *
  40785. * @param {Object} map
  40786. * The map object representing the init segment to get or set
  40787. * @param {boolean=} set
  40788. * If true, the init segment for the provided map should be saved
  40789. * @return {Object}
  40790. * map object for desired init segment
  40791. */
  40792. initSegmentForMap(map, set = false) {
  40793. if (!map) {
  40794. return null;
  40795. }
  40796. const id = initSegmentId(map);
  40797. let storedMap = this.initSegments_[id];
  40798. if (set && !storedMap && map.bytes) {
  40799. // append WebVTT line terminators to the media initialization segment if it exists
  40800. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  40801. // requires two or more WebVTT line terminators between the WebVTT header and the
  40802. // rest of the file
  40803. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  40804. const combinedSegment = new Uint8Array(combinedByteLength);
  40805. combinedSegment.set(map.bytes);
  40806. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  40807. this.initSegments_[id] = storedMap = {
  40808. resolvedUri: map.resolvedUri,
  40809. byterange: map.byterange,
  40810. bytes: combinedSegment
  40811. };
  40812. }
  40813. return storedMap || map;
  40814. }
  40815. /**
  40816. * Returns true if all configuration required for loading is present, otherwise false.
  40817. *
  40818. * @return {boolean} True if the all configuration is ready for loading
  40819. * @private
  40820. */
  40821. couldBeginLoading_() {
  40822. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  40823. }
  40824. /**
  40825. * Once all the starting parameters have been specified, begin
  40826. * operation. This method should only be invoked from the INIT
  40827. * state.
  40828. *
  40829. * @private
  40830. */
  40831. init_() {
  40832. this.state = 'READY';
  40833. this.resetEverything();
  40834. return this.monitorBuffer_();
  40835. }
  40836. /**
  40837. * Set a subtitle track on the segment loader to add subtitles to
  40838. *
  40839. * @param {TextTrack=} track
  40840. * The text track to add loaded subtitles to
  40841. * @return {TextTrack}
  40842. * Returns the subtitles track
  40843. */
  40844. track(track) {
  40845. if (typeof track === 'undefined') {
  40846. return this.subtitlesTrack_;
  40847. }
  40848. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  40849. // buffering now
  40850. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  40851. this.init_();
  40852. }
  40853. return this.subtitlesTrack_;
  40854. }
  40855. /**
  40856. * Remove any data in the source buffer between start and end times
  40857. *
  40858. * @param {number} start - the start time of the region to remove from the buffer
  40859. * @param {number} end - the end time of the region to remove from the buffer
  40860. */
  40861. remove(start, end) {
  40862. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  40863. }
  40864. /**
  40865. * fill the buffer with segements unless the sourceBuffers are
  40866. * currently updating
  40867. *
  40868. * Note: this function should only ever be called by monitorBuffer_
  40869. * and never directly
  40870. *
  40871. * @private
  40872. */
  40873. fillBuffer_() {
  40874. // see if we need to begin loading immediately
  40875. const segmentInfo = this.chooseNextRequest_();
  40876. if (!segmentInfo) {
  40877. return;
  40878. }
  40879. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  40880. // We don't have the timestamp offset that we need to sync subtitles.
  40881. // Rerun on a timestamp offset or user interaction.
  40882. const checkTimestampOffset = () => {
  40883. this.state = 'READY';
  40884. if (!this.paused()) {
  40885. // if not paused, queue a buffer check as soon as possible
  40886. this.monitorBuffer_();
  40887. }
  40888. };
  40889. this.syncController_.one('timestampoffset', checkTimestampOffset);
  40890. this.state = 'WAITING_ON_TIMELINE';
  40891. return;
  40892. }
  40893. this.loadSegment_(segmentInfo);
  40894. } // never set a timestamp offset for vtt segments.
  40895. timestampOffsetForSegment_() {
  40896. return null;
  40897. }
  40898. chooseNextRequest_() {
  40899. return this.skipEmptySegments_(super.chooseNextRequest_());
  40900. }
  40901. /**
  40902. * Prevents the segment loader from requesting segments we know contain no subtitles
  40903. * by walking forward until we find the next segment that we don't know whether it is
  40904. * empty or not.
  40905. *
  40906. * @param {Object} segmentInfo
  40907. * a segment info object that describes the current segment
  40908. * @return {Object}
  40909. * a segment info object that describes the current segment
  40910. */
  40911. skipEmptySegments_(segmentInfo) {
  40912. while (segmentInfo && segmentInfo.segment.empty) {
  40913. // stop at the last possible segmentInfo
  40914. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  40915. segmentInfo = null;
  40916. break;
  40917. }
  40918. segmentInfo = this.generateSegmentInfo_({
  40919. playlist: segmentInfo.playlist,
  40920. mediaIndex: segmentInfo.mediaIndex + 1,
  40921. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  40922. isSyncRequest: segmentInfo.isSyncRequest
  40923. });
  40924. }
  40925. return segmentInfo;
  40926. }
  40927. stopForError(error) {
  40928. this.error(error);
  40929. this.state = 'READY';
  40930. this.pause();
  40931. this.trigger('error');
  40932. }
  40933. /**
  40934. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  40935. *
  40936. * @private
  40937. */
  40938. segmentRequestFinished_(error, simpleSegment, result) {
  40939. if (!this.subtitlesTrack_) {
  40940. this.state = 'READY';
  40941. return;
  40942. }
  40943. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  40944. if (!this.pendingSegment_) {
  40945. this.state = 'READY';
  40946. this.mediaRequestsAborted += 1;
  40947. return;
  40948. }
  40949. if (error) {
  40950. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  40951. this.handleTimeout_();
  40952. }
  40953. if (error.code === REQUEST_ERRORS.ABORTED) {
  40954. this.mediaRequestsAborted += 1;
  40955. } else {
  40956. this.mediaRequestsErrored += 1;
  40957. }
  40958. this.stopForError(error);
  40959. return;
  40960. }
  40961. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  40962. // maintain functionality between segment loaders
  40963. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  40964. if (simpleSegment.key) {
  40965. this.segmentKey(simpleSegment.key, true);
  40966. }
  40967. this.state = 'APPENDING'; // used for tests
  40968. this.trigger('appending');
  40969. const segment = segmentInfo.segment;
  40970. if (segment.map) {
  40971. segment.map.bytes = simpleSegment.map.bytes;
  40972. }
  40973. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  40974. if (typeof window__default["default"].WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  40975. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  40976. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  40977. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  40978. message: 'Error loading vtt.js'
  40979. }));
  40980. return;
  40981. }
  40982. segment.requested = true;
  40983. try {
  40984. this.parseVTTCues_(segmentInfo);
  40985. } catch (e) {
  40986. this.stopForError({
  40987. message: e.message
  40988. });
  40989. return;
  40990. }
  40991. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  40992. if (segmentInfo.cues.length) {
  40993. segmentInfo.timingInfo = {
  40994. start: segmentInfo.cues[0].startTime,
  40995. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  40996. };
  40997. } else {
  40998. segmentInfo.timingInfo = {
  40999. start: segmentInfo.startOfSegment,
  41000. end: segmentInfo.startOfSegment + segmentInfo.duration
  41001. };
  41002. }
  41003. if (segmentInfo.isSyncRequest) {
  41004. this.trigger('syncinfoupdate');
  41005. this.pendingSegment_ = null;
  41006. this.state = 'READY';
  41007. return;
  41008. }
  41009. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  41010. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  41011. // the subtitle track
  41012. segmentInfo.cues.forEach(cue => {
  41013. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window__default["default"].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  41014. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  41015. // cues to have identical time-intervals, but if the text is also identical
  41016. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  41017. // "overlaps" VTT segments)
  41018. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  41019. this.handleAppendsDone_();
  41020. }
  41021. handleData_() {// noop as we shouldn't be getting video/audio data captions
  41022. // that we do not support here.
  41023. }
  41024. updateTimingInfoEnd_() {// noop
  41025. }
  41026. /**
  41027. * Uses the WebVTT parser to parse the segment response
  41028. *
  41029. * @throws NoVttJsError
  41030. *
  41031. * @param {Object} segmentInfo
  41032. * a segment info object that describes the current segment
  41033. * @private
  41034. */
  41035. parseVTTCues_(segmentInfo) {
  41036. let decoder;
  41037. let decodeBytesToString = false;
  41038. if (typeof window__default["default"].WebVTT !== 'function') {
  41039. // caller is responsible for exception handling.
  41040. throw new NoVttJsError();
  41041. }
  41042. if (typeof window__default["default"].TextDecoder === 'function') {
  41043. decoder = new window__default["default"].TextDecoder('utf8');
  41044. } else {
  41045. decoder = window__default["default"].WebVTT.StringDecoder();
  41046. decodeBytesToString = true;
  41047. }
  41048. const parser = new window__default["default"].WebVTT.Parser(window__default["default"], window__default["default"].vttjs, decoder);
  41049. segmentInfo.cues = [];
  41050. segmentInfo.timestampmap = {
  41051. MPEGTS: 0,
  41052. LOCAL: 0
  41053. };
  41054. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  41055. parser.ontimestampmap = map => {
  41056. segmentInfo.timestampmap = map;
  41057. };
  41058. parser.onparsingerror = error => {
  41059. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  41060. };
  41061. if (segmentInfo.segment.map) {
  41062. let mapData = segmentInfo.segment.map.bytes;
  41063. if (decodeBytesToString) {
  41064. mapData = uint8ToUtf8(mapData);
  41065. }
  41066. parser.parse(mapData);
  41067. }
  41068. let segmentData = segmentInfo.bytes;
  41069. if (decodeBytesToString) {
  41070. segmentData = uint8ToUtf8(segmentData);
  41071. }
  41072. parser.parse(segmentData);
  41073. parser.flush();
  41074. }
  41075. /**
  41076. * Updates the start and end times of any cues parsed by the WebVTT parser using
  41077. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  41078. * from the SyncController
  41079. *
  41080. * @param {Object} segmentInfo
  41081. * a segment info object that describes the current segment
  41082. * @param {Object} mappingObj
  41083. * object containing a mapping from TS to media time
  41084. * @param {Object} playlist
  41085. * the playlist object containing the segment
  41086. * @private
  41087. */
  41088. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  41089. const segment = segmentInfo.segment;
  41090. if (!mappingObj) {
  41091. // If the sync controller does not have a mapping of TS to Media Time for the
  41092. // timeline, then we don't have enough information to update the cue
  41093. // start/end times
  41094. return;
  41095. }
  41096. if (!segmentInfo.cues.length) {
  41097. // If there are no cues, we also do not have enough information to figure out
  41098. // segment timing. Mark that the segment contains no cues so we don't re-request
  41099. // an empty segment.
  41100. segment.empty = true;
  41101. return;
  41102. }
  41103. const timestampmap = segmentInfo.timestampmap;
  41104. const diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  41105. segmentInfo.cues.forEach(cue => {
  41106. // First convert cue time to TS time using the timestamp-map provided within the vtt
  41107. cue.startTime += diff;
  41108. cue.endTime += diff;
  41109. });
  41110. if (!playlist.syncInfo) {
  41111. const firstStart = segmentInfo.cues[0].startTime;
  41112. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  41113. playlist.syncInfo = {
  41114. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  41115. time: Math.min(firstStart, lastStart - segment.duration)
  41116. };
  41117. }
  41118. }
  41119. }
  41120. /**
  41121. * @file ad-cue-tags.js
  41122. */
  41123. /**
  41124. * Searches for an ad cue that overlaps with the given mediaTime
  41125. *
  41126. * @param {Object} track
  41127. * the track to find the cue for
  41128. *
  41129. * @param {number} mediaTime
  41130. * the time to find the cue at
  41131. *
  41132. * @return {Object|null}
  41133. * the found cue or null
  41134. */
  41135. const findAdCue = function (track, mediaTime) {
  41136. const cues = track.cues;
  41137. for (let i = 0; i < cues.length; i++) {
  41138. const cue = cues[i];
  41139. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  41140. return cue;
  41141. }
  41142. }
  41143. return null;
  41144. };
  41145. const updateAdCues = function (media, track, offset = 0) {
  41146. if (!media.segments) {
  41147. return;
  41148. }
  41149. let mediaTime = offset;
  41150. let cue;
  41151. for (let i = 0; i < media.segments.length; i++) {
  41152. const segment = media.segments[i];
  41153. if (!cue) {
  41154. // Since the cues will span for at least the segment duration, adding a fudge
  41155. // factor of half segment duration will prevent duplicate cues from being
  41156. // created when timing info is not exact (e.g. cue start time initialized
  41157. // at 10.006677, but next call mediaTime is 10.003332 )
  41158. cue = findAdCue(track, mediaTime + segment.duration / 2);
  41159. }
  41160. if (cue) {
  41161. if ('cueIn' in segment) {
  41162. // Found a CUE-IN so end the cue
  41163. cue.endTime = mediaTime;
  41164. cue.adEndTime = mediaTime;
  41165. mediaTime += segment.duration;
  41166. cue = null;
  41167. continue;
  41168. }
  41169. if (mediaTime < cue.endTime) {
  41170. // Already processed this mediaTime for this cue
  41171. mediaTime += segment.duration;
  41172. continue;
  41173. } // otherwise extend cue until a CUE-IN is found
  41174. cue.endTime += segment.duration;
  41175. } else {
  41176. if ('cueOut' in segment) {
  41177. cue = new window__default["default"].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  41178. cue.adStartTime = mediaTime; // Assumes tag format to be
  41179. // #EXT-X-CUE-OUT:30
  41180. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  41181. track.addCue(cue);
  41182. }
  41183. if ('cueOutCont' in segment) {
  41184. // Entered into the middle of an ad cue
  41185. // Assumes tag formate to be
  41186. // #EXT-X-CUE-OUT-CONT:10/30
  41187. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  41188. cue = new window__default["default"].VTTCue(mediaTime, mediaTime + segment.duration, '');
  41189. cue.adStartTime = mediaTime - adOffset;
  41190. cue.adEndTime = cue.adStartTime + adTotal;
  41191. track.addCue(cue);
  41192. }
  41193. }
  41194. mediaTime += segment.duration;
  41195. }
  41196. };
  41197. /**
  41198. * @file sync-controller.js
  41199. */
  41200. // synchronize expired playlist segments.
  41201. // the max media sequence diff is 48 hours of live stream
  41202. // content with two second segments. Anything larger than that
  41203. // will likely be invalid.
  41204. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  41205. const syncPointStrategies = [
  41206. // Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  41207. // the equivalence display-time 0 === segment-index 0
  41208. {
  41209. name: 'VOD',
  41210. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41211. if (duration !== Infinity) {
  41212. const syncPoint = {
  41213. time: 0,
  41214. segmentIndex: 0,
  41215. partIndex: null
  41216. };
  41217. return syncPoint;
  41218. }
  41219. return null;
  41220. }
  41221. },
  41222. // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  41223. {
  41224. name: 'ProgramDateTime',
  41225. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41226. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  41227. return null;
  41228. }
  41229. let syncPoint = null;
  41230. let lastDistance = null;
  41231. const partsAndSegments = getPartsAndSegments(playlist);
  41232. currentTime = currentTime || 0;
  41233. for (let i = 0; i < partsAndSegments.length; i++) {
  41234. // start from the end and loop backwards for live
  41235. // or start from the front and loop forwards for non-live
  41236. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41237. const partAndSegment = partsAndSegments[index];
  41238. const segment = partAndSegment.segment;
  41239. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  41240. if (!datetimeMapping || !segment.dateTimeObject) {
  41241. continue;
  41242. }
  41243. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  41244. let start = segmentTime + datetimeMapping; // take part duration into account.
  41245. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  41246. for (let z = 0; z < partAndSegment.partIndex; z++) {
  41247. start += segment.parts[z].duration;
  41248. }
  41249. }
  41250. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  41251. // currentTime and can stop looking for better candidates
  41252. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  41253. break;
  41254. }
  41255. lastDistance = distance;
  41256. syncPoint = {
  41257. time: start,
  41258. segmentIndex: partAndSegment.segmentIndex,
  41259. partIndex: partAndSegment.partIndex
  41260. };
  41261. }
  41262. return syncPoint;
  41263. }
  41264. },
  41265. // Stategy "Segment": We have a known time mapping for a timeline and a
  41266. // segment in the current timeline with timing data
  41267. {
  41268. name: 'Segment',
  41269. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41270. let syncPoint = null;
  41271. let lastDistance = null;
  41272. currentTime = currentTime || 0;
  41273. const partsAndSegments = getPartsAndSegments(playlist);
  41274. for (let i = 0; i < partsAndSegments.length; i++) {
  41275. // start from the end and loop backwards for live
  41276. // or start from the front and loop forwards for non-live
  41277. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41278. const partAndSegment = partsAndSegments[index];
  41279. const segment = partAndSegment.segment;
  41280. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  41281. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  41282. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  41283. // currentTime and can stop looking for better candidates
  41284. if (lastDistance !== null && lastDistance < distance) {
  41285. break;
  41286. }
  41287. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41288. lastDistance = distance;
  41289. syncPoint = {
  41290. time: start,
  41291. segmentIndex: partAndSegment.segmentIndex,
  41292. partIndex: partAndSegment.partIndex
  41293. };
  41294. }
  41295. }
  41296. }
  41297. return syncPoint;
  41298. }
  41299. },
  41300. // Stategy "Discontinuity": We have a discontinuity with a known
  41301. // display-time
  41302. {
  41303. name: 'Discontinuity',
  41304. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41305. let syncPoint = null;
  41306. currentTime = currentTime || 0;
  41307. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41308. let lastDistance = null;
  41309. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  41310. const segmentIndex = playlist.discontinuityStarts[i];
  41311. const discontinuity = playlist.discontinuitySequence + i + 1;
  41312. const discontinuitySync = syncController.discontinuities[discontinuity];
  41313. if (discontinuitySync) {
  41314. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  41315. // currentTime and can stop looking for better candidates
  41316. if (lastDistance !== null && lastDistance < distance) {
  41317. break;
  41318. }
  41319. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41320. lastDistance = distance;
  41321. syncPoint = {
  41322. time: discontinuitySync.time,
  41323. segmentIndex,
  41324. partIndex: null
  41325. };
  41326. }
  41327. }
  41328. }
  41329. }
  41330. return syncPoint;
  41331. }
  41332. },
  41333. // Stategy "Playlist": We have a playlist with a known mapping of
  41334. // segment index to display time
  41335. {
  41336. name: 'Playlist',
  41337. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  41338. if (playlist.syncInfo) {
  41339. const syncPoint = {
  41340. time: playlist.syncInfo.time,
  41341. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  41342. partIndex: null
  41343. };
  41344. return syncPoint;
  41345. }
  41346. return null;
  41347. }
  41348. }];
  41349. class SyncController extends videojs.EventTarget {
  41350. constructor(options = {}) {
  41351. super(); // ...for synching across variants
  41352. this.timelines = [];
  41353. this.discontinuities = [];
  41354. this.timelineToDatetimeMappings = {};
  41355. this.logger_ = logger('SyncController');
  41356. }
  41357. /**
  41358. * Find a sync-point for the playlist specified
  41359. *
  41360. * A sync-point is defined as a known mapping from display-time to
  41361. * a segment-index in the current playlist.
  41362. *
  41363. * @param {Playlist} playlist
  41364. * The playlist that needs a sync-point
  41365. * @param {number} duration
  41366. * Duration of the MediaSource (Infinite if playing a live source)
  41367. * @param {number} currentTimeline
  41368. * The last timeline from which a segment was loaded
  41369. * @return {Object}
  41370. * A sync-point object
  41371. */
  41372. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  41373. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  41374. if (!syncPoints.length) {
  41375. // Signal that we need to attempt to get a sync-point manually
  41376. // by fetching a segment in the playlist and constructing
  41377. // a sync-point from that information
  41378. return null;
  41379. } // Now find the sync-point that is closest to the currentTime because
  41380. // that should result in the most accurate guess about which segment
  41381. // to fetch
  41382. return this.selectSyncPoint_(syncPoints, {
  41383. key: 'time',
  41384. value: currentTime
  41385. });
  41386. }
  41387. /**
  41388. * Calculate the amount of time that has expired off the playlist during playback
  41389. *
  41390. * @param {Playlist} playlist
  41391. * Playlist object to calculate expired from
  41392. * @param {number} duration
  41393. * Duration of the MediaSource (Infinity if playling a live source)
  41394. * @return {number|null}
  41395. * The amount of time that has expired off the playlist during playback. Null
  41396. * if no sync-points for the playlist can be found.
  41397. */
  41398. getExpiredTime(playlist, duration) {
  41399. if (!playlist || !playlist.segments) {
  41400. return null;
  41401. }
  41402. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  41403. if (!syncPoints.length) {
  41404. return null;
  41405. }
  41406. const syncPoint = this.selectSyncPoint_(syncPoints, {
  41407. key: 'segmentIndex',
  41408. value: 0
  41409. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  41410. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  41411. if (syncPoint.segmentIndex > 0) {
  41412. syncPoint.time *= -1;
  41413. }
  41414. return Math.abs(syncPoint.time + sumDurations({
  41415. defaultDuration: playlist.targetDuration,
  41416. durationList: playlist.segments,
  41417. startIndex: syncPoint.segmentIndex,
  41418. endIndex: 0
  41419. }));
  41420. }
  41421. /**
  41422. * Runs each sync-point strategy and returns a list of sync-points returned by the
  41423. * strategies
  41424. *
  41425. * @private
  41426. * @param {Playlist} playlist
  41427. * The playlist that needs a sync-point
  41428. * @param {number} duration
  41429. * Duration of the MediaSource (Infinity if playing a live source)
  41430. * @param {number} currentTimeline
  41431. * The last timeline from which a segment was loaded
  41432. * @return {Array}
  41433. * A list of sync-point objects
  41434. */
  41435. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  41436. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  41437. for (let i = 0; i < syncPointStrategies.length; i++) {
  41438. const strategy = syncPointStrategies[i];
  41439. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  41440. if (syncPoint) {
  41441. syncPoint.strategy = strategy.name;
  41442. syncPoints.push({
  41443. strategy: strategy.name,
  41444. syncPoint
  41445. });
  41446. }
  41447. }
  41448. return syncPoints;
  41449. }
  41450. /**
  41451. * Selects the sync-point nearest the specified target
  41452. *
  41453. * @private
  41454. * @param {Array} syncPoints
  41455. * List of sync-points to select from
  41456. * @param {Object} target
  41457. * Object specifying the property and value we are targeting
  41458. * @param {string} target.key
  41459. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  41460. * @param {number} target.value
  41461. * The value to target for the specified key.
  41462. * @return {Object}
  41463. * The sync-point nearest the target
  41464. */
  41465. selectSyncPoint_(syncPoints, target) {
  41466. let bestSyncPoint = syncPoints[0].syncPoint;
  41467. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  41468. let bestStrategy = syncPoints[0].strategy;
  41469. for (let i = 1; i < syncPoints.length; i++) {
  41470. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  41471. if (newDistance < bestDistance) {
  41472. bestDistance = newDistance;
  41473. bestSyncPoint = syncPoints[i].syncPoint;
  41474. bestStrategy = syncPoints[i].strategy;
  41475. }
  41476. }
  41477. this.logger_(`syncPoint for [${target.key}: ${target.value}] chosen with strategy` + ` [${bestStrategy}]: [time:${bestSyncPoint.time},` + ` segmentIndex:${bestSyncPoint.segmentIndex}` + (typeof bestSyncPoint.partIndex === 'number' ? `,partIndex:${bestSyncPoint.partIndex}` : '') + ']');
  41478. return bestSyncPoint;
  41479. }
  41480. /**
  41481. * Save any meta-data present on the segments when segments leave
  41482. * the live window to the playlist to allow for synchronization at the
  41483. * playlist level later.
  41484. *
  41485. * @param {Playlist} oldPlaylist - The previous active playlist
  41486. * @param {Playlist} newPlaylist - The updated and most current playlist
  41487. */
  41488. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  41489. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  41490. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  41491. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  41492. return;
  41493. } // When a segment expires from the playlist and it has a start time
  41494. // save that information as a possible sync-point reference in future
  41495. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  41496. const lastRemovedSegment = oldPlaylist.segments[i];
  41497. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  41498. newPlaylist.syncInfo = {
  41499. mediaSequence: oldPlaylist.mediaSequence + i,
  41500. time: lastRemovedSegment.start
  41501. };
  41502. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  41503. this.trigger('syncinfoupdate');
  41504. break;
  41505. }
  41506. }
  41507. }
  41508. /**
  41509. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  41510. * before segments start to load.
  41511. *
  41512. * @param {Playlist} playlist - The currently active playlist
  41513. */
  41514. setDateTimeMappingForStart(playlist) {
  41515. // It's possible for the playlist to be updated before playback starts, meaning time
  41516. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  41517. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  41518. // unless the mappings are cleared.
  41519. this.timelineToDatetimeMappings = {};
  41520. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  41521. const firstSegment = playlist.segments[0];
  41522. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  41523. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  41524. }
  41525. }
  41526. /**
  41527. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  41528. * based on the latest timing information.
  41529. *
  41530. * @param {Object} options
  41531. * Options object
  41532. * @param {SegmentInfo} options.segmentInfo
  41533. * The current active request information
  41534. * @param {boolean} options.shouldSaveTimelineMapping
  41535. * If there's a timeline change, determines if the timeline mapping should be
  41536. * saved for timeline mapping and program date time mappings.
  41537. */
  41538. saveSegmentTimingInfo({
  41539. segmentInfo,
  41540. shouldSaveTimelineMapping
  41541. }) {
  41542. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  41543. const segment = segmentInfo.segment;
  41544. if (didCalculateSegmentTimeMapping) {
  41545. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  41546. // now with segment timing information
  41547. if (!segmentInfo.playlist.syncInfo) {
  41548. segmentInfo.playlist.syncInfo = {
  41549. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  41550. time: segment.start
  41551. };
  41552. }
  41553. }
  41554. const dateTime = segment.dateTimeObject;
  41555. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  41556. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  41557. }
  41558. }
  41559. timestampOffsetForTimeline(timeline) {
  41560. if (typeof this.timelines[timeline] === 'undefined') {
  41561. return null;
  41562. }
  41563. return this.timelines[timeline].time;
  41564. }
  41565. mappingForTimeline(timeline) {
  41566. if (typeof this.timelines[timeline] === 'undefined') {
  41567. return null;
  41568. }
  41569. return this.timelines[timeline].mapping;
  41570. }
  41571. /**
  41572. * Use the "media time" for a segment to generate a mapping to "display time" and
  41573. * save that display time to the segment.
  41574. *
  41575. * @private
  41576. * @param {SegmentInfo} segmentInfo
  41577. * The current active request information
  41578. * @param {Object} timingInfo
  41579. * The start and end time of the current segment in "media time"
  41580. * @param {boolean} shouldSaveTimelineMapping
  41581. * If there's a timeline change, determines if the timeline mapping should be
  41582. * saved in timelines.
  41583. * @return {boolean}
  41584. * Returns false if segment time mapping could not be calculated
  41585. */
  41586. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  41587. // TODO: remove side effects
  41588. const segment = segmentInfo.segment;
  41589. const part = segmentInfo.part;
  41590. let mappingObj = this.timelines[segmentInfo.timeline];
  41591. let start;
  41592. let end;
  41593. if (typeof segmentInfo.timestampOffset === 'number') {
  41594. mappingObj = {
  41595. time: segmentInfo.startOfSegment,
  41596. mapping: segmentInfo.startOfSegment - timingInfo.start
  41597. };
  41598. if (shouldSaveTimelineMapping) {
  41599. this.timelines[segmentInfo.timeline] = mappingObj;
  41600. this.trigger('timestampoffset');
  41601. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  41602. }
  41603. start = segmentInfo.startOfSegment;
  41604. end = timingInfo.end + mappingObj.mapping;
  41605. } else if (mappingObj) {
  41606. start = timingInfo.start + mappingObj.mapping;
  41607. end = timingInfo.end + mappingObj.mapping;
  41608. } else {
  41609. return false;
  41610. }
  41611. if (part) {
  41612. part.start = start;
  41613. part.end = end;
  41614. } // If we don't have a segment start yet or the start value we got
  41615. // is less than our current segment.start value, save a new start value.
  41616. // We have to do this because parts will have segment timing info saved
  41617. // multiple times and we want segment start to be the earliest part start
  41618. // value for that segment.
  41619. if (!segment.start || start < segment.start) {
  41620. segment.start = start;
  41621. }
  41622. segment.end = end;
  41623. return true;
  41624. }
  41625. /**
  41626. * Each time we have discontinuity in the playlist, attempt to calculate the location
  41627. * in display of the start of the discontinuity and save that. We also save an accuracy
  41628. * value so that we save values with the most accuracy (closest to 0.)
  41629. *
  41630. * @private
  41631. * @param {SegmentInfo} segmentInfo - The current active request information
  41632. */
  41633. saveDiscontinuitySyncInfo_(segmentInfo) {
  41634. const playlist = segmentInfo.playlist;
  41635. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  41636. // the start of the range and it's accuracy is 0 (greater accuracy values
  41637. // mean more approximation)
  41638. if (segment.discontinuity) {
  41639. this.discontinuities[segment.timeline] = {
  41640. time: segment.start,
  41641. accuracy: 0
  41642. };
  41643. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41644. // Search for future discontinuities that we can provide better timing
  41645. // information for and save that information for sync purposes
  41646. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  41647. const segmentIndex = playlist.discontinuityStarts[i];
  41648. const discontinuity = playlist.discontinuitySequence + i + 1;
  41649. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  41650. const accuracy = Math.abs(mediaIndexDiff);
  41651. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  41652. let time;
  41653. if (mediaIndexDiff < 0) {
  41654. time = segment.start - sumDurations({
  41655. defaultDuration: playlist.targetDuration,
  41656. durationList: playlist.segments,
  41657. startIndex: segmentInfo.mediaIndex,
  41658. endIndex: segmentIndex
  41659. });
  41660. } else {
  41661. time = segment.end + sumDurations({
  41662. defaultDuration: playlist.targetDuration,
  41663. durationList: playlist.segments,
  41664. startIndex: segmentInfo.mediaIndex + 1,
  41665. endIndex: segmentIndex
  41666. });
  41667. }
  41668. this.discontinuities[discontinuity] = {
  41669. time,
  41670. accuracy
  41671. };
  41672. }
  41673. }
  41674. }
  41675. }
  41676. dispose() {
  41677. this.trigger('dispose');
  41678. this.off();
  41679. }
  41680. }
  41681. /**
  41682. * The TimelineChangeController acts as a source for segment loaders to listen for and
  41683. * keep track of latest and pending timeline changes. This is useful to ensure proper
  41684. * sync, as each loader may need to make a consideration for what timeline the other
  41685. * loader is on before making changes which could impact the other loader's media.
  41686. *
  41687. * @class TimelineChangeController
  41688. * @extends videojs.EventTarget
  41689. */
  41690. class TimelineChangeController extends videojs.EventTarget {
  41691. constructor() {
  41692. super();
  41693. this.pendingTimelineChanges_ = {};
  41694. this.lastTimelineChanges_ = {};
  41695. }
  41696. clearPendingTimelineChange(type) {
  41697. this.pendingTimelineChanges_[type] = null;
  41698. this.trigger('pendingtimelinechange');
  41699. }
  41700. pendingTimelineChange({
  41701. type,
  41702. from,
  41703. to
  41704. }) {
  41705. if (typeof from === 'number' && typeof to === 'number') {
  41706. this.pendingTimelineChanges_[type] = {
  41707. type,
  41708. from,
  41709. to
  41710. };
  41711. this.trigger('pendingtimelinechange');
  41712. }
  41713. return this.pendingTimelineChanges_[type];
  41714. }
  41715. lastTimelineChange({
  41716. type,
  41717. from,
  41718. to
  41719. }) {
  41720. if (typeof from === 'number' && typeof to === 'number') {
  41721. this.lastTimelineChanges_[type] = {
  41722. type,
  41723. from,
  41724. to
  41725. };
  41726. delete this.pendingTimelineChanges_[type];
  41727. this.trigger('timelinechange');
  41728. }
  41729. return this.lastTimelineChanges_[type];
  41730. }
  41731. dispose() {
  41732. this.trigger('dispose');
  41733. this.pendingTimelineChanges_ = {};
  41734. this.lastTimelineChanges_ = {};
  41735. this.off();
  41736. }
  41737. }
  41738. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  41739. const workerCode = transform(getWorkerString(function () {
  41740. /**
  41741. * @file stream.js
  41742. */
  41743. /**
  41744. * A lightweight readable stream implemention that handles event dispatching.
  41745. *
  41746. * @class Stream
  41747. */
  41748. var Stream = /*#__PURE__*/function () {
  41749. function Stream() {
  41750. this.listeners = {};
  41751. }
  41752. /**
  41753. * Add a listener for a specified event type.
  41754. *
  41755. * @param {string} type the event name
  41756. * @param {Function} listener the callback to be invoked when an event of
  41757. * the specified type occurs
  41758. */
  41759. var _proto = Stream.prototype;
  41760. _proto.on = function on(type, listener) {
  41761. if (!this.listeners[type]) {
  41762. this.listeners[type] = [];
  41763. }
  41764. this.listeners[type].push(listener);
  41765. }
  41766. /**
  41767. * Remove a listener for a specified event type.
  41768. *
  41769. * @param {string} type the event name
  41770. * @param {Function} listener a function previously registered for this
  41771. * type of event through `on`
  41772. * @return {boolean} if we could turn it off or not
  41773. */;
  41774. _proto.off = function off(type, listener) {
  41775. if (!this.listeners[type]) {
  41776. return false;
  41777. }
  41778. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  41779. // In Video.js we slice listener functions
  41780. // on trigger so that it does not mess up the order
  41781. // while we loop through.
  41782. //
  41783. // Here we slice on off so that the loop in trigger
  41784. // can continue using it's old reference to loop without
  41785. // messing up the order.
  41786. this.listeners[type] = this.listeners[type].slice(0);
  41787. this.listeners[type].splice(index, 1);
  41788. return index > -1;
  41789. }
  41790. /**
  41791. * Trigger an event of the specified type on this stream. Any additional
  41792. * arguments to this function are passed as parameters to event listeners.
  41793. *
  41794. * @param {string} type the event name
  41795. */;
  41796. _proto.trigger = function trigger(type) {
  41797. var callbacks = this.listeners[type];
  41798. if (!callbacks) {
  41799. return;
  41800. } // Slicing the arguments on every invocation of this method
  41801. // can add a significant amount of overhead. Avoid the
  41802. // intermediate object creation for the common case of a
  41803. // single callback argument
  41804. if (arguments.length === 2) {
  41805. var length = callbacks.length;
  41806. for (var i = 0; i < length; ++i) {
  41807. callbacks[i].call(this, arguments[1]);
  41808. }
  41809. } else {
  41810. var args = Array.prototype.slice.call(arguments, 1);
  41811. var _length = callbacks.length;
  41812. for (var _i = 0; _i < _length; ++_i) {
  41813. callbacks[_i].apply(this, args);
  41814. }
  41815. }
  41816. }
  41817. /**
  41818. * Destroys the stream and cleans up.
  41819. */;
  41820. _proto.dispose = function dispose() {
  41821. this.listeners = {};
  41822. }
  41823. /**
  41824. * Forwards all `data` events on this stream to the destination stream. The
  41825. * destination stream should provide a method `push` to receive the data
  41826. * events as they arrive.
  41827. *
  41828. * @param {Stream} destination the stream that will receive all `data` events
  41829. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  41830. */;
  41831. _proto.pipe = function pipe(destination) {
  41832. this.on('data', function (data) {
  41833. destination.push(data);
  41834. });
  41835. };
  41836. return Stream;
  41837. }();
  41838. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  41839. /**
  41840. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  41841. *
  41842. * @param padded {Uint8Array} unencrypted bytes that have been padded
  41843. * @return {Uint8Array} the unpadded bytes
  41844. * @see http://tools.ietf.org/html/rfc5652
  41845. */
  41846. function unpad(padded) {
  41847. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  41848. }
  41849. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  41850. /**
  41851. * @file aes.js
  41852. *
  41853. * This file contains an adaptation of the AES decryption algorithm
  41854. * from the Standford Javascript Cryptography Library. That work is
  41855. * covered by the following copyright and permissions notice:
  41856. *
  41857. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  41858. * All rights reserved.
  41859. *
  41860. * Redistribution and use in source and binary forms, with or without
  41861. * modification, are permitted provided that the following conditions are
  41862. * met:
  41863. *
  41864. * 1. Redistributions of source code must retain the above copyright
  41865. * notice, this list of conditions and the following disclaimer.
  41866. *
  41867. * 2. Redistributions in binary form must reproduce the above
  41868. * copyright notice, this list of conditions and the following
  41869. * disclaimer in the documentation and/or other materials provided
  41870. * with the distribution.
  41871. *
  41872. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  41873. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  41874. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  41875. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  41876. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  41877. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  41878. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  41879. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  41880. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  41881. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  41882. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41883. *
  41884. * The views and conclusions contained in the software and documentation
  41885. * are those of the authors and should not be interpreted as representing
  41886. * official policies, either expressed or implied, of the authors.
  41887. */
  41888. /**
  41889. * Expand the S-box tables.
  41890. *
  41891. * @private
  41892. */
  41893. const precompute = function () {
  41894. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  41895. const encTable = tables[0];
  41896. const decTable = tables[1];
  41897. const sbox = encTable[4];
  41898. const sboxInv = decTable[4];
  41899. let i;
  41900. let x;
  41901. let xInv;
  41902. const d = [];
  41903. const th = [];
  41904. let x2;
  41905. let x4;
  41906. let x8;
  41907. let s;
  41908. let tEnc;
  41909. let tDec; // Compute double and third tables
  41910. for (i = 0; i < 256; i++) {
  41911. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  41912. }
  41913. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  41914. // Compute sbox
  41915. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  41916. s = s >> 8 ^ s & 255 ^ 99;
  41917. sbox[x] = s;
  41918. sboxInv[s] = x; // Compute MixColumns
  41919. x8 = d[x4 = d[x2 = d[x]]];
  41920. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  41921. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  41922. for (i = 0; i < 4; i++) {
  41923. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  41924. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  41925. }
  41926. } // Compactify. Considerable speedup on Firefox.
  41927. for (i = 0; i < 5; i++) {
  41928. encTable[i] = encTable[i].slice(0);
  41929. decTable[i] = decTable[i].slice(0);
  41930. }
  41931. return tables;
  41932. };
  41933. let aesTables = null;
  41934. /**
  41935. * Schedule out an AES key for both encryption and decryption. This
  41936. * is a low-level class. Use a cipher mode to do bulk encryption.
  41937. *
  41938. * @class AES
  41939. * @param key {Array} The key as an array of 4, 6 or 8 words.
  41940. */
  41941. class AES {
  41942. constructor(key) {
  41943. /**
  41944. * The expanded S-box and inverse S-box tables. These will be computed
  41945. * on the client so that we don't have to send them down the wire.
  41946. *
  41947. * There are two tables, _tables[0] is for encryption and
  41948. * _tables[1] is for decryption.
  41949. *
  41950. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  41951. * last (_tables[01][4]) is the S-box itself.
  41952. *
  41953. * @private
  41954. */
  41955. // if we have yet to precompute the S-box tables
  41956. // do so now
  41957. if (!aesTables) {
  41958. aesTables = precompute();
  41959. } // then make a copy of that object for use
  41960. this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
  41961. let i;
  41962. let j;
  41963. let tmp;
  41964. const sbox = this._tables[0][4];
  41965. const decTable = this._tables[1];
  41966. const keyLen = key.length;
  41967. let rcon = 1;
  41968. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  41969. throw new Error('Invalid aes key size');
  41970. }
  41971. const encKey = key.slice(0);
  41972. const decKey = [];
  41973. this._key = [encKey, decKey]; // schedule encryption keys
  41974. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  41975. tmp = encKey[i - 1]; // apply sbox
  41976. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  41977. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  41978. if (i % keyLen === 0) {
  41979. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  41980. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  41981. }
  41982. }
  41983. encKey[i] = encKey[i - keyLen] ^ tmp;
  41984. } // schedule decryption keys
  41985. for (j = 0; i; j++, i--) {
  41986. tmp = encKey[j & 3 ? i : i - 4];
  41987. if (i <= 4 || j < 4) {
  41988. decKey[j] = tmp;
  41989. } else {
  41990. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  41991. }
  41992. }
  41993. }
  41994. /**
  41995. * Decrypt 16 bytes, specified as four 32-bit words.
  41996. *
  41997. * @param {number} encrypted0 the first word to decrypt
  41998. * @param {number} encrypted1 the second word to decrypt
  41999. * @param {number} encrypted2 the third word to decrypt
  42000. * @param {number} encrypted3 the fourth word to decrypt
  42001. * @param {Int32Array} out the array to write the decrypted words
  42002. * into
  42003. * @param {number} offset the offset into the output array to start
  42004. * writing results
  42005. * @return {Array} The plaintext.
  42006. */
  42007. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  42008. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  42009. let a = encrypted0 ^ key[0];
  42010. let b = encrypted3 ^ key[1];
  42011. let c = encrypted2 ^ key[2];
  42012. let d = encrypted1 ^ key[3];
  42013. let a2;
  42014. let b2;
  42015. let c2; // key.length === 2 ?
  42016. const nInnerRounds = key.length / 4 - 2;
  42017. let i;
  42018. let kIndex = 4;
  42019. const table = this._tables[1]; // load up the tables
  42020. const table0 = table[0];
  42021. const table1 = table[1];
  42022. const table2 = table[2];
  42023. const table3 = table[3];
  42024. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  42025. for (i = 0; i < nInnerRounds; i++) {
  42026. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  42027. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  42028. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  42029. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  42030. kIndex += 4;
  42031. a = a2;
  42032. b = b2;
  42033. c = c2;
  42034. } // Last round.
  42035. for (i = 0; i < 4; i++) {
  42036. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  42037. a2 = a;
  42038. a = b;
  42039. b = c;
  42040. c = d;
  42041. d = a2;
  42042. }
  42043. }
  42044. }
  42045. /**
  42046. * @file async-stream.js
  42047. */
  42048. /**
  42049. * A wrapper around the Stream class to use setTimeout
  42050. * and run stream "jobs" Asynchronously
  42051. *
  42052. * @class AsyncStream
  42053. * @extends Stream
  42054. */
  42055. class AsyncStream extends Stream {
  42056. constructor() {
  42057. super(Stream);
  42058. this.jobs = [];
  42059. this.delay = 1;
  42060. this.timeout_ = null;
  42061. }
  42062. /**
  42063. * process an async job
  42064. *
  42065. * @private
  42066. */
  42067. processJob_() {
  42068. this.jobs.shift()();
  42069. if (this.jobs.length) {
  42070. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42071. } else {
  42072. this.timeout_ = null;
  42073. }
  42074. }
  42075. /**
  42076. * push a job into the stream
  42077. *
  42078. * @param {Function} job the job to push into the stream
  42079. */
  42080. push(job) {
  42081. this.jobs.push(job);
  42082. if (!this.timeout_) {
  42083. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42084. }
  42085. }
  42086. }
  42087. /**
  42088. * @file decrypter.js
  42089. *
  42090. * An asynchronous implementation of AES-128 CBC decryption with
  42091. * PKCS#7 padding.
  42092. */
  42093. /**
  42094. * Convert network-order (big-endian) bytes into their little-endian
  42095. * representation.
  42096. */
  42097. const ntoh = function (word) {
  42098. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  42099. };
  42100. /**
  42101. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  42102. *
  42103. * @param {Uint8Array} encrypted the encrypted bytes
  42104. * @param {Uint32Array} key the bytes of the decryption key
  42105. * @param {Uint32Array} initVector the initialization vector (IV) to
  42106. * use for the first round of CBC.
  42107. * @return {Uint8Array} the decrypted bytes
  42108. *
  42109. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  42110. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  42111. * @see https://tools.ietf.org/html/rfc2315
  42112. */
  42113. const decrypt = function (encrypted, key, initVector) {
  42114. // word-level access to the encrypted bytes
  42115. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  42116. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  42117. const decrypted = new Uint8Array(encrypted.byteLength);
  42118. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  42119. // decrypted data
  42120. let init0;
  42121. let init1;
  42122. let init2;
  42123. let init3;
  42124. let encrypted0;
  42125. let encrypted1;
  42126. let encrypted2;
  42127. let encrypted3; // iteration variable
  42128. let wordIx; // pull out the words of the IV to ensure we don't modify the
  42129. // passed-in reference and easier access
  42130. init0 = initVector[0];
  42131. init1 = initVector[1];
  42132. init2 = initVector[2];
  42133. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  42134. // to each decrypted block
  42135. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  42136. // convert big-endian (network order) words into little-endian
  42137. // (javascript order)
  42138. encrypted0 = ntoh(encrypted32[wordIx]);
  42139. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  42140. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  42141. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  42142. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  42143. // plaintext
  42144. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  42145. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  42146. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  42147. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  42148. init0 = encrypted0;
  42149. init1 = encrypted1;
  42150. init2 = encrypted2;
  42151. init3 = encrypted3;
  42152. }
  42153. return decrypted;
  42154. };
  42155. /**
  42156. * The `Decrypter` class that manages decryption of AES
  42157. * data through `AsyncStream` objects and the `decrypt`
  42158. * function
  42159. *
  42160. * @param {Uint8Array} encrypted the encrypted bytes
  42161. * @param {Uint32Array} key the bytes of the decryption key
  42162. * @param {Uint32Array} initVector the initialization vector (IV) to
  42163. * @param {Function} done the function to run when done
  42164. * @class Decrypter
  42165. */
  42166. class Decrypter {
  42167. constructor(encrypted, key, initVector, done) {
  42168. const step = Decrypter.STEP;
  42169. const encrypted32 = new Int32Array(encrypted.buffer);
  42170. const decrypted = new Uint8Array(encrypted.byteLength);
  42171. let i = 0;
  42172. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  42173. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42174. for (i = step; i < encrypted32.length; i += step) {
  42175. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  42176. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42177. } // invoke the done() callback when everything is finished
  42178. this.asyncStream_.push(function () {
  42179. // remove pkcs#7 padding from the decrypted bytes
  42180. done(null, unpad(decrypted));
  42181. });
  42182. }
  42183. /**
  42184. * a getter for step the maximum number of bytes to process at one time
  42185. *
  42186. * @return {number} the value of step 32000
  42187. */
  42188. static get STEP() {
  42189. // 4 * 8000;
  42190. return 32000;
  42191. }
  42192. /**
  42193. * @private
  42194. */
  42195. decryptChunk_(encrypted, key, initVector, decrypted) {
  42196. return function () {
  42197. const bytes = decrypt(encrypted, key, initVector);
  42198. decrypted.set(bytes, encrypted.byteOffset);
  42199. };
  42200. }
  42201. }
  42202. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  42203. var win;
  42204. if (typeof window !== "undefined") {
  42205. win = window;
  42206. } else if (typeof commonjsGlobal !== "undefined") {
  42207. win = commonjsGlobal;
  42208. } else if (typeof self !== "undefined") {
  42209. win = self;
  42210. } else {
  42211. win = {};
  42212. }
  42213. var window_1 = win;
  42214. var isArrayBufferView = function isArrayBufferView(obj) {
  42215. if (ArrayBuffer.isView === 'function') {
  42216. return ArrayBuffer.isView(obj);
  42217. }
  42218. return obj && obj.buffer instanceof ArrayBuffer;
  42219. };
  42220. var BigInt = window_1.BigInt || Number;
  42221. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  42222. (function () {
  42223. var a = new Uint16Array([0xFFCC]);
  42224. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  42225. if (b[0] === 0xFF) {
  42226. return 'big';
  42227. }
  42228. if (b[0] === 0xCC) {
  42229. return 'little';
  42230. }
  42231. return 'unknown';
  42232. })();
  42233. /**
  42234. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  42235. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  42236. *
  42237. * @param {Object} message
  42238. * Object of properties and values to send to the web worker
  42239. * @return {Object}
  42240. * Modified message with TypedArray values expanded
  42241. * @function createTransferableMessage
  42242. */
  42243. const createTransferableMessage = function (message) {
  42244. const transferable = {};
  42245. Object.keys(message).forEach(key => {
  42246. const value = message[key];
  42247. if (isArrayBufferView(value)) {
  42248. transferable[key] = {
  42249. bytes: value.buffer,
  42250. byteOffset: value.byteOffset,
  42251. byteLength: value.byteLength
  42252. };
  42253. } else {
  42254. transferable[key] = value;
  42255. }
  42256. });
  42257. return transferable;
  42258. };
  42259. /* global self */
  42260. /**
  42261. * Our web worker interface so that things can talk to aes-decrypter
  42262. * that will be running in a web worker. the scope is passed to this by
  42263. * webworkify.
  42264. */
  42265. self.onmessage = function (event) {
  42266. const data = event.data;
  42267. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  42268. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  42269. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  42270. /* eslint-disable no-new, handle-callback-err */
  42271. new Decrypter(encrypted, key, iv, function (err, bytes) {
  42272. self.postMessage(createTransferableMessage({
  42273. source: data.source,
  42274. decrypted: bytes
  42275. }), [bytes.buffer]);
  42276. });
  42277. /* eslint-enable */
  42278. };
  42279. }));
  42280. var Decrypter = factory(workerCode);
  42281. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  42282. /**
  42283. * Convert the properties of an HLS track into an audioTrackKind.
  42284. *
  42285. * @private
  42286. */
  42287. const audioTrackKind_ = properties => {
  42288. let kind = properties.default ? 'main' : 'alternative';
  42289. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  42290. kind = 'main-desc';
  42291. }
  42292. return kind;
  42293. };
  42294. /**
  42295. * Pause provided segment loader and playlist loader if active
  42296. *
  42297. * @param {SegmentLoader} segmentLoader
  42298. * SegmentLoader to pause
  42299. * @param {Object} mediaType
  42300. * Active media type
  42301. * @function stopLoaders
  42302. */
  42303. const stopLoaders = (segmentLoader, mediaType) => {
  42304. segmentLoader.abort();
  42305. segmentLoader.pause();
  42306. if (mediaType && mediaType.activePlaylistLoader) {
  42307. mediaType.activePlaylistLoader.pause();
  42308. mediaType.activePlaylistLoader = null;
  42309. }
  42310. };
  42311. /**
  42312. * Start loading provided segment loader and playlist loader
  42313. *
  42314. * @param {PlaylistLoader} playlistLoader
  42315. * PlaylistLoader to start loading
  42316. * @param {Object} mediaType
  42317. * Active media type
  42318. * @function startLoaders
  42319. */
  42320. const startLoaders = (playlistLoader, mediaType) => {
  42321. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  42322. // playlist loader
  42323. mediaType.activePlaylistLoader = playlistLoader;
  42324. playlistLoader.load();
  42325. };
  42326. /**
  42327. * Returns a function to be called when the media group changes. It performs a
  42328. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  42329. * change of group is merely a rendition switch of the same content at another encoding,
  42330. * rather than a change of content, such as switching audio from English to Spanish.
  42331. *
  42332. * @param {string} type
  42333. * MediaGroup type
  42334. * @param {Object} settings
  42335. * Object containing required information for media groups
  42336. * @return {Function}
  42337. * Handler for a non-destructive resync of SegmentLoader when the active media
  42338. * group changes.
  42339. * @function onGroupChanged
  42340. */
  42341. const onGroupChanged = (type, settings) => () => {
  42342. const {
  42343. segmentLoaders: {
  42344. [type]: segmentLoader,
  42345. main: mainSegmentLoader
  42346. },
  42347. mediaTypes: {
  42348. [type]: mediaType
  42349. }
  42350. } = settings;
  42351. const activeTrack = mediaType.activeTrack();
  42352. const activeGroup = mediaType.getActiveGroup();
  42353. const previousActiveLoader = mediaType.activePlaylistLoader;
  42354. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  42355. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  42356. return;
  42357. }
  42358. mediaType.lastGroup_ = activeGroup;
  42359. mediaType.lastTrack_ = activeTrack;
  42360. stopLoaders(segmentLoader, mediaType);
  42361. if (!activeGroup || activeGroup.isMainPlaylist) {
  42362. // there is no group active or active group is a main playlist and won't change
  42363. return;
  42364. }
  42365. if (!activeGroup.playlistLoader) {
  42366. if (previousActiveLoader) {
  42367. // The previous group had a playlist loader but the new active group does not
  42368. // this means we are switching from demuxed to muxed audio. In this case we want to
  42369. // do a destructive reset of the main segment loader and not restart the audio
  42370. // loaders.
  42371. mainSegmentLoader.resetEverything();
  42372. }
  42373. return;
  42374. } // Non-destructive resync
  42375. segmentLoader.resyncLoader();
  42376. startLoaders(activeGroup.playlistLoader, mediaType);
  42377. };
  42378. const onGroupChanging = (type, settings) => () => {
  42379. const {
  42380. segmentLoaders: {
  42381. [type]: segmentLoader
  42382. },
  42383. mediaTypes: {
  42384. [type]: mediaType
  42385. }
  42386. } = settings;
  42387. mediaType.lastGroup_ = null;
  42388. segmentLoader.abort();
  42389. segmentLoader.pause();
  42390. };
  42391. /**
  42392. * Returns a function to be called when the media track changes. It performs a
  42393. * destructive reset of the SegmentLoader to ensure we start loading as close to
  42394. * currentTime as possible.
  42395. *
  42396. * @param {string} type
  42397. * MediaGroup type
  42398. * @param {Object} settings
  42399. * Object containing required information for media groups
  42400. * @return {Function}
  42401. * Handler for a destructive reset of SegmentLoader when the active media
  42402. * track changes.
  42403. * @function onTrackChanged
  42404. */
  42405. const onTrackChanged = (type, settings) => () => {
  42406. const {
  42407. mainPlaylistLoader,
  42408. segmentLoaders: {
  42409. [type]: segmentLoader,
  42410. main: mainSegmentLoader
  42411. },
  42412. mediaTypes: {
  42413. [type]: mediaType
  42414. }
  42415. } = settings;
  42416. const activeTrack = mediaType.activeTrack();
  42417. const activeGroup = mediaType.getActiveGroup();
  42418. const previousActiveLoader = mediaType.activePlaylistLoader;
  42419. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  42420. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  42421. return;
  42422. }
  42423. mediaType.lastGroup_ = activeGroup;
  42424. mediaType.lastTrack_ = activeTrack;
  42425. stopLoaders(segmentLoader, mediaType);
  42426. if (!activeGroup) {
  42427. // there is no group active so we do not want to restart loaders
  42428. return;
  42429. }
  42430. if (activeGroup.isMainPlaylist) {
  42431. // track did not change, do nothing
  42432. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  42433. return;
  42434. }
  42435. const pc = settings.vhs.playlistController_;
  42436. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  42437. if (pc.media() === newPlaylist) {
  42438. return;
  42439. }
  42440. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  42441. mainPlaylistLoader.pause();
  42442. mainSegmentLoader.resetEverything();
  42443. pc.fastQualityChange_(newPlaylist);
  42444. return;
  42445. }
  42446. if (type === 'AUDIO') {
  42447. if (!activeGroup.playlistLoader) {
  42448. // when switching from demuxed audio/video to muxed audio/video (noted by no
  42449. // playlist loader for the audio group), we want to do a destructive reset of the
  42450. // main segment loader and not restart the audio loaders
  42451. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  42452. // it should be stopped
  42453. mainSegmentLoader.resetEverything();
  42454. return;
  42455. } // although the segment loader is an audio segment loader, call the setAudio
  42456. // function to ensure it is prepared to re-append the init segment (or handle other
  42457. // config changes)
  42458. segmentLoader.setAudio(true);
  42459. mainSegmentLoader.setAudio(false);
  42460. }
  42461. if (previousActiveLoader === activeGroup.playlistLoader) {
  42462. // Nothing has actually changed. This can happen because track change events can fire
  42463. // multiple times for a "single" change. One for enabling the new active track, and
  42464. // one for disabling the track that was active
  42465. startLoaders(activeGroup.playlistLoader, mediaType);
  42466. return;
  42467. }
  42468. if (segmentLoader.track) {
  42469. // For WebVTT, set the new text track in the segmentloader
  42470. segmentLoader.track(activeTrack);
  42471. } // destructive reset
  42472. segmentLoader.resetEverything();
  42473. startLoaders(activeGroup.playlistLoader, mediaType);
  42474. };
  42475. const onError = {
  42476. /**
  42477. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42478. * an error.
  42479. *
  42480. * @param {string} type
  42481. * MediaGroup type
  42482. * @param {Object} settings
  42483. * Object containing required information for media groups
  42484. * @return {Function}
  42485. * Error handler. Logs warning (or error if the playlist is excluded) to
  42486. * console and switches back to default audio track.
  42487. * @function onError.AUDIO
  42488. */
  42489. AUDIO: (type, settings) => () => {
  42490. const {
  42491. segmentLoaders: {
  42492. [type]: segmentLoader
  42493. },
  42494. mediaTypes: {
  42495. [type]: mediaType
  42496. },
  42497. excludePlaylist
  42498. } = settings;
  42499. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  42500. const activeTrack = mediaType.activeTrack();
  42501. const activeGroup = mediaType.activeGroup();
  42502. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  42503. const defaultTrack = mediaType.tracks[id];
  42504. if (activeTrack === defaultTrack) {
  42505. // Default track encountered an error. All we can do now is exclude the current
  42506. // rendition and hope another will switch audio groups
  42507. excludePlaylist({
  42508. error: {
  42509. message: 'Problem encountered loading the default audio track.'
  42510. }
  42511. });
  42512. return;
  42513. }
  42514. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  42515. for (const trackId in mediaType.tracks) {
  42516. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  42517. }
  42518. mediaType.onTrackChanged();
  42519. },
  42520. /**
  42521. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42522. * an error.
  42523. *
  42524. * @param {string} type
  42525. * MediaGroup type
  42526. * @param {Object} settings
  42527. * Object containing required information for media groups
  42528. * @return {Function}
  42529. * Error handler. Logs warning to console and disables the active subtitle track
  42530. * @function onError.SUBTITLES
  42531. */
  42532. SUBTITLES: (type, settings) => () => {
  42533. const {
  42534. segmentLoaders: {
  42535. [type]: segmentLoader
  42536. },
  42537. mediaTypes: {
  42538. [type]: mediaType
  42539. }
  42540. } = settings;
  42541. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  42542. stopLoaders(segmentLoader, mediaType);
  42543. const track = mediaType.activeTrack();
  42544. if (track) {
  42545. track.mode = 'disabled';
  42546. }
  42547. mediaType.onTrackChanged();
  42548. }
  42549. };
  42550. const setupListeners = {
  42551. /**
  42552. * Setup event listeners for audio playlist loader
  42553. *
  42554. * @param {string} type
  42555. * MediaGroup type
  42556. * @param {PlaylistLoader|null} playlistLoader
  42557. * PlaylistLoader to register listeners on
  42558. * @param {Object} settings
  42559. * Object containing required information for media groups
  42560. * @function setupListeners.AUDIO
  42561. */
  42562. AUDIO: (type, playlistLoader, settings) => {
  42563. if (!playlistLoader) {
  42564. // no playlist loader means audio will be muxed with the video
  42565. return;
  42566. }
  42567. const {
  42568. tech,
  42569. requestOptions,
  42570. segmentLoaders: {
  42571. [type]: segmentLoader
  42572. }
  42573. } = settings;
  42574. playlistLoader.on('loadedmetadata', () => {
  42575. const media = playlistLoader.media();
  42576. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  42577. // permits, start downloading segments
  42578. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42579. segmentLoader.load();
  42580. }
  42581. });
  42582. playlistLoader.on('loadedplaylist', () => {
  42583. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42584. if (!tech.paused()) {
  42585. segmentLoader.load();
  42586. }
  42587. });
  42588. playlistLoader.on('error', onError[type](type, settings));
  42589. },
  42590. /**
  42591. * Setup event listeners for subtitle playlist loader
  42592. *
  42593. * @param {string} type
  42594. * MediaGroup type
  42595. * @param {PlaylistLoader|null} playlistLoader
  42596. * PlaylistLoader to register listeners on
  42597. * @param {Object} settings
  42598. * Object containing required information for media groups
  42599. * @function setupListeners.SUBTITLES
  42600. */
  42601. SUBTITLES: (type, playlistLoader, settings) => {
  42602. const {
  42603. tech,
  42604. requestOptions,
  42605. segmentLoaders: {
  42606. [type]: segmentLoader
  42607. },
  42608. mediaTypes: {
  42609. [type]: mediaType
  42610. }
  42611. } = settings;
  42612. playlistLoader.on('loadedmetadata', () => {
  42613. const media = playlistLoader.media();
  42614. segmentLoader.playlist(media, requestOptions);
  42615. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  42616. // permits, start downloading segments
  42617. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42618. segmentLoader.load();
  42619. }
  42620. });
  42621. playlistLoader.on('loadedplaylist', () => {
  42622. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42623. if (!tech.paused()) {
  42624. segmentLoader.load();
  42625. }
  42626. });
  42627. playlistLoader.on('error', onError[type](type, settings));
  42628. }
  42629. };
  42630. const initialize = {
  42631. /**
  42632. * Setup PlaylistLoaders and AudioTracks for the audio groups
  42633. *
  42634. * @param {string} type
  42635. * MediaGroup type
  42636. * @param {Object} settings
  42637. * Object containing required information for media groups
  42638. * @function initialize.AUDIO
  42639. */
  42640. 'AUDIO': (type, settings) => {
  42641. const {
  42642. vhs,
  42643. sourceType,
  42644. segmentLoaders: {
  42645. [type]: segmentLoader
  42646. },
  42647. requestOptions,
  42648. main: {
  42649. mediaGroups
  42650. },
  42651. mediaTypes: {
  42652. [type]: {
  42653. groups,
  42654. tracks,
  42655. logger_
  42656. }
  42657. },
  42658. mainPlaylistLoader
  42659. } = settings;
  42660. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  42661. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  42662. mediaGroups[type] = {
  42663. main: {
  42664. default: {
  42665. default: true
  42666. }
  42667. }
  42668. };
  42669. if (audioOnlyMain) {
  42670. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  42671. }
  42672. }
  42673. for (const groupId in mediaGroups[type]) {
  42674. if (!groups[groupId]) {
  42675. groups[groupId] = [];
  42676. }
  42677. for (const variantLabel in mediaGroups[type][groupId]) {
  42678. let properties = mediaGroups[type][groupId][variantLabel];
  42679. let playlistLoader;
  42680. if (audioOnlyMain) {
  42681. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  42682. properties.isMainPlaylist = true;
  42683. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  42684. // use the resolved media playlist object
  42685. } else if (sourceType === 'vhs-json' && properties.playlists) {
  42686. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  42687. } else if (properties.resolvedUri) {
  42688. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  42689. // should we even have properties.playlists in this check.
  42690. } else if (properties.playlists && sourceType === 'dash') {
  42691. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  42692. } else {
  42693. // no resolvedUri means the audio is muxed with the video when using this
  42694. // audio track
  42695. playlistLoader = null;
  42696. }
  42697. properties = merge({
  42698. id: variantLabel,
  42699. playlistLoader
  42700. }, properties);
  42701. setupListeners[type](type, properties.playlistLoader, settings);
  42702. groups[groupId].push(properties);
  42703. if (typeof tracks[variantLabel] === 'undefined') {
  42704. const track = new videojs.AudioTrack({
  42705. id: variantLabel,
  42706. kind: audioTrackKind_(properties),
  42707. enabled: false,
  42708. language: properties.language,
  42709. default: properties.default,
  42710. label: variantLabel
  42711. });
  42712. tracks[variantLabel] = track;
  42713. }
  42714. }
  42715. } // setup single error event handler for the segment loader
  42716. segmentLoader.on('error', onError[type](type, settings));
  42717. },
  42718. /**
  42719. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  42720. *
  42721. * @param {string} type
  42722. * MediaGroup type
  42723. * @param {Object} settings
  42724. * Object containing required information for media groups
  42725. * @function initialize.SUBTITLES
  42726. */
  42727. 'SUBTITLES': (type, settings) => {
  42728. const {
  42729. tech,
  42730. vhs,
  42731. sourceType,
  42732. segmentLoaders: {
  42733. [type]: segmentLoader
  42734. },
  42735. requestOptions,
  42736. main: {
  42737. mediaGroups
  42738. },
  42739. mediaTypes: {
  42740. [type]: {
  42741. groups,
  42742. tracks
  42743. }
  42744. },
  42745. mainPlaylistLoader
  42746. } = settings;
  42747. for (const groupId in mediaGroups[type]) {
  42748. if (!groups[groupId]) {
  42749. groups[groupId] = [];
  42750. }
  42751. for (const variantLabel in mediaGroups[type][groupId]) {
  42752. if (mediaGroups[type][groupId][variantLabel].forced) {
  42753. // Subtitle playlists with the forced attribute are not selectable in Safari.
  42754. // According to Apple's HLS Authoring Specification:
  42755. // If content has forced subtitles and regular subtitles in a given language,
  42756. // the regular subtitles track in that language MUST contain both the forced
  42757. // subtitles and the regular subtitles for that language.
  42758. // Because of this requirement and that Safari does not add forced subtitles,
  42759. // forced subtitles are skipped here to maintain consistent experience across
  42760. // all platforms
  42761. continue;
  42762. }
  42763. let properties = mediaGroups[type][groupId][variantLabel];
  42764. let playlistLoader;
  42765. if (sourceType === 'hls') {
  42766. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  42767. } else if (sourceType === 'dash') {
  42768. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  42769. if (!playlists.length) {
  42770. return;
  42771. }
  42772. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  42773. } else if (sourceType === 'vhs-json') {
  42774. playlistLoader = new PlaylistLoader(
  42775. // if the vhs-json object included the media playlist, use the media playlist
  42776. // as provided, otherwise use the resolved URI to load the playlist
  42777. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  42778. }
  42779. properties = merge({
  42780. id: variantLabel,
  42781. playlistLoader
  42782. }, properties);
  42783. setupListeners[type](type, properties.playlistLoader, settings);
  42784. groups[groupId].push(properties);
  42785. if (typeof tracks[variantLabel] === 'undefined') {
  42786. const track = tech.addRemoteTextTrack({
  42787. id: variantLabel,
  42788. kind: 'subtitles',
  42789. default: properties.default && properties.autoselect,
  42790. language: properties.language,
  42791. label: variantLabel
  42792. }, false).track;
  42793. tracks[variantLabel] = track;
  42794. }
  42795. }
  42796. } // setup single error event handler for the segment loader
  42797. segmentLoader.on('error', onError[type](type, settings));
  42798. },
  42799. /**
  42800. * Setup TextTracks for the closed-caption groups
  42801. *
  42802. * @param {String} type
  42803. * MediaGroup type
  42804. * @param {Object} settings
  42805. * Object containing required information for media groups
  42806. * @function initialize['CLOSED-CAPTIONS']
  42807. */
  42808. 'CLOSED-CAPTIONS': (type, settings) => {
  42809. const {
  42810. tech,
  42811. main: {
  42812. mediaGroups
  42813. },
  42814. mediaTypes: {
  42815. [type]: {
  42816. groups,
  42817. tracks
  42818. }
  42819. }
  42820. } = settings;
  42821. for (const groupId in mediaGroups[type]) {
  42822. if (!groups[groupId]) {
  42823. groups[groupId] = [];
  42824. }
  42825. for (const variantLabel in mediaGroups[type][groupId]) {
  42826. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  42827. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  42828. continue;
  42829. }
  42830. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  42831. let newProps = {
  42832. label: variantLabel,
  42833. language: properties.language,
  42834. instreamId: properties.instreamId,
  42835. default: properties.default && properties.autoselect
  42836. };
  42837. if (captionServices[newProps.instreamId]) {
  42838. newProps = merge(newProps, captionServices[newProps.instreamId]);
  42839. }
  42840. if (newProps.default === undefined) {
  42841. delete newProps.default;
  42842. } // No PlaylistLoader is required for Closed-Captions because the captions are
  42843. // embedded within the video stream
  42844. groups[groupId].push(merge({
  42845. id: variantLabel
  42846. }, properties));
  42847. if (typeof tracks[variantLabel] === 'undefined') {
  42848. const track = tech.addRemoteTextTrack({
  42849. id: newProps.instreamId,
  42850. kind: 'captions',
  42851. default: newProps.default,
  42852. language: newProps.language,
  42853. label: newProps.label
  42854. }, false).track;
  42855. tracks[variantLabel] = track;
  42856. }
  42857. }
  42858. }
  42859. }
  42860. };
  42861. const groupMatch = (list, media) => {
  42862. for (let i = 0; i < list.length; i++) {
  42863. if (playlistMatch(media, list[i])) {
  42864. return true;
  42865. }
  42866. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  42867. return true;
  42868. }
  42869. }
  42870. return false;
  42871. };
  42872. /**
  42873. * Returns a function used to get the active group of the provided type
  42874. *
  42875. * @param {string} type
  42876. * MediaGroup type
  42877. * @param {Object} settings
  42878. * Object containing required information for media groups
  42879. * @return {Function}
  42880. * Function that returns the active media group for the provided type. Takes an
  42881. * optional parameter {TextTrack} track. If no track is provided, a list of all
  42882. * variants in the group, otherwise the variant corresponding to the provided
  42883. * track is returned.
  42884. * @function activeGroup
  42885. */
  42886. const activeGroup = (type, settings) => track => {
  42887. const {
  42888. mainPlaylistLoader,
  42889. mediaTypes: {
  42890. [type]: {
  42891. groups
  42892. }
  42893. }
  42894. } = settings;
  42895. const media = mainPlaylistLoader.media();
  42896. if (!media) {
  42897. return null;
  42898. }
  42899. let variants = null; // set to variants to main media active group
  42900. if (media.attributes[type]) {
  42901. variants = groups[media.attributes[type]];
  42902. }
  42903. const groupKeys = Object.keys(groups);
  42904. if (!variants) {
  42905. // find the mainPlaylistLoader media
  42906. // that is in a media group if we are dealing
  42907. // with audio only
  42908. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  42909. for (let i = 0; i < groupKeys.length; i++) {
  42910. const groupPropertyList = groups[groupKeys[i]];
  42911. if (groupMatch(groupPropertyList, media)) {
  42912. variants = groupPropertyList;
  42913. break;
  42914. }
  42915. } // use the main group if it exists
  42916. } else if (groups.main) {
  42917. variants = groups.main; // only one group, use that one
  42918. } else if (groupKeys.length === 1) {
  42919. variants = groups[groupKeys[0]];
  42920. }
  42921. }
  42922. if (typeof track === 'undefined') {
  42923. return variants;
  42924. }
  42925. if (track === null || !variants) {
  42926. // An active track was specified so a corresponding group is expected. track === null
  42927. // means no track is currently active so there is no corresponding group
  42928. return null;
  42929. }
  42930. return variants.filter(props => props.id === track.id)[0] || null;
  42931. };
  42932. const activeTrack = {
  42933. /**
  42934. * Returns a function used to get the active track of type provided
  42935. *
  42936. * @param {string} type
  42937. * MediaGroup type
  42938. * @param {Object} settings
  42939. * Object containing required information for media groups
  42940. * @return {Function}
  42941. * Function that returns the active media track for the provided type. Returns
  42942. * null if no track is active
  42943. * @function activeTrack.AUDIO
  42944. */
  42945. AUDIO: (type, settings) => () => {
  42946. const {
  42947. mediaTypes: {
  42948. [type]: {
  42949. tracks
  42950. }
  42951. }
  42952. } = settings;
  42953. for (const id in tracks) {
  42954. if (tracks[id].enabled) {
  42955. return tracks[id];
  42956. }
  42957. }
  42958. return null;
  42959. },
  42960. /**
  42961. * Returns a function used to get the active track of type provided
  42962. *
  42963. * @param {string} type
  42964. * MediaGroup type
  42965. * @param {Object} settings
  42966. * Object containing required information for media groups
  42967. * @return {Function}
  42968. * Function that returns the active media track for the provided type. Returns
  42969. * null if no track is active
  42970. * @function activeTrack.SUBTITLES
  42971. */
  42972. SUBTITLES: (type, settings) => () => {
  42973. const {
  42974. mediaTypes: {
  42975. [type]: {
  42976. tracks
  42977. }
  42978. }
  42979. } = settings;
  42980. for (const id in tracks) {
  42981. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  42982. return tracks[id];
  42983. }
  42984. }
  42985. return null;
  42986. }
  42987. };
  42988. const getActiveGroup = (type, {
  42989. mediaTypes
  42990. }) => () => {
  42991. const activeTrack_ = mediaTypes[type].activeTrack();
  42992. if (!activeTrack_) {
  42993. return null;
  42994. }
  42995. return mediaTypes[type].activeGroup(activeTrack_);
  42996. };
  42997. /**
  42998. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  42999. * Closed-Captions) specified in the main manifest.
  43000. *
  43001. * @param {Object} settings
  43002. * Object containing required information for setting up the media groups
  43003. * @param {Tech} settings.tech
  43004. * The tech of the player
  43005. * @param {Object} settings.requestOptions
  43006. * XHR request options used by the segment loaders
  43007. * @param {PlaylistLoader} settings.mainPlaylistLoader
  43008. * PlaylistLoader for the main source
  43009. * @param {VhsHandler} settings.vhs
  43010. * VHS SourceHandler
  43011. * @param {Object} settings.main
  43012. * The parsed main manifest
  43013. * @param {Object} settings.mediaTypes
  43014. * Object to store the loaders, tracks, and utility methods for each media type
  43015. * @param {Function} settings.excludePlaylist
  43016. * Excludes the current rendition and forces a rendition switch.
  43017. * @function setupMediaGroups
  43018. */
  43019. const setupMediaGroups = settings => {
  43020. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  43021. initialize[type](type, settings);
  43022. });
  43023. const {
  43024. mediaTypes,
  43025. mainPlaylistLoader,
  43026. tech,
  43027. vhs,
  43028. segmentLoaders: {
  43029. ['AUDIO']: audioSegmentLoader,
  43030. main: mainSegmentLoader
  43031. }
  43032. } = settings; // setup active group and track getters and change event handlers
  43033. ['AUDIO', 'SUBTITLES'].forEach(type => {
  43034. mediaTypes[type].activeGroup = activeGroup(type, settings);
  43035. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  43036. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  43037. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  43038. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  43039. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  43040. }); // DO NOT enable the default subtitle or caption track.
  43041. // DO enable the default audio track
  43042. const audioGroup = mediaTypes.AUDIO.activeGroup();
  43043. if (audioGroup) {
  43044. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  43045. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  43046. mediaTypes.AUDIO.onGroupChanged();
  43047. mediaTypes.AUDIO.onTrackChanged();
  43048. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  43049. // track is changed, but needs to be handled here since the track may not be considered
  43050. // changed on the first call to onTrackChanged
  43051. if (!activeAudioGroup.playlistLoader) {
  43052. // either audio is muxed with video or the stream is audio only
  43053. mainSegmentLoader.setAudio(true);
  43054. } else {
  43055. // audio is demuxed
  43056. mainSegmentLoader.setAudio(false);
  43057. audioSegmentLoader.setAudio(true);
  43058. }
  43059. }
  43060. mainPlaylistLoader.on('mediachange', () => {
  43061. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  43062. });
  43063. mainPlaylistLoader.on('mediachanging', () => {
  43064. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  43065. }); // custom audio track change event handler for usage event
  43066. const onAudioTrackChanged = () => {
  43067. mediaTypes.AUDIO.onTrackChanged();
  43068. tech.trigger({
  43069. type: 'usage',
  43070. name: 'vhs-audio-change'
  43071. });
  43072. };
  43073. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  43074. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  43075. vhs.on('dispose', () => {
  43076. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  43077. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  43078. }); // clear existing audio tracks and add the ones we just created
  43079. tech.clearTracks('audio');
  43080. for (const id in mediaTypes.AUDIO.tracks) {
  43081. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  43082. }
  43083. };
  43084. /**
  43085. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  43086. * media type
  43087. *
  43088. * @return {Object}
  43089. * Object to store the loaders, tracks, and utility methods for each media type
  43090. * @function createMediaTypes
  43091. */
  43092. const createMediaTypes = () => {
  43093. const mediaTypes = {};
  43094. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  43095. mediaTypes[type] = {
  43096. groups: {},
  43097. tracks: {},
  43098. activePlaylistLoader: null,
  43099. activeGroup: noop,
  43100. activeTrack: noop,
  43101. getActiveGroup: noop,
  43102. onGroupChanged: noop,
  43103. onTrackChanged: noop,
  43104. lastTrack_: null,
  43105. logger_: logger(`MediaGroups[${type}]`)
  43106. };
  43107. });
  43108. return mediaTypes;
  43109. };
  43110. /**
  43111. * @file playlist-controller.js
  43112. */
  43113. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  43114. let Vhs$1; // SegmentLoader stats that need to have each loader's
  43115. // values summed to calculate the final value
  43116. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  43117. const sumLoaderStat = function (stat) {
  43118. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  43119. };
  43120. const shouldSwitchToMedia = function ({
  43121. currentPlaylist,
  43122. buffered,
  43123. currentTime,
  43124. nextPlaylist,
  43125. bufferLowWaterLine,
  43126. bufferHighWaterLine,
  43127. duration,
  43128. bufferBasedABR,
  43129. log
  43130. }) {
  43131. // we have no other playlist to switch to
  43132. if (!nextPlaylist) {
  43133. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  43134. return false;
  43135. }
  43136. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  43137. if (!currentPlaylist) {
  43138. log(`${sharedLogLine} as current playlist is not set`);
  43139. return true;
  43140. } // no need to switch if playlist is the same
  43141. if (nextPlaylist.id === currentPlaylist.id) {
  43142. return false;
  43143. } // determine if current time is in a buffered range.
  43144. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  43145. // This is because in LIVE, the player plays 3 segments from the end of the
  43146. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  43147. // in those segments, a viewer will never experience a rendition upswitch.
  43148. if (!currentPlaylist.endList) {
  43149. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  43150. // doubles the time to first playback.
  43151. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  43152. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  43153. return false;
  43154. }
  43155. log(`${sharedLogLine} as current playlist is live`);
  43156. return true;
  43157. }
  43158. const forwardBuffer = timeAheadOf(buffered, currentTime);
  43159. const maxBufferLowWaterLine = bufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
  43160. // duration is below the max potential low water line
  43161. if (duration < maxBufferLowWaterLine) {
  43162. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  43163. return true;
  43164. }
  43165. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  43166. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  43167. // we can switch down
  43168. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  43169. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  43170. if (bufferBasedABR) {
  43171. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  43172. }
  43173. log(logLine);
  43174. return true;
  43175. } // and if our buffer is higher than the low water line,
  43176. // we can switch up
  43177. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  43178. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  43179. if (bufferBasedABR) {
  43180. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  43181. }
  43182. log(logLine);
  43183. return true;
  43184. }
  43185. log(`not ${sharedLogLine} as no switching criteria met`);
  43186. return false;
  43187. };
  43188. /**
  43189. * the main playlist controller controller all interactons
  43190. * between playlists and segmentloaders. At this time this mainly
  43191. * involves a main playlist and a series of audio playlists
  43192. * if they are available
  43193. *
  43194. * @class PlaylistController
  43195. * @extends videojs.EventTarget
  43196. */
  43197. class PlaylistController extends videojs.EventTarget {
  43198. constructor(options) {
  43199. super();
  43200. const {
  43201. src,
  43202. withCredentials,
  43203. tech,
  43204. bandwidth,
  43205. externVhs,
  43206. useCueTags,
  43207. playlistExclusionDuration,
  43208. enableLowInitialPlaylist,
  43209. sourceType,
  43210. cacheEncryptionKeys,
  43211. bufferBasedABR,
  43212. leastPixelDiffSelector,
  43213. captionServices
  43214. } = options;
  43215. if (!src) {
  43216. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  43217. }
  43218. let {
  43219. maxPlaylistRetries
  43220. } = options;
  43221. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  43222. maxPlaylistRetries = Infinity;
  43223. }
  43224. Vhs$1 = externVhs;
  43225. this.bufferBasedABR = Boolean(bufferBasedABR);
  43226. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  43227. this.withCredentials = withCredentials;
  43228. this.tech_ = tech;
  43229. this.vhs_ = tech.vhs;
  43230. this.sourceType_ = sourceType;
  43231. this.useCueTags_ = useCueTags;
  43232. this.playlistExclusionDuration = playlistExclusionDuration;
  43233. this.maxPlaylistRetries = maxPlaylistRetries;
  43234. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  43235. if (this.useCueTags_) {
  43236. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  43237. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  43238. }
  43239. this.requestOptions_ = {
  43240. withCredentials,
  43241. maxPlaylistRetries,
  43242. timeout: null
  43243. };
  43244. this.on('error', this.pauseLoading);
  43245. this.mediaTypes_ = createMediaTypes();
  43246. this.mediaSource = new window__default["default"].MediaSource();
  43247. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  43248. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  43249. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  43250. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  43251. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  43252. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  43253. // everything, and the MediaSource should not be detached without a proper disposal
  43254. this.seekable_ = createTimeRanges();
  43255. this.hasPlayed_ = false;
  43256. this.syncController_ = new SyncController(options);
  43257. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  43258. kind: 'metadata',
  43259. label: 'segment-metadata'
  43260. }, false).track;
  43261. this.decrypter_ = new Decrypter();
  43262. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  43263. this.inbandTextTracks_ = {};
  43264. this.timelineChangeController_ = new TimelineChangeController();
  43265. const segmentLoaderSettings = {
  43266. vhs: this.vhs_,
  43267. parse708captions: options.parse708captions,
  43268. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  43269. captionServices,
  43270. mediaSource: this.mediaSource,
  43271. currentTime: this.tech_.currentTime.bind(this.tech_),
  43272. seekable: () => this.seekable(),
  43273. seeking: () => this.tech_.seeking(),
  43274. duration: () => this.duration(),
  43275. hasPlayed: () => this.hasPlayed_,
  43276. goalBufferLength: () => this.goalBufferLength(),
  43277. bandwidth,
  43278. syncController: this.syncController_,
  43279. decrypter: this.decrypter_,
  43280. sourceType: this.sourceType_,
  43281. inbandTextTracks: this.inbandTextTracks_,
  43282. cacheEncryptionKeys,
  43283. sourceUpdater: this.sourceUpdater_,
  43284. timelineChangeController: this.timelineChangeController_,
  43285. exactManifestTimings: options.exactManifestTimings
  43286. }; // The source type check not only determines whether a special DASH playlist loader
  43287. // should be used, but also covers the case where the provided src is a vhs-json
  43288. // manifest object (instead of a URL). In the case of vhs-json, the default
  43289. // PlaylistLoader should be used.
  43290. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  43291. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  43292. // combined audio/video or just video when alternate audio track is selected
  43293. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  43294. segmentMetadataTrack: this.segmentMetadataTrack_,
  43295. loaderType: 'main'
  43296. }), options); // alternate audio track
  43297. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  43298. loaderType: 'audio'
  43299. }), options);
  43300. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  43301. loaderType: 'vtt',
  43302. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  43303. loadVttJs: () => new Promise((resolve, reject) => {
  43304. function onLoad() {
  43305. tech.off('vttjserror', onError);
  43306. resolve();
  43307. }
  43308. function onError() {
  43309. tech.off('vttjsloaded', onLoad);
  43310. reject();
  43311. }
  43312. tech.one('vttjsloaded', onLoad);
  43313. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  43314. tech.addWebVttScript_();
  43315. })
  43316. }), options);
  43317. this.setupSegmentLoaderListeners_();
  43318. if (this.bufferBasedABR) {
  43319. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  43320. this.tech_.on('pause', () => this.stopABRTimer_());
  43321. this.tech_.on('play', () => this.startABRTimer_());
  43322. } // Create SegmentLoader stat-getters
  43323. // mediaRequests_
  43324. // mediaRequestsAborted_
  43325. // mediaRequestsTimedout_
  43326. // mediaRequestsErrored_
  43327. // mediaTransferDuration_
  43328. // mediaBytesTransferred_
  43329. // mediaAppends_
  43330. loaderStats.forEach(stat => {
  43331. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  43332. });
  43333. this.logger_ = logger('pc');
  43334. this.triggeredFmp4Usage = false;
  43335. if (this.tech_.preload() === 'none') {
  43336. this.loadOnPlay_ = () => {
  43337. this.loadOnPlay_ = null;
  43338. this.mainPlaylistLoader_.load();
  43339. };
  43340. this.tech_.one('play', this.loadOnPlay_);
  43341. } else {
  43342. this.mainPlaylistLoader_.load();
  43343. }
  43344. this.timeToLoadedData__ = -1;
  43345. this.mainAppendsToLoadedData__ = -1;
  43346. this.audioAppendsToLoadedData__ = -1;
  43347. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  43348. this.tech_.one(event, () => {
  43349. const timeToLoadedDataStart = Date.now();
  43350. this.tech_.one('loadeddata', () => {
  43351. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  43352. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  43353. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  43354. });
  43355. });
  43356. }
  43357. mainAppendsToLoadedData_() {
  43358. return this.mainAppendsToLoadedData__;
  43359. }
  43360. audioAppendsToLoadedData_() {
  43361. return this.audioAppendsToLoadedData__;
  43362. }
  43363. appendsToLoadedData_() {
  43364. const main = this.mainAppendsToLoadedData_();
  43365. const audio = this.audioAppendsToLoadedData_();
  43366. if (main === -1 || audio === -1) {
  43367. return -1;
  43368. }
  43369. return main + audio;
  43370. }
  43371. timeToLoadedData_() {
  43372. return this.timeToLoadedData__;
  43373. }
  43374. /**
  43375. * Run selectPlaylist and switch to the new playlist if we should
  43376. *
  43377. * @param {string} [reason=abr] a reason for why the ABR check is made
  43378. * @private
  43379. */
  43380. checkABR_(reason = 'abr') {
  43381. const nextPlaylist = this.selectPlaylist();
  43382. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  43383. this.switchMedia_(nextPlaylist, reason);
  43384. }
  43385. }
  43386. switchMedia_(playlist, cause, delay) {
  43387. const oldMedia = this.media();
  43388. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  43389. const newId = playlist.id || playlist.uri;
  43390. if (oldId && oldId !== newId) {
  43391. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  43392. this.tech_.trigger({
  43393. type: 'usage',
  43394. name: `vhs-rendition-change-${cause}`
  43395. });
  43396. }
  43397. this.mainPlaylistLoader_.media(playlist, delay);
  43398. }
  43399. /**
  43400. * Start a timer that periodically calls checkABR_
  43401. *
  43402. * @private
  43403. */
  43404. startABRTimer_() {
  43405. this.stopABRTimer_();
  43406. this.abrTimer_ = window__default["default"].setInterval(() => this.checkABR_(), 250);
  43407. }
  43408. /**
  43409. * Stop the timer that periodically calls checkABR_
  43410. *
  43411. * @private
  43412. */
  43413. stopABRTimer_() {
  43414. // if we're scrubbing, we don't need to pause.
  43415. // This getter will be added to Video.js in version 7.11.
  43416. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  43417. return;
  43418. }
  43419. window__default["default"].clearInterval(this.abrTimer_);
  43420. this.abrTimer_ = null;
  43421. }
  43422. /**
  43423. * Get a list of playlists for the currently selected audio playlist
  43424. *
  43425. * @return {Array} the array of audio playlists
  43426. */
  43427. getAudioTrackPlaylists_() {
  43428. const main = this.main();
  43429. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  43430. // assume that the audio tracks are contained in main
  43431. // playlist array, use that or an empty array.
  43432. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  43433. return defaultPlaylists;
  43434. }
  43435. const AUDIO = main.mediaGroups.AUDIO;
  43436. const groupKeys = Object.keys(AUDIO);
  43437. let track; // get the current active track
  43438. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  43439. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  43440. } else {
  43441. // default group is `main` or just the first group.
  43442. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  43443. for (const label in defaultGroup) {
  43444. if (defaultGroup[label].default) {
  43445. track = {
  43446. label
  43447. };
  43448. break;
  43449. }
  43450. }
  43451. } // no active track no playlists.
  43452. if (!track) {
  43453. return defaultPlaylists;
  43454. }
  43455. const playlists = []; // get all of the playlists that are possible for the
  43456. // active track.
  43457. for (const group in AUDIO) {
  43458. if (AUDIO[group][track.label]) {
  43459. const properties = AUDIO[group][track.label];
  43460. if (properties.playlists && properties.playlists.length) {
  43461. playlists.push.apply(playlists, properties.playlists);
  43462. } else if (properties.uri) {
  43463. playlists.push(properties);
  43464. } else if (main.playlists.length) {
  43465. // if an audio group does not have a uri
  43466. // see if we have main playlists that use it as a group.
  43467. // if we do then add those to the playlists list.
  43468. for (let i = 0; i < main.playlists.length; i++) {
  43469. const playlist = main.playlists[i];
  43470. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  43471. playlists.push(playlist);
  43472. }
  43473. }
  43474. }
  43475. }
  43476. }
  43477. if (!playlists.length) {
  43478. return defaultPlaylists;
  43479. }
  43480. return playlists;
  43481. }
  43482. /**
  43483. * Register event handlers on the main playlist loader. A helper
  43484. * function for construction time.
  43485. *
  43486. * @private
  43487. */
  43488. setupMainPlaylistLoaderListeners_() {
  43489. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  43490. const media = this.mainPlaylistLoader_.media();
  43491. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43492. // timeout the request.
  43493. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  43494. this.requestOptions_.timeout = 0;
  43495. } else {
  43496. this.requestOptions_.timeout = requestTimeout;
  43497. } // if this isn't a live video and preload permits, start
  43498. // downloading segments
  43499. if (media.endList && this.tech_.preload() !== 'none') {
  43500. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  43501. this.mainSegmentLoader_.load();
  43502. }
  43503. setupMediaGroups({
  43504. sourceType: this.sourceType_,
  43505. segmentLoaders: {
  43506. AUDIO: this.audioSegmentLoader_,
  43507. SUBTITLES: this.subtitleSegmentLoader_,
  43508. main: this.mainSegmentLoader_
  43509. },
  43510. tech: this.tech_,
  43511. requestOptions: this.requestOptions_,
  43512. mainPlaylistLoader: this.mainPlaylistLoader_,
  43513. vhs: this.vhs_,
  43514. main: this.main(),
  43515. mediaTypes: this.mediaTypes_,
  43516. excludePlaylist: this.excludePlaylist.bind(this)
  43517. });
  43518. this.triggerPresenceUsage_(this.main(), media);
  43519. this.setupFirstPlay();
  43520. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  43521. this.trigger('selectedinitialmedia');
  43522. } else {
  43523. // We must wait for the active audio playlist loader to
  43524. // finish setting up before triggering this event so the
  43525. // representations API and EME setup is correct
  43526. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  43527. this.trigger('selectedinitialmedia');
  43528. });
  43529. }
  43530. });
  43531. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  43532. if (this.loadOnPlay_) {
  43533. this.tech_.off('play', this.loadOnPlay_);
  43534. }
  43535. let updatedPlaylist = this.mainPlaylistLoader_.media();
  43536. if (!updatedPlaylist) {
  43537. // exclude any variants that are not supported by the browser before selecting
  43538. // an initial media as the playlist selectors do not consider browser support
  43539. this.excludeUnsupportedVariants_();
  43540. let selectedMedia;
  43541. if (this.enableLowInitialPlaylist) {
  43542. selectedMedia = this.selectInitialPlaylist();
  43543. }
  43544. if (!selectedMedia) {
  43545. selectedMedia = this.selectPlaylist();
  43546. }
  43547. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  43548. return;
  43549. }
  43550. this.initialMedia_ = selectedMedia;
  43551. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  43552. // fire again since the playlist will be requested. In the case of vhs-json
  43553. // (where the manifest object is provided as the source), when the media
  43554. // playlist's `segments` list is already available, a media playlist won't be
  43555. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  43556. // called on its own here.
  43557. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  43558. if (!haveJsonSource) {
  43559. return;
  43560. }
  43561. updatedPlaylist = this.initialMedia_;
  43562. }
  43563. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  43564. });
  43565. this.mainPlaylistLoader_.on('error', () => {
  43566. const error = this.mainPlaylistLoader_.error;
  43567. this.excludePlaylist({
  43568. playlistToExclude: error.playlist,
  43569. error
  43570. });
  43571. });
  43572. this.mainPlaylistLoader_.on('mediachanging', () => {
  43573. this.mainSegmentLoader_.abort();
  43574. this.mainSegmentLoader_.pause();
  43575. });
  43576. this.mainPlaylistLoader_.on('mediachange', () => {
  43577. const media = this.mainPlaylistLoader_.media();
  43578. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43579. // timeout the request.
  43580. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  43581. this.requestOptions_.timeout = 0;
  43582. } else {
  43583. this.requestOptions_.timeout = requestTimeout;
  43584. }
  43585. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  43586. // that the segments have changed in some way and use that to
  43587. // update the SegmentLoader instead of doing it twice here and
  43588. // on `loadedplaylist`
  43589. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  43590. this.mainSegmentLoader_.load();
  43591. this.tech_.trigger({
  43592. type: 'mediachange',
  43593. bubbles: true
  43594. });
  43595. });
  43596. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  43597. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  43598. // excluded for not-changing. We likely just have a really slowly updating
  43599. // playlist.
  43600. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  43601. return;
  43602. }
  43603. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  43604. if (playlistOutdated) {
  43605. // Playlist has stopped updating and we're stuck at its end. Try to
  43606. // exclude it and switch to another playlist in the hope that that
  43607. // one is updating (and give the player a chance to re-adjust to the
  43608. // safe live point).
  43609. this.excludePlaylist({
  43610. error: {
  43611. message: 'Playlist no longer updating.',
  43612. reason: 'playlist-unchanged'
  43613. }
  43614. }); // useful for monitoring QoS
  43615. this.tech_.trigger('playliststuck');
  43616. }
  43617. });
  43618. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  43619. this.tech_.trigger({
  43620. type: 'usage',
  43621. name: 'vhs-rendition-disabled'
  43622. });
  43623. });
  43624. this.mainPlaylistLoader_.on('renditionenabled', () => {
  43625. this.tech_.trigger({
  43626. type: 'usage',
  43627. name: 'vhs-rendition-enabled'
  43628. });
  43629. });
  43630. }
  43631. /**
  43632. * Given an updated media playlist (whether it was loaded for the first time, or
  43633. * refreshed for live playlists), update any relevant properties and state to reflect
  43634. * changes in the media that should be accounted for (e.g., cues and duration).
  43635. *
  43636. * @param {Object} updatedPlaylist the updated media playlist object
  43637. *
  43638. * @private
  43639. */
  43640. handleUpdatedMediaPlaylist(updatedPlaylist) {
  43641. if (this.useCueTags_) {
  43642. this.updateAdCues_(updatedPlaylist);
  43643. } // TODO: Create a new event on the PlaylistLoader that signals
  43644. // that the segments have changed in some way and use that to
  43645. // update the SegmentLoader instead of doing it twice here and
  43646. // on `mediachange`
  43647. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  43648. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  43649. // as it is possible that it was temporarily stopped while waiting for
  43650. // a playlist (e.g., in case the playlist errored and we re-requested it).
  43651. if (!this.tech_.paused()) {
  43652. this.mainSegmentLoader_.load();
  43653. if (this.audioSegmentLoader_) {
  43654. this.audioSegmentLoader_.load();
  43655. }
  43656. }
  43657. }
  43658. /**
  43659. * A helper function for triggerring presence usage events once per source
  43660. *
  43661. * @private
  43662. */
  43663. triggerPresenceUsage_(main, media) {
  43664. const mediaGroups = main.mediaGroups || {};
  43665. let defaultDemuxed = true;
  43666. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  43667. for (const mediaGroup in mediaGroups.AUDIO) {
  43668. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  43669. const properties = mediaGroups.AUDIO[mediaGroup][label];
  43670. if (!properties.uri) {
  43671. defaultDemuxed = false;
  43672. }
  43673. }
  43674. }
  43675. if (defaultDemuxed) {
  43676. this.tech_.trigger({
  43677. type: 'usage',
  43678. name: 'vhs-demuxed'
  43679. });
  43680. }
  43681. if (Object.keys(mediaGroups.SUBTITLES).length) {
  43682. this.tech_.trigger({
  43683. type: 'usage',
  43684. name: 'vhs-webvtt'
  43685. });
  43686. }
  43687. if (Vhs$1.Playlist.isAes(media)) {
  43688. this.tech_.trigger({
  43689. type: 'usage',
  43690. name: 'vhs-aes'
  43691. });
  43692. }
  43693. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  43694. this.tech_.trigger({
  43695. type: 'usage',
  43696. name: 'vhs-alternate-audio'
  43697. });
  43698. }
  43699. if (this.useCueTags_) {
  43700. this.tech_.trigger({
  43701. type: 'usage',
  43702. name: 'vhs-playlist-cue-tags'
  43703. });
  43704. }
  43705. }
  43706. shouldSwitchToMedia_(nextPlaylist) {
  43707. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  43708. const currentTime = this.tech_.currentTime();
  43709. const bufferLowWaterLine = this.bufferLowWaterLine();
  43710. const bufferHighWaterLine = this.bufferHighWaterLine();
  43711. const buffered = this.tech_.buffered();
  43712. return shouldSwitchToMedia({
  43713. buffered,
  43714. currentTime,
  43715. currentPlaylist,
  43716. nextPlaylist,
  43717. bufferLowWaterLine,
  43718. bufferHighWaterLine,
  43719. duration: this.duration(),
  43720. bufferBasedABR: this.bufferBasedABR,
  43721. log: this.logger_
  43722. });
  43723. }
  43724. /**
  43725. * Register event handlers on the segment loaders. A helper function
  43726. * for construction time.
  43727. *
  43728. * @private
  43729. */
  43730. setupSegmentLoaderListeners_() {
  43731. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  43732. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  43733. // useful to check to see if a rendition switch should be made.
  43734. this.checkABR_('bandwidthupdate');
  43735. this.tech_.trigger('bandwidthupdate');
  43736. });
  43737. this.mainSegmentLoader_.on('timeout', () => {
  43738. if (this.bufferBasedABR) {
  43739. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  43740. // Here the only consideration is that for buffer based ABR there's no guarantee
  43741. // of an immediate switch (since the bandwidth is averaged with a timeout
  43742. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  43743. this.mainSegmentLoader_.load();
  43744. }
  43745. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  43746. // based ABR.
  43747. if (!this.bufferBasedABR) {
  43748. this.mainSegmentLoader_.on('progress', () => {
  43749. this.trigger('progress');
  43750. });
  43751. }
  43752. this.mainSegmentLoader_.on('error', () => {
  43753. const error = this.mainSegmentLoader_.error();
  43754. this.excludePlaylist({
  43755. playlistToExclude: error.playlist,
  43756. error
  43757. });
  43758. });
  43759. this.mainSegmentLoader_.on('appenderror', () => {
  43760. this.error = this.mainSegmentLoader_.error_;
  43761. this.trigger('error');
  43762. });
  43763. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  43764. this.onSyncInfoUpdate_();
  43765. });
  43766. this.mainSegmentLoader_.on('timestampoffset', () => {
  43767. this.tech_.trigger({
  43768. type: 'usage',
  43769. name: 'vhs-timestamp-offset'
  43770. });
  43771. });
  43772. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  43773. this.onSyncInfoUpdate_();
  43774. });
  43775. this.audioSegmentLoader_.on('appenderror', () => {
  43776. this.error = this.audioSegmentLoader_.error_;
  43777. this.trigger('error');
  43778. });
  43779. this.mainSegmentLoader_.on('ended', () => {
  43780. this.logger_('main segment loader ended');
  43781. this.onEndOfStream();
  43782. });
  43783. this.mainSegmentLoader_.on('earlyabort', event => {
  43784. // never try to early abort with the new ABR algorithm
  43785. if (this.bufferBasedABR) {
  43786. return;
  43787. }
  43788. this.delegateLoaders_('all', ['abort']);
  43789. this.excludePlaylist({
  43790. error: {
  43791. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  43792. },
  43793. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  43794. });
  43795. });
  43796. const updateCodecs = () => {
  43797. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  43798. return this.tryToCreateSourceBuffers_();
  43799. }
  43800. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  43801. if (!codecs) {
  43802. return;
  43803. }
  43804. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  43805. };
  43806. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  43807. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  43808. this.mainSegmentLoader_.on('fmp4', () => {
  43809. if (!this.triggeredFmp4Usage) {
  43810. this.tech_.trigger({
  43811. type: 'usage',
  43812. name: 'vhs-fmp4'
  43813. });
  43814. this.triggeredFmp4Usage = true;
  43815. }
  43816. });
  43817. this.audioSegmentLoader_.on('fmp4', () => {
  43818. if (!this.triggeredFmp4Usage) {
  43819. this.tech_.trigger({
  43820. type: 'usage',
  43821. name: 'vhs-fmp4'
  43822. });
  43823. this.triggeredFmp4Usage = true;
  43824. }
  43825. });
  43826. this.audioSegmentLoader_.on('ended', () => {
  43827. this.logger_('audioSegmentLoader ended');
  43828. this.onEndOfStream();
  43829. });
  43830. }
  43831. mediaSecondsLoaded_() {
  43832. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  43833. }
  43834. /**
  43835. * Call load on our SegmentLoaders
  43836. */
  43837. load() {
  43838. this.mainSegmentLoader_.load();
  43839. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43840. this.audioSegmentLoader_.load();
  43841. }
  43842. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  43843. this.subtitleSegmentLoader_.load();
  43844. }
  43845. }
  43846. /**
  43847. * Re-tune playback quality level for the current player
  43848. * conditions. This method will perform destructive actions like removing
  43849. * already buffered content in order to readjust the currently active
  43850. * playlist quickly. This is good for manual quality changes
  43851. *
  43852. * @private
  43853. */
  43854. fastQualityChange_(media = this.selectPlaylist()) {
  43855. if (media === this.mainPlaylistLoader_.media()) {
  43856. this.logger_('skipping fastQualityChange because new media is same as old');
  43857. return;
  43858. }
  43859. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  43860. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  43861. // ahead is roughly the minimum that will accomplish this across a variety of content
  43862. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  43863. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  43864. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  43865. this.mainSegmentLoader_.resetEverything(() => {
  43866. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  43867. // from the previously enabled rendition to load before the new playlist has finished loading
  43868. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  43869. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  43870. } else {
  43871. this.tech_.setCurrentTime(this.tech_.currentTime());
  43872. }
  43873. }); // don't need to reset audio as it is reset when media changes
  43874. }
  43875. /**
  43876. * Begin playback.
  43877. */
  43878. play() {
  43879. if (this.setupFirstPlay()) {
  43880. return;
  43881. }
  43882. if (this.tech_.ended()) {
  43883. this.tech_.setCurrentTime(0);
  43884. }
  43885. if (this.hasPlayed_) {
  43886. this.load();
  43887. }
  43888. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  43889. // seek forward to the live point
  43890. if (this.tech_.duration() === Infinity) {
  43891. if (this.tech_.currentTime() < seekable.start(0)) {
  43892. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  43893. }
  43894. }
  43895. }
  43896. /**
  43897. * Seek to the latest media position if this is a live video and the
  43898. * player and video are loaded and initialized.
  43899. */
  43900. setupFirstPlay() {
  43901. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  43902. // If 1) there is no active media
  43903. // 2) the player is paused
  43904. // 3) the first play has already been setup
  43905. // then exit early
  43906. if (!media || this.tech_.paused() || this.hasPlayed_) {
  43907. return false;
  43908. } // when the video is a live stream
  43909. if (!media.endList) {
  43910. const seekable = this.seekable();
  43911. if (!seekable.length) {
  43912. // without a seekable range, the player cannot seek to begin buffering at the live
  43913. // point
  43914. return false;
  43915. }
  43916. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  43917. // IE11 throws an InvalidStateError if you try to set currentTime while the
  43918. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  43919. this.tech_.one('loadedmetadata', () => {
  43920. this.trigger('firstplay');
  43921. this.tech_.setCurrentTime(seekable.end(0));
  43922. this.hasPlayed_ = true;
  43923. });
  43924. return false;
  43925. } // trigger firstplay to inform the source handler to ignore the next seek event
  43926. this.trigger('firstplay'); // seek to the live point
  43927. this.tech_.setCurrentTime(seekable.end(0));
  43928. }
  43929. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  43930. this.load();
  43931. return true;
  43932. }
  43933. /**
  43934. * handle the sourceopen event on the MediaSource
  43935. *
  43936. * @private
  43937. */
  43938. handleSourceOpen_() {
  43939. // Only attempt to create the source buffer if none already exist.
  43940. // handleSourceOpen is also called when we are "re-opening" a source buffer
  43941. // after `endOfStream` has been called (in response to a seek for instance)
  43942. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  43943. // code in video.js but is required because play() must be invoked
  43944. // *after* the media source has opened.
  43945. if (this.tech_.autoplay()) {
  43946. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  43947. // on browsers which return a promise
  43948. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  43949. playPromise.then(null, e => {});
  43950. }
  43951. }
  43952. this.trigger('sourceopen');
  43953. }
  43954. /**
  43955. * handle the sourceended event on the MediaSource
  43956. *
  43957. * @private
  43958. */
  43959. handleSourceEnded_() {
  43960. if (!this.inbandTextTracks_.metadataTrack_) {
  43961. return;
  43962. }
  43963. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  43964. if (!cues || !cues.length) {
  43965. return;
  43966. }
  43967. const duration = this.duration();
  43968. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  43969. }
  43970. /**
  43971. * handle the durationchange event on the MediaSource
  43972. *
  43973. * @private
  43974. */
  43975. handleDurationChange_() {
  43976. this.tech_.trigger('durationchange');
  43977. }
  43978. /**
  43979. * Calls endOfStream on the media source when all active stream types have called
  43980. * endOfStream
  43981. *
  43982. * @param {string} streamType
  43983. * Stream type of the segment loader that called endOfStream
  43984. * @private
  43985. */
  43986. onEndOfStream() {
  43987. let isEndOfStream = this.mainSegmentLoader_.ended_;
  43988. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43989. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  43990. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  43991. // if we do not know if the main segment loader contains video yet or if we
  43992. // definitively know the main segment loader contains video, then we need to wait
  43993. // for both main and audio segment loaders to call endOfStream
  43994. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  43995. } else {
  43996. // otherwise just rely on the audio loader
  43997. isEndOfStream = this.audioSegmentLoader_.ended_;
  43998. }
  43999. }
  44000. if (!isEndOfStream) {
  44001. return;
  44002. }
  44003. this.stopABRTimer_();
  44004. this.sourceUpdater_.endOfStream();
  44005. }
  44006. /**
  44007. * Check if a playlist has stopped being updated
  44008. *
  44009. * @param {Object} playlist the media playlist object
  44010. * @return {boolean} whether the playlist has stopped being updated or not
  44011. */
  44012. stuckAtPlaylistEnd_(playlist) {
  44013. const seekable = this.seekable();
  44014. if (!seekable.length) {
  44015. // playlist doesn't have enough information to determine whether we are stuck
  44016. return false;
  44017. }
  44018. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  44019. if (expired === null) {
  44020. return false;
  44021. } // does not use the safe live end to calculate playlist end, since we
  44022. // don't want to say we are stuck while there is still content
  44023. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  44024. const currentTime = this.tech_.currentTime();
  44025. const buffered = this.tech_.buffered();
  44026. if (!buffered.length) {
  44027. // return true if the playhead reached the absolute end of the playlist
  44028. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  44029. }
  44030. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  44031. // end of playlist
  44032. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  44033. }
  44034. /**
  44035. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  44036. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  44037. *
  44038. * @param {Object=} playlistToExclude
  44039. * the playlist to exclude, defaults to the currently selected playlist
  44040. * @param {Object=} error
  44041. * an optional error
  44042. * @param {number=} playlistExclusionDuration
  44043. * an optional number of seconds to exclude the playlist
  44044. */
  44045. excludePlaylist({
  44046. playlistToExclude = this.mainPlaylistLoader_.media(),
  44047. error = {},
  44048. playlistExclusionDuration
  44049. }) {
  44050. // If the `error` was generated by the playlist loader, it will contain
  44051. // the playlist we were trying to load (but failed) and that should be
  44052. // excluded instead of the currently selected playlist which is likely
  44053. // out-of-date in this scenario
  44054. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  44055. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  44056. // trying to load the main OR while we were disposing of the tech
  44057. if (!playlistToExclude) {
  44058. this.error = error;
  44059. if (this.mediaSource.readyState !== 'open') {
  44060. this.trigger('error');
  44061. } else {
  44062. this.sourceUpdater_.endOfStream('network');
  44063. }
  44064. return;
  44065. }
  44066. playlistToExclude.playlistErrors_++;
  44067. const playlists = this.mainPlaylistLoader_.main.playlists;
  44068. const enabledPlaylists = playlists.filter(isEnabled);
  44069. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  44070. // forever
  44071. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  44072. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  44073. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  44074. return this.mainPlaylistLoader_.load(isFinalRendition);
  44075. }
  44076. if (isFinalRendition) {
  44077. // Since we're on the final non-excluded playlist, and we're about to exclude
  44078. // it, instead of erring the player or retrying this playlist, clear out the current
  44079. // exclusion list. This allows other playlists to be attempted in case any have been
  44080. // fixed.
  44081. let reincluded = false;
  44082. playlists.forEach(playlist => {
  44083. // skip current playlist which is about to be excluded
  44084. if (playlist === playlistToExclude) {
  44085. return;
  44086. }
  44087. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  44088. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  44089. reincluded = true;
  44090. delete playlist.excludeUntil;
  44091. }
  44092. });
  44093. if (reincluded) {
  44094. videojs.log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
  44095. // playlist. This is needed for users relying on the retryplaylist event to catch a
  44096. // case where the player might be stuck and looping through "dead" playlists.
  44097. this.tech_.trigger('retryplaylist');
  44098. }
  44099. } // Exclude this playlist
  44100. let excludeUntil;
  44101. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  44102. excludeUntil = Infinity;
  44103. } else {
  44104. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  44105. }
  44106. playlistToExclude.excludeUntil = excludeUntil;
  44107. if (error.reason) {
  44108. playlistToExclude.lastExcludeReason_ = error.reason;
  44109. }
  44110. this.tech_.trigger('excludeplaylist');
  44111. this.tech_.trigger({
  44112. type: 'usage',
  44113. name: 'vhs-rendition-excluded'
  44114. }); // TODO: only load a new playlist if we're excluding the current playlist
  44115. // If this function was called with a playlist that's not the current active playlist
  44116. // (e.g., media().id !== playlistToExclude.id),
  44117. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  44118. const nextPlaylist = this.selectPlaylist();
  44119. if (!nextPlaylist) {
  44120. this.error = 'Playback cannot continue. No available working or supported playlists.';
  44121. this.trigger('error');
  44122. return;
  44123. }
  44124. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  44125. const errorMessage = error.message ? ' ' + error.message : '';
  44126. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  44127. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  44128. this.delegateLoaders_('audio', ['abort', 'pause']);
  44129. } // if subtitle group changed reset subtitle loaders
  44130. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  44131. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  44132. }
  44133. this.delegateLoaders_('main', ['abort', 'pause']);
  44134. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  44135. const shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
  44136. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  44137. }
  44138. /**
  44139. * Pause all segment/playlist loaders
  44140. */
  44141. pauseLoading() {
  44142. this.delegateLoaders_('all', ['abort', 'pause']);
  44143. this.stopABRTimer_();
  44144. }
  44145. /**
  44146. * Call a set of functions in order on playlist loaders, segment loaders,
  44147. * or both types of loaders.
  44148. *
  44149. * @param {string} filter
  44150. * Filter loaders that should call fnNames using a string. Can be:
  44151. * * all - run on all loaders
  44152. * * audio - run on all audio loaders
  44153. * * subtitle - run on all subtitle loaders
  44154. * * main - run on the main loaders
  44155. *
  44156. * @param {Array|string} fnNames
  44157. * A string or array of function names to call.
  44158. */
  44159. delegateLoaders_(filter, fnNames) {
  44160. const loaders = [];
  44161. const dontFilterPlaylist = filter === 'all';
  44162. if (dontFilterPlaylist || filter === 'main') {
  44163. loaders.push(this.mainPlaylistLoader_);
  44164. }
  44165. const mediaTypes = [];
  44166. if (dontFilterPlaylist || filter === 'audio') {
  44167. mediaTypes.push('AUDIO');
  44168. }
  44169. if (dontFilterPlaylist || filter === 'subtitle') {
  44170. mediaTypes.push('CLOSED-CAPTIONS');
  44171. mediaTypes.push('SUBTITLES');
  44172. }
  44173. mediaTypes.forEach(mediaType => {
  44174. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  44175. if (loader) {
  44176. loaders.push(loader);
  44177. }
  44178. });
  44179. ['main', 'audio', 'subtitle'].forEach(name => {
  44180. const loader = this[`${name}SegmentLoader_`];
  44181. if (loader && (filter === name || filter === 'all')) {
  44182. loaders.push(loader);
  44183. }
  44184. });
  44185. loaders.forEach(loader => fnNames.forEach(fnName => {
  44186. if (typeof loader[fnName] === 'function') {
  44187. loader[fnName]();
  44188. }
  44189. }));
  44190. }
  44191. /**
  44192. * set the current time on all segment loaders
  44193. *
  44194. * @param {TimeRange} currentTime the current time to set
  44195. * @return {TimeRange} the current time
  44196. */
  44197. setCurrentTime(currentTime) {
  44198. const buffered = findRange(this.tech_.buffered(), currentTime);
  44199. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  44200. // return immediately if the metadata is not ready yet
  44201. return 0;
  44202. } // it's clearly an edge-case but don't thrown an error if asked to
  44203. // seek within an empty playlist
  44204. if (!this.mainPlaylistLoader_.media().segments) {
  44205. return 0;
  44206. } // if the seek location is already buffered, continue buffering as usual
  44207. if (buffered && buffered.length) {
  44208. return currentTime;
  44209. } // cancel outstanding requests so we begin buffering at the new
  44210. // location
  44211. this.mainSegmentLoader_.resetEverything();
  44212. this.mainSegmentLoader_.abort();
  44213. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44214. this.audioSegmentLoader_.resetEverything();
  44215. this.audioSegmentLoader_.abort();
  44216. }
  44217. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  44218. this.subtitleSegmentLoader_.resetEverything();
  44219. this.subtitleSegmentLoader_.abort();
  44220. } // start segment loader loading in case they are paused
  44221. this.load();
  44222. }
  44223. /**
  44224. * get the current duration
  44225. *
  44226. * @return {TimeRange} the duration
  44227. */
  44228. duration() {
  44229. if (!this.mainPlaylistLoader_) {
  44230. return 0;
  44231. }
  44232. const media = this.mainPlaylistLoader_.media();
  44233. if (!media) {
  44234. // no playlists loaded yet, so can't determine a duration
  44235. return 0;
  44236. } // Don't rely on the media source for duration in the case of a live playlist since
  44237. // setting the native MediaSource's duration to infinity ends up with consequences to
  44238. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44239. //
  44240. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44241. // however, few browsers have support for setLiveSeekableRange()
  44242. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44243. //
  44244. // Until a time when the duration of the media source can be set to infinity, and a
  44245. // seekable range specified across browsers, just return Infinity.
  44246. if (!media.endList) {
  44247. return Infinity;
  44248. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  44249. // available). If it's not available, fall back to a playlist-calculated estimate.
  44250. if (this.mediaSource) {
  44251. return this.mediaSource.duration;
  44252. }
  44253. return Vhs$1.Playlist.duration(media);
  44254. }
  44255. /**
  44256. * check the seekable range
  44257. *
  44258. * @return {TimeRange} the seekable range
  44259. */
  44260. seekable() {
  44261. return this.seekable_;
  44262. }
  44263. onSyncInfoUpdate_() {
  44264. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  44265. //
  44266. // A fix was made to this function where a check for
  44267. // this.sourceUpdater_.hasCreatedSourceBuffers
  44268. // was added to ensure that both source buffers were created before seekable was
  44269. // updated. However, it originally had a bug where it was checking for a true and
  44270. // returning early instead of checking for false. Setting it to check for false to
  44271. // return early though created other issues. A call to play() would check for seekable
  44272. // end without verifying that a seekable range was present. In addition, even checking
  44273. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  44274. // due to a media update calling load on the segment loaders, skipping a seek to live,
  44275. // thereby starting live streams at the beginning of the stream rather than at the end.
  44276. //
  44277. // This conditional should be fixed to wait for the creation of two source buffers at
  44278. // the same time as the other sections of code are fixed to properly seek to live and
  44279. // not throw an error due to checking for a seekable end when no seekable range exists.
  44280. //
  44281. // For now, fall back to the older behavior, with the understanding that the seekable
  44282. // range may not be completely correct, leading to a suboptimal initial live point.
  44283. if (!this.mainPlaylistLoader_) {
  44284. return;
  44285. }
  44286. let media = this.mainPlaylistLoader_.media();
  44287. if (!media) {
  44288. return;
  44289. }
  44290. let expired = this.syncController_.getExpiredTime(media, this.duration());
  44291. if (expired === null) {
  44292. // not enough information to update seekable
  44293. return;
  44294. }
  44295. const main = this.mainPlaylistLoader_.main;
  44296. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  44297. if (mainSeekable.length === 0) {
  44298. return;
  44299. }
  44300. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44301. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  44302. expired = this.syncController_.getExpiredTime(media, this.duration());
  44303. if (expired === null) {
  44304. return;
  44305. }
  44306. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  44307. if (audioSeekable.length === 0) {
  44308. return;
  44309. }
  44310. }
  44311. let oldEnd;
  44312. let oldStart;
  44313. if (this.seekable_ && this.seekable_.length) {
  44314. oldEnd = this.seekable_.end(0);
  44315. oldStart = this.seekable_.start(0);
  44316. }
  44317. if (!audioSeekable) {
  44318. // seekable has been calculated based on buffering video data so it
  44319. // can be returned directly
  44320. this.seekable_ = mainSeekable;
  44321. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  44322. // seekables are pretty far off, rely on main
  44323. this.seekable_ = mainSeekable;
  44324. } else {
  44325. this.seekable_ = createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
  44326. } // seekable is the same as last time
  44327. if (this.seekable_ && this.seekable_.length) {
  44328. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  44329. return;
  44330. }
  44331. }
  44332. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  44333. this.tech_.trigger('seekablechanged');
  44334. }
  44335. /**
  44336. * Update the player duration
  44337. */
  44338. updateDuration(isLive) {
  44339. if (this.updateDuration_) {
  44340. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44341. this.updateDuration_ = null;
  44342. }
  44343. if (this.mediaSource.readyState !== 'open') {
  44344. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  44345. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  44346. return;
  44347. }
  44348. if (isLive) {
  44349. const seekable = this.seekable();
  44350. if (!seekable.length) {
  44351. return;
  44352. } // Even in the case of a live playlist, the native MediaSource's duration should not
  44353. // be set to Infinity (even though this would be expected for a live playlist), since
  44354. // setting the native MediaSource's duration to infinity ends up with consequences to
  44355. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44356. //
  44357. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44358. // however, few browsers have support for setLiveSeekableRange()
  44359. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44360. //
  44361. // Until a time when the duration of the media source can be set to infinity, and a
  44362. // seekable range specified across browsers, the duration should be greater than or
  44363. // equal to the last possible seekable value.
  44364. // MediaSource duration starts as NaN
  44365. // It is possible (and probable) that this case will never be reached for many
  44366. // sources, since the MediaSource reports duration as the highest value without
  44367. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  44368. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  44369. // time will be between 0 and 100, the native media source may report the duration
  44370. // as 200. However, since we report duration separate from the media source (as
  44371. // Infinity), and as long as the native media source duration value is greater than
  44372. // our reported seekable range, seeks will work as expected. The large number as
  44373. // duration for live is actually a strategy used by some players to work around the
  44374. // issue of live seekable ranges cited above.
  44375. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  44376. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  44377. }
  44378. return;
  44379. }
  44380. const buffered = this.tech_.buffered();
  44381. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  44382. if (buffered.length > 0) {
  44383. duration = Math.max(duration, buffered.end(buffered.length - 1));
  44384. }
  44385. if (this.mediaSource.duration !== duration) {
  44386. this.sourceUpdater_.setDuration(duration);
  44387. }
  44388. }
  44389. /**
  44390. * dispose of the PlaylistController and everything
  44391. * that it controls
  44392. */
  44393. dispose() {
  44394. this.trigger('dispose');
  44395. this.decrypter_.terminate();
  44396. this.mainPlaylistLoader_.dispose();
  44397. this.mainSegmentLoader_.dispose();
  44398. if (this.loadOnPlay_) {
  44399. this.tech_.off('play', this.loadOnPlay_);
  44400. }
  44401. ['AUDIO', 'SUBTITLES'].forEach(type => {
  44402. const groups = this.mediaTypes_[type].groups;
  44403. for (const id in groups) {
  44404. groups[id].forEach(group => {
  44405. if (group.playlistLoader) {
  44406. group.playlistLoader.dispose();
  44407. }
  44408. });
  44409. }
  44410. });
  44411. this.audioSegmentLoader_.dispose();
  44412. this.subtitleSegmentLoader_.dispose();
  44413. this.sourceUpdater_.dispose();
  44414. this.timelineChangeController_.dispose();
  44415. this.stopABRTimer_();
  44416. if (this.updateDuration_) {
  44417. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44418. }
  44419. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  44420. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  44421. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  44422. this.off();
  44423. }
  44424. /**
  44425. * return the main playlist object if we have one
  44426. *
  44427. * @return {Object} the main playlist object that we parsed
  44428. */
  44429. main() {
  44430. return this.mainPlaylistLoader_.main;
  44431. }
  44432. /**
  44433. * return the currently selected playlist
  44434. *
  44435. * @return {Object} the currently selected playlist object that we parsed
  44436. */
  44437. media() {
  44438. // playlist loader will not return media if it has not been fully loaded
  44439. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  44440. }
  44441. areMediaTypesKnown_() {
  44442. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44443. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  44444. // otherwise check on the segment loader.
  44445. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  44446. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  44447. return false;
  44448. }
  44449. return true;
  44450. }
  44451. getCodecsOrExclude_() {
  44452. const media = {
  44453. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  44454. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  44455. };
  44456. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  44457. media.video = media.main;
  44458. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  44459. const codecs = {};
  44460. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44461. if (media.main.hasVideo) {
  44462. codecs.video = playlistCodecs.video || media.main.videoCodec || codecs_js.DEFAULT_VIDEO_CODEC;
  44463. }
  44464. if (media.main.isMuxed) {
  44465. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC}`;
  44466. }
  44467. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  44468. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  44469. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  44470. } // no codecs, no playback.
  44471. if (!codecs.audio && !codecs.video) {
  44472. this.excludePlaylist({
  44473. playlistToExclude: playlist,
  44474. error: {
  44475. message: 'Could not determine codecs for playlist.'
  44476. },
  44477. playlistExclusionDuration: Infinity
  44478. });
  44479. return;
  44480. } // fmp4 relies on browser support, while ts relies on muxer support
  44481. const supportFunction = (isFmp4, codec) => isFmp4 ? codecs_js.browserSupportsCodec(codec) : codecs_js.muxerSupportsCodec(codec);
  44482. const unsupportedCodecs = {};
  44483. let unsupportedAudio;
  44484. ['video', 'audio'].forEach(function (type) {
  44485. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  44486. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  44487. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  44488. unsupportedCodecs[supporter].push(codecs[type]);
  44489. if (type === 'audio') {
  44490. unsupportedAudio = supporter;
  44491. }
  44492. }
  44493. });
  44494. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  44495. const audioGroup = playlist.attributes.AUDIO;
  44496. this.main().playlists.forEach(variant => {
  44497. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  44498. if (variantAudioGroup === audioGroup && variant !== playlist) {
  44499. variant.excludeUntil = Infinity;
  44500. }
  44501. });
  44502. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  44503. } // if we have any unsupported codecs exclude this playlist.
  44504. if (Object.keys(unsupportedCodecs).length) {
  44505. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  44506. if (acc) {
  44507. acc += ', ';
  44508. }
  44509. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  44510. return acc;
  44511. }, '') + '.';
  44512. this.excludePlaylist({
  44513. playlistToExclude: playlist,
  44514. error: {
  44515. internal: true,
  44516. message
  44517. },
  44518. playlistExclusionDuration: Infinity
  44519. });
  44520. return;
  44521. } // check if codec switching is happening
  44522. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  44523. const switchMessages = [];
  44524. ['video', 'audio'].forEach(type => {
  44525. const newCodec = (codecs_js.parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  44526. const oldCodec = (codecs_js.parseCodecs(codecs[type] || '')[0] || {}).type;
  44527. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  44528. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  44529. }
  44530. });
  44531. if (switchMessages.length) {
  44532. this.excludePlaylist({
  44533. playlistToExclude: playlist,
  44534. error: {
  44535. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  44536. internal: true
  44537. },
  44538. playlistExclusionDuration: Infinity
  44539. });
  44540. return;
  44541. }
  44542. } // TODO: when using the muxer shouldn't we just return
  44543. // the codecs that the muxer outputs?
  44544. return codecs;
  44545. }
  44546. /**
  44547. * Create source buffers and exlude any incompatible renditions.
  44548. *
  44549. * @private
  44550. */
  44551. tryToCreateSourceBuffers_() {
  44552. // media source is not ready yet or sourceBuffers are already
  44553. // created.
  44554. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  44555. return;
  44556. }
  44557. if (!this.areMediaTypesKnown_()) {
  44558. return;
  44559. }
  44560. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  44561. if (!codecs) {
  44562. return;
  44563. }
  44564. this.sourceUpdater_.createSourceBuffers(codecs);
  44565. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  44566. this.excludeIncompatibleVariants_(codecString);
  44567. }
  44568. /**
  44569. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  44570. */
  44571. excludeUnsupportedVariants_() {
  44572. const playlists = this.main().playlists;
  44573. const ids = []; // TODO: why don't we have a property to loop through all
  44574. // playlist? Why did we ever mix indexes and keys?
  44575. Object.keys(playlists).forEach(key => {
  44576. const variant = playlists[key]; // check if we already processed this playlist.
  44577. if (ids.indexOf(variant.id) !== -1) {
  44578. return;
  44579. }
  44580. ids.push(variant.id);
  44581. const codecs = codecsForPlaylist(this.main, variant);
  44582. const unsupported = [];
  44583. if (codecs.audio && !codecs_js.muxerSupportsCodec(codecs.audio) && !codecs_js.browserSupportsCodec(codecs.audio)) {
  44584. unsupported.push(`audio codec ${codecs.audio}`);
  44585. }
  44586. if (codecs.video && !codecs_js.muxerSupportsCodec(codecs.video) && !codecs_js.browserSupportsCodec(codecs.video)) {
  44587. unsupported.push(`video codec ${codecs.video}`);
  44588. }
  44589. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  44590. unsupported.push(`text codec ${codecs.text}`);
  44591. }
  44592. if (unsupported.length) {
  44593. variant.excludeUntil = Infinity;
  44594. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  44595. }
  44596. });
  44597. }
  44598. /**
  44599. * Exclude playlists that are known to be codec or
  44600. * stream-incompatible with the SourceBuffer configuration. For
  44601. * instance, Media Source Extensions would cause the video element to
  44602. * stall waiting for video data if you switched from a variant with
  44603. * video and audio to an audio-only one.
  44604. *
  44605. * @param {Object} media a media playlist compatible with the current
  44606. * set of SourceBuffers. Variants in the current main playlist that
  44607. * do not appear to have compatible codec or stream configurations
  44608. * will be excluded from the default playlist selection algorithm
  44609. * indefinitely.
  44610. * @private
  44611. */
  44612. excludeIncompatibleVariants_(codecString) {
  44613. const ids = [];
  44614. const playlists = this.main().playlists;
  44615. const codecs = unwrapCodecList(codecs_js.parseCodecs(codecString));
  44616. const codecCount_ = codecCount(codecs);
  44617. const videoDetails = codecs.video && codecs_js.parseCodecs(codecs.video)[0] || null;
  44618. const audioDetails = codecs.audio && codecs_js.parseCodecs(codecs.audio)[0] || null;
  44619. Object.keys(playlists).forEach(key => {
  44620. const variant = playlists[key]; // check if we already processed this playlist.
  44621. // or it if it is already excluded forever.
  44622. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  44623. return;
  44624. }
  44625. ids.push(variant.id);
  44626. const exclusionReasons = []; // get codecs from the playlist for this variant
  44627. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  44628. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  44629. // variant is incompatible. Wait for mux.js to probe
  44630. if (!variantCodecs.audio && !variantCodecs.video) {
  44631. return;
  44632. } // TODO: we can support this by removing the
  44633. // old media source and creating a new one, but it will take some work.
  44634. // The number of streams cannot change
  44635. if (variantCodecCount !== codecCount_) {
  44636. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  44637. } // only exclude playlists by codec change, if codecs cannot switch
  44638. // during playback.
  44639. if (!this.sourceUpdater_.canChangeType()) {
  44640. const variantVideoDetails = variantCodecs.video && codecs_js.parseCodecs(variantCodecs.video)[0] || null;
  44641. const variantAudioDetails = variantCodecs.audio && codecs_js.parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  44642. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  44643. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  44644. } // the audio codec cannot change
  44645. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  44646. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  44647. }
  44648. }
  44649. if (exclusionReasons.length) {
  44650. variant.excludeUntil = Infinity;
  44651. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  44652. }
  44653. });
  44654. }
  44655. updateAdCues_(media) {
  44656. let offset = 0;
  44657. const seekable = this.seekable();
  44658. if (seekable.length) {
  44659. offset = seekable.start(0);
  44660. }
  44661. updateAdCues(media, this.cueTagsTrack_, offset);
  44662. }
  44663. /**
  44664. * Calculates the desired forward buffer length based on current time
  44665. *
  44666. * @return {number} Desired forward buffer length in seconds
  44667. */
  44668. goalBufferLength() {
  44669. const currentTime = this.tech_.currentTime();
  44670. const initial = Config.GOAL_BUFFER_LENGTH;
  44671. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  44672. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  44673. return Math.min(initial + currentTime * rate, max);
  44674. }
  44675. /**
  44676. * Calculates the desired buffer low water line based on current time
  44677. *
  44678. * @return {number} Desired buffer low water line in seconds
  44679. */
  44680. bufferLowWaterLine() {
  44681. const currentTime = this.tech_.currentTime();
  44682. const initial = Config.BUFFER_LOW_WATER_LINE;
  44683. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  44684. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  44685. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  44686. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  44687. }
  44688. bufferHighWaterLine() {
  44689. return Config.BUFFER_HIGH_WATER_LINE;
  44690. }
  44691. }
  44692. /**
  44693. * Returns a function that acts as the Enable/disable playlist function.
  44694. *
  44695. * @param {PlaylistLoader} loader - The main playlist loader
  44696. * @param {string} playlistID - id of the playlist
  44697. * @param {Function} changePlaylistFn - A function to be called after a
  44698. * playlist's enabled-state has been changed. Will NOT be called if a
  44699. * playlist's enabled-state is unchanged
  44700. * @param {boolean=} enable - Value to set the playlist enabled-state to
  44701. * or if undefined returns the current enabled-state for the playlist
  44702. * @return {Function} Function for setting/getting enabled
  44703. */
  44704. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  44705. const playlist = loader.main.playlists[playlistID];
  44706. const incompatible = isIncompatible(playlist);
  44707. const currentlyEnabled = isEnabled(playlist);
  44708. if (typeof enable === 'undefined') {
  44709. return currentlyEnabled;
  44710. }
  44711. if (enable) {
  44712. delete playlist.disabled;
  44713. } else {
  44714. playlist.disabled = true;
  44715. }
  44716. if (enable !== currentlyEnabled && !incompatible) {
  44717. // Ensure the outside world knows about our changes
  44718. changePlaylistFn();
  44719. if (enable) {
  44720. loader.trigger('renditionenabled');
  44721. } else {
  44722. loader.trigger('renditiondisabled');
  44723. }
  44724. }
  44725. return enable;
  44726. };
  44727. /**
  44728. * The representation object encapsulates the publicly visible information
  44729. * in a media playlist along with a setter/getter-type function (enabled)
  44730. * for changing the enabled-state of a particular playlist entry
  44731. *
  44732. * @class Representation
  44733. */
  44734. class Representation {
  44735. constructor(vhsHandler, playlist, id) {
  44736. const {
  44737. playlistController_: pc
  44738. } = vhsHandler;
  44739. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  44740. if (playlist.attributes) {
  44741. const resolution = playlist.attributes.RESOLUTION;
  44742. this.width = resolution && resolution.width;
  44743. this.height = resolution && resolution.height;
  44744. this.bandwidth = playlist.attributes.BANDWIDTH;
  44745. this.frameRate = playlist.attributes['FRAME-RATE'];
  44746. }
  44747. this.codecs = codecsForPlaylist(pc.main(), playlist);
  44748. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  44749. // within the main playlist
  44750. this.id = id; // Partially-apply the enableFunction to create a playlist-
  44751. // specific variant
  44752. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  44753. }
  44754. }
  44755. /**
  44756. * A mixin function that adds the `representations` api to an instance
  44757. * of the VhsHandler class
  44758. *
  44759. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  44760. * representation API into
  44761. */
  44762. const renditionSelectionMixin = function (vhsHandler) {
  44763. // Add a single API-specific function to the VhsHandler instance
  44764. vhsHandler.representations = () => {
  44765. const main = vhsHandler.playlistController_.main();
  44766. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  44767. if (!playlists) {
  44768. return [];
  44769. }
  44770. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  44771. };
  44772. };
  44773. /**
  44774. * @file playback-watcher.js
  44775. *
  44776. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  44777. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  44778. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  44779. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  44780. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  44781. */
  44782. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  44783. /**
  44784. * @class PlaybackWatcher
  44785. */
  44786. class PlaybackWatcher {
  44787. /**
  44788. * Represents an PlaybackWatcher object.
  44789. *
  44790. * @class
  44791. * @param {Object} options an object that includes the tech and settings
  44792. */
  44793. constructor(options) {
  44794. this.playlistController_ = options.playlistController;
  44795. this.tech_ = options.tech;
  44796. this.seekable = options.seekable;
  44797. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  44798. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  44799. this.media = options.media;
  44800. this.consecutiveUpdates = 0;
  44801. this.lastRecordedTime = null;
  44802. this.checkCurrentTimeTimeout_ = null;
  44803. this.logger_ = logger('PlaybackWatcher');
  44804. this.logger_('initialize');
  44805. const playHandler = () => this.monitorCurrentTime_();
  44806. const canPlayHandler = () => this.monitorCurrentTime_();
  44807. const waitingHandler = () => this.techWaiting_();
  44808. const cancelTimerHandler = () => this.resetTimeUpdate_();
  44809. const pc = this.playlistController_;
  44810. const loaderTypes = ['main', 'subtitle', 'audio'];
  44811. const loaderChecks = {};
  44812. loaderTypes.forEach(type => {
  44813. loaderChecks[type] = {
  44814. reset: () => this.resetSegmentDownloads_(type),
  44815. updateend: () => this.checkSegmentDownloads_(type)
  44816. };
  44817. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  44818. // isn't changing we want to reset. We cannot assume that the new rendition
  44819. // will also be stalled, until after new appends.
  44820. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  44821. // This prevents one segment playlists (single vtt or single segment content)
  44822. // from being detected as stalling. As the buffer will not change in those cases, since
  44823. // the buffer is the entire video duration.
  44824. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  44825. });
  44826. /**
  44827. * We check if a seek was into a gap through the following steps:
  44828. * 1. We get a seeking event and we do not get a seeked event. This means that
  44829. * a seek was attempted but not completed.
  44830. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  44831. * removed everything from our buffer and appended a segment, and should be ready
  44832. * to check for gaps.
  44833. */
  44834. const setSeekingHandlers = fn => {
  44835. ['main', 'audio'].forEach(type => {
  44836. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  44837. });
  44838. };
  44839. this.seekingAppendCheck_ = () => {
  44840. if (this.fixesBadSeeks_()) {
  44841. this.consecutiveUpdates = 0;
  44842. this.lastRecordedTime = this.tech_.currentTime();
  44843. setSeekingHandlers('off');
  44844. }
  44845. };
  44846. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  44847. this.watchForBadSeeking_ = () => {
  44848. this.clearSeekingAppendCheck_();
  44849. setSeekingHandlers('on');
  44850. };
  44851. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  44852. this.tech_.on('seeking', this.watchForBadSeeking_);
  44853. this.tech_.on('waiting', waitingHandler);
  44854. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  44855. this.tech_.on('canplay', canPlayHandler);
  44856. /*
  44857. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  44858. is surfaced in one of two ways:
  44859. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  44860. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  44861. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  44862. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  44863. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  44864. even if the player is in a playing state
  44865. */
  44866. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  44867. this.dispose = () => {
  44868. this.clearSeekingAppendCheck_();
  44869. this.logger_('dispose');
  44870. this.tech_.off('waiting', waitingHandler);
  44871. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  44872. this.tech_.off('canplay', canPlayHandler);
  44873. this.tech_.off('play', playHandler);
  44874. this.tech_.off('seeking', this.watchForBadSeeking_);
  44875. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  44876. loaderTypes.forEach(type => {
  44877. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  44878. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  44879. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  44880. });
  44881. if (this.checkCurrentTimeTimeout_) {
  44882. window__default["default"].clearTimeout(this.checkCurrentTimeTimeout_);
  44883. }
  44884. this.resetTimeUpdate_();
  44885. };
  44886. }
  44887. /**
  44888. * Periodically check current time to see if playback stopped
  44889. *
  44890. * @private
  44891. */
  44892. monitorCurrentTime_() {
  44893. this.checkCurrentTime_();
  44894. if (this.checkCurrentTimeTimeout_) {
  44895. window__default["default"].clearTimeout(this.checkCurrentTimeTimeout_);
  44896. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  44897. this.checkCurrentTimeTimeout_ = window__default["default"].setTimeout(this.monitorCurrentTime_.bind(this), 250);
  44898. }
  44899. /**
  44900. * Reset stalled download stats for a specific type of loader
  44901. *
  44902. * @param {string} type
  44903. * The segment loader type to check.
  44904. *
  44905. * @listens SegmentLoader#playlistupdate
  44906. * @listens Tech#seeking
  44907. * @listens Tech#seeked
  44908. */
  44909. resetSegmentDownloads_(type) {
  44910. const loader = this.playlistController_[`${type}SegmentLoader_`];
  44911. if (this[`${type}StalledDownloads_`] > 0) {
  44912. this.logger_(`resetting possible stalled download count for ${type} loader`);
  44913. }
  44914. this[`${type}StalledDownloads_`] = 0;
  44915. this[`${type}Buffered_`] = loader.buffered_();
  44916. }
  44917. /**
  44918. * Checks on every segment `appendsdone` to see
  44919. * if segment appends are making progress. If they are not
  44920. * and we are still downloading bytes. We exclude the playlist.
  44921. *
  44922. * @param {string} type
  44923. * The segment loader type to check.
  44924. *
  44925. * @listens SegmentLoader#appendsdone
  44926. */
  44927. checkSegmentDownloads_(type) {
  44928. const pc = this.playlistController_;
  44929. const loader = pc[`${type}SegmentLoader_`];
  44930. const buffered = loader.buffered_();
  44931. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  44932. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  44933. // the buffered value for this loader changed
  44934. // appends are working
  44935. if (isBufferedDifferent) {
  44936. this.resetSegmentDownloads_(type);
  44937. return;
  44938. }
  44939. this[`${type}StalledDownloads_`]++;
  44940. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  44941. playlistId: loader.playlist_ && loader.playlist_.id,
  44942. buffered: timeRangesToArray(buffered)
  44943. }); // after 10 possibly stalled appends with no reset, exclude
  44944. if (this[`${type}StalledDownloads_`] < 10) {
  44945. return;
  44946. }
  44947. this.logger_(`${type} loader stalled download exclusion`);
  44948. this.resetSegmentDownloads_(type);
  44949. this.tech_.trigger({
  44950. type: 'usage',
  44951. name: `vhs-${type}-download-exclusion`
  44952. });
  44953. if (type === 'subtitle') {
  44954. return;
  44955. } // TODO: should we exclude audio tracks rather than main tracks
  44956. // when type is audio?
  44957. pc.excludePlaylist({
  44958. error: {
  44959. message: `Excessive ${type} segment downloading detected.`
  44960. },
  44961. playlistExclusionDuration: Infinity
  44962. });
  44963. }
  44964. /**
  44965. * The purpose of this function is to emulate the "waiting" event on
  44966. * browsers that do not emit it when they are waiting for more
  44967. * data to continue playback
  44968. *
  44969. * @private
  44970. */
  44971. checkCurrentTime_() {
  44972. if (this.tech_.paused() || this.tech_.seeking()) {
  44973. return;
  44974. }
  44975. const currentTime = this.tech_.currentTime();
  44976. const buffered = this.tech_.buffered();
  44977. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  44978. // If current time is at the end of the final buffered region, then any playback
  44979. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  44980. // should fire a `waiting` event in this scenario, but due to browser and tech
  44981. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  44982. // responding to a native `waiting` event when the tech fails to emit one.
  44983. return this.techWaiting_();
  44984. }
  44985. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  44986. this.consecutiveUpdates++;
  44987. this.waiting_();
  44988. } else if (currentTime === this.lastRecordedTime) {
  44989. this.consecutiveUpdates++;
  44990. } else {
  44991. this.consecutiveUpdates = 0;
  44992. this.lastRecordedTime = currentTime;
  44993. }
  44994. }
  44995. /**
  44996. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  44997. *
  44998. * @private
  44999. */
  45000. resetTimeUpdate_() {
  45001. this.consecutiveUpdates = 0;
  45002. }
  45003. /**
  45004. * Fixes situations where there's a bad seek
  45005. *
  45006. * @return {boolean} whether an action was taken to fix the seek
  45007. * @private
  45008. */
  45009. fixesBadSeeks_() {
  45010. const seeking = this.tech_.seeking();
  45011. if (!seeking) {
  45012. return false;
  45013. } // TODO: It's possible that these seekable checks should be moved out of this function
  45014. // and into a function that runs on seekablechange. It's also possible that we only need
  45015. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  45016. // seekable range.
  45017. const seekable = this.seekable();
  45018. const currentTime = this.tech_.currentTime();
  45019. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  45020. let seekTo;
  45021. if (isAfterSeekableRange) {
  45022. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  45023. seekTo = seekableEnd;
  45024. }
  45025. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45026. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  45027. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  45028. seekTo = seekableStart + (
  45029. // if the playlist is too short and the seekable range is an exact time (can
  45030. // happen in live with a 3 segment playlist), then don't use a time delta
  45031. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  45032. }
  45033. if (typeof seekTo !== 'undefined') {
  45034. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  45035. this.tech_.setCurrentTime(seekTo);
  45036. return true;
  45037. }
  45038. const sourceUpdater = this.playlistController_.sourceUpdater_;
  45039. const buffered = this.tech_.buffered();
  45040. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  45041. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  45042. const media = this.media(); // verify that at least two segment durations or one part duration have been
  45043. // appended before checking for a gap.
  45044. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  45045. // appended before checking for a gap.
  45046. const bufferedToCheck = [audioBuffered, videoBuffered];
  45047. for (let i = 0; i < bufferedToCheck.length; i++) {
  45048. // skip null buffered
  45049. if (!bufferedToCheck[i]) {
  45050. continue;
  45051. }
  45052. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  45053. // duration behind we haven't appended enough to call this a bad seek.
  45054. if (timeAhead < minAppendedDuration) {
  45055. return false;
  45056. }
  45057. }
  45058. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  45059. // to seek over the gap
  45060. if (nextRange.length === 0) {
  45061. return false;
  45062. }
  45063. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  45064. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  45065. this.tech_.setCurrentTime(seekTo);
  45066. return true;
  45067. }
  45068. /**
  45069. * Handler for situations when we determine the player is waiting.
  45070. *
  45071. * @private
  45072. */
  45073. waiting_() {
  45074. if (this.techWaiting_()) {
  45075. return;
  45076. } // All tech waiting checks failed. Use last resort correction
  45077. const currentTime = this.tech_.currentTime();
  45078. const buffered = this.tech_.buffered();
  45079. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  45080. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  45081. // currentTime is usually enough to kickstart the player. This checks that the player
  45082. // is currently within a buffered region before attempting a corrective seek.
  45083. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  45084. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  45085. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  45086. // to avoid triggering an `unknownwaiting` event when the network is slow.
  45087. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  45088. this.resetTimeUpdate_();
  45089. this.tech_.setCurrentTime(currentTime);
  45090. this.logger_(`Stopped at ${currentTime} while inside a buffered region ` + `[${currentRange.start(0)} -> ${currentRange.end(0)}]. Attempting to resume ` + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
  45091. this.tech_.trigger({
  45092. type: 'usage',
  45093. name: 'vhs-unknown-waiting'
  45094. });
  45095. return;
  45096. }
  45097. }
  45098. /**
  45099. * Handler for situations when the tech fires a `waiting` event
  45100. *
  45101. * @return {boolean}
  45102. * True if an action (or none) was needed to correct the waiting. False if no
  45103. * checks passed
  45104. * @private
  45105. */
  45106. techWaiting_() {
  45107. const seekable = this.seekable();
  45108. const currentTime = this.tech_.currentTime();
  45109. if (this.tech_.seeking()) {
  45110. // Tech is seeking or already waiting on another action, no action needed
  45111. return true;
  45112. }
  45113. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45114. const livePoint = seekable.end(seekable.length - 1);
  45115. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  45116. this.resetTimeUpdate_();
  45117. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  45118. this.tech_.trigger({
  45119. type: 'usage',
  45120. name: 'vhs-live-resync'
  45121. });
  45122. return true;
  45123. }
  45124. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  45125. const buffered = this.tech_.buffered();
  45126. const videoUnderflow = this.videoUnderflow_({
  45127. audioBuffered: sourceUpdater.audioBuffered(),
  45128. videoBuffered: sourceUpdater.videoBuffered(),
  45129. currentTime
  45130. });
  45131. if (videoUnderflow) {
  45132. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  45133. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  45134. // allows the video to catch up to the audio position without losing any audio
  45135. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  45136. this.resetTimeUpdate_();
  45137. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  45138. this.tech_.trigger({
  45139. type: 'usage',
  45140. name: 'vhs-video-underflow'
  45141. });
  45142. return true;
  45143. }
  45144. const nextRange = findNextRange(buffered, currentTime); // check for gap
  45145. if (nextRange.length > 0) {
  45146. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  45147. this.resetTimeUpdate_();
  45148. this.skipTheGap_(currentTime);
  45149. return true;
  45150. } // All checks failed. Returning false to indicate failure to correct waiting
  45151. return false;
  45152. }
  45153. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  45154. if (!seekable.length) {
  45155. // we can't make a solid case if there's no seekable, default to false
  45156. return false;
  45157. }
  45158. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  45159. const isLive = !playlist.endList;
  45160. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  45161. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  45162. }
  45163. if (currentTime > allowedEnd) {
  45164. return true;
  45165. }
  45166. return false;
  45167. }
  45168. beforeSeekableWindow_(seekable, currentTime) {
  45169. if (seekable.length &&
  45170. // can't fall before 0 and 0 seekable start identifies VOD stream
  45171. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  45172. return true;
  45173. }
  45174. return false;
  45175. }
  45176. videoUnderflow_({
  45177. videoBuffered,
  45178. audioBuffered,
  45179. currentTime
  45180. }) {
  45181. // audio only content will not have video underflow :)
  45182. if (!videoBuffered) {
  45183. return;
  45184. }
  45185. let gap; // find a gap in demuxed content.
  45186. if (videoBuffered.length && audioBuffered.length) {
  45187. // in Chrome audio will continue to play for ~3s when we run out of video
  45188. // so we have to check that the video buffer did have some buffer in the
  45189. // past.
  45190. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  45191. const videoRange = findRange(videoBuffered, currentTime);
  45192. const audioRange = findRange(audioBuffered, currentTime);
  45193. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  45194. gap = {
  45195. start: lastVideoRange.end(0),
  45196. end: audioRange.end(0)
  45197. };
  45198. } // find a gap in muxed content.
  45199. } else {
  45200. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  45201. // stuck in a gap due to video underflow.
  45202. if (!nextRange.length) {
  45203. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  45204. }
  45205. }
  45206. if (gap) {
  45207. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  45208. return true;
  45209. }
  45210. return false;
  45211. }
  45212. /**
  45213. * Timer callback. If playback still has not proceeded, then we seek
  45214. * to the start of the next buffered region.
  45215. *
  45216. * @private
  45217. */
  45218. skipTheGap_(scheduledCurrentTime) {
  45219. const buffered = this.tech_.buffered();
  45220. const currentTime = this.tech_.currentTime();
  45221. const nextRange = findNextRange(buffered, currentTime);
  45222. this.resetTimeUpdate_();
  45223. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  45224. return;
  45225. }
  45226. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  45227. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  45228. this.tech_.trigger({
  45229. type: 'usage',
  45230. name: 'vhs-gap-skip'
  45231. });
  45232. }
  45233. gapFromVideoUnderflow_(buffered, currentTime) {
  45234. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  45235. // playing for ~3 seconds after the video gap starts. This is done to account for
  45236. // video buffer underflow/underrun (note that this is not done when there is audio
  45237. // buffer underflow/underrun -- in that case the video will stop as soon as it
  45238. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  45239. // video stalls). The player's time will reflect the playthrough of audio, so the
  45240. // time will appear as if we are in a buffered region, even if we are stuck in a
  45241. // "gap."
  45242. //
  45243. // Example:
  45244. // video buffer: 0 => 10.1, 10.2 => 20
  45245. // audio buffer: 0 => 20
  45246. // overall buffer: 0 => 10.1, 10.2 => 20
  45247. // current time: 13
  45248. //
  45249. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  45250. // however, the audio continued playing until it reached ~3 seconds past the gap
  45251. // (13 seconds), at which point it stops as well. Since current time is past the
  45252. // gap, findNextRange will return no ranges.
  45253. //
  45254. // To check for this issue, we see if there is a gap that starts somewhere within
  45255. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  45256. const gaps = findGaps(buffered);
  45257. for (let i = 0; i < gaps.length; i++) {
  45258. const start = gaps.start(i);
  45259. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  45260. if (currentTime - start < 4 && currentTime - start > 2) {
  45261. return {
  45262. start,
  45263. end
  45264. };
  45265. }
  45266. }
  45267. return null;
  45268. }
  45269. }
  45270. const defaultOptions = {
  45271. errorInterval: 30,
  45272. getSource(next) {
  45273. const tech = this.tech({
  45274. IWillNotUseThisInPlugins: true
  45275. });
  45276. const sourceObj = tech.currentSource_ || this.currentSource();
  45277. return next(sourceObj);
  45278. }
  45279. };
  45280. /**
  45281. * Main entry point for the plugin
  45282. *
  45283. * @param {Player} player a reference to a videojs Player instance
  45284. * @param {Object} [options] an object with plugin options
  45285. * @private
  45286. */
  45287. const initPlugin = function (player, options) {
  45288. let lastCalled = 0;
  45289. let seekTo = 0;
  45290. const localOptions = merge(defaultOptions, options);
  45291. player.ready(() => {
  45292. player.trigger({
  45293. type: 'usage',
  45294. name: 'vhs-error-reload-initialized'
  45295. });
  45296. });
  45297. /**
  45298. * Player modifications to perform that must wait until `loadedmetadata`
  45299. * has been triggered
  45300. *
  45301. * @private
  45302. */
  45303. const loadedMetadataHandler = function () {
  45304. if (seekTo) {
  45305. player.currentTime(seekTo);
  45306. }
  45307. };
  45308. /**
  45309. * Set the source on the player element, play, and seek if necessary
  45310. *
  45311. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  45312. * @private
  45313. */
  45314. const setSource = function (sourceObj) {
  45315. if (sourceObj === null || sourceObj === undefined) {
  45316. return;
  45317. }
  45318. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  45319. player.one('loadedmetadata', loadedMetadataHandler);
  45320. player.src(sourceObj);
  45321. player.trigger({
  45322. type: 'usage',
  45323. name: 'vhs-error-reload'
  45324. });
  45325. player.play();
  45326. };
  45327. /**
  45328. * Attempt to get a source from either the built-in getSource function
  45329. * or a custom function provided via the options
  45330. *
  45331. * @private
  45332. */
  45333. const errorHandler = function () {
  45334. // Do not attempt to reload the source if a source-reload occurred before
  45335. // 'errorInterval' time has elapsed since the last source-reload
  45336. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  45337. player.trigger({
  45338. type: 'usage',
  45339. name: 'vhs-error-reload-canceled'
  45340. });
  45341. return;
  45342. }
  45343. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  45344. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  45345. return;
  45346. }
  45347. lastCalled = Date.now();
  45348. return localOptions.getSource.call(player, setSource);
  45349. };
  45350. /**
  45351. * Unbind any event handlers that were bound by the plugin
  45352. *
  45353. * @private
  45354. */
  45355. const cleanupEvents = function () {
  45356. player.off('loadedmetadata', loadedMetadataHandler);
  45357. player.off('error', errorHandler);
  45358. player.off('dispose', cleanupEvents);
  45359. };
  45360. /**
  45361. * Cleanup before re-initializing the plugin
  45362. *
  45363. * @param {Object} [newOptions] an object with plugin options
  45364. * @private
  45365. */
  45366. const reinitPlugin = function (newOptions) {
  45367. cleanupEvents();
  45368. initPlugin(player, newOptions);
  45369. };
  45370. player.on('error', errorHandler);
  45371. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  45372. // initializing the plugin
  45373. player.reloadSourceOnError = reinitPlugin;
  45374. };
  45375. /**
  45376. * Reload the source when an error is detected as long as there
  45377. * wasn't an error previously within the last 30 seconds
  45378. *
  45379. * @param {Object} [options] an object with plugin options
  45380. */
  45381. const reloadSourceOnError = function (options) {
  45382. initPlugin(this, options);
  45383. };
  45384. var version$4 = "3.0.2";
  45385. var version$3 = "6.3.0";
  45386. var version$2 = "1.0.1";
  45387. var version$1 = "6.0.0";
  45388. var version = "4.0.1";
  45389. /**
  45390. * @file videojs-http-streaming.js
  45391. *
  45392. * The main file for the VHS project.
  45393. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  45394. */
  45395. const Vhs = {
  45396. PlaylistLoader,
  45397. Playlist,
  45398. utils,
  45399. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  45400. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  45401. lastBandwidthSelector,
  45402. movingAverageBandwidthSelector,
  45403. comparePlaylistBandwidth,
  45404. comparePlaylistResolution,
  45405. xhr: xhrFactory()
  45406. }; // Define getter/setters for config properties
  45407. Object.keys(Config).forEach(prop => {
  45408. Object.defineProperty(Vhs, prop, {
  45409. get() {
  45410. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  45411. return Config[prop];
  45412. },
  45413. set(value) {
  45414. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  45415. if (typeof value !== 'number' || value < 0) {
  45416. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  45417. return;
  45418. }
  45419. Config[prop] = value;
  45420. }
  45421. });
  45422. });
  45423. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  45424. /**
  45425. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  45426. *
  45427. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  45428. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  45429. * @function handleVhsMediaChange
  45430. */
  45431. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  45432. const newPlaylist = playlistLoader.media();
  45433. let selectedIndex = -1;
  45434. for (let i = 0; i < qualityLevels.length; i++) {
  45435. if (qualityLevels[i].id === newPlaylist.id) {
  45436. selectedIndex = i;
  45437. break;
  45438. }
  45439. }
  45440. qualityLevels.selectedIndex_ = selectedIndex;
  45441. qualityLevels.trigger({
  45442. selectedIndex,
  45443. type: 'change'
  45444. });
  45445. };
  45446. /**
  45447. * Adds quality levels to list once playlist metadata is available
  45448. *
  45449. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  45450. * @param {Object} vhs Vhs object to listen to for media events.
  45451. * @function handleVhsLoadedMetadata
  45452. */
  45453. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  45454. vhs.representations().forEach(rep => {
  45455. qualityLevels.addQualityLevel(rep);
  45456. });
  45457. handleVhsMediaChange(qualityLevels, vhs.playlists);
  45458. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  45459. // as one do not cause exceptions.
  45460. Vhs.canPlaySource = function () {
  45461. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45462. };
  45463. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  45464. if (!keySystemOptions) {
  45465. return keySystemOptions;
  45466. }
  45467. let codecs = {};
  45468. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  45469. codecs = unwrapCodecList(codecs_js.parseCodecs(mainPlaylist.attributes.CODECS));
  45470. }
  45471. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  45472. codecs.audio = audioPlaylist.attributes.CODECS;
  45473. }
  45474. const videoContentType = codecs_js.getMimeForCodec(codecs.video);
  45475. const audioContentType = codecs_js.getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  45476. const keySystemContentTypes = {};
  45477. for (const keySystem in keySystemOptions) {
  45478. keySystemContentTypes[keySystem] = {};
  45479. if (audioContentType) {
  45480. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  45481. }
  45482. if (videoContentType) {
  45483. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  45484. } // Default to using the video playlist's PSSH even though they may be different, as
  45485. // videojs-contrib-eme will only accept one in the options.
  45486. //
  45487. // This shouldn't be an issue for most cases as early intialization will handle all
  45488. // unique PSSH values, and if they aren't, then encrypted events should have the
  45489. // specific information needed for the unique license.
  45490. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  45491. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  45492. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  45493. // so we need to prevent overwriting the URL entirely
  45494. if (typeof keySystemOptions[keySystem] === 'string') {
  45495. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  45496. }
  45497. }
  45498. return merge(keySystemOptions, keySystemContentTypes);
  45499. };
  45500. /**
  45501. * @typedef {Object} KeySystems
  45502. *
  45503. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  45504. * Note: not all options are listed here.
  45505. *
  45506. * @property {Uint8Array} [pssh]
  45507. * Protection System Specific Header
  45508. */
  45509. /**
  45510. * Goes through all the playlists and collects an array of KeySystems options objects
  45511. * containing each playlist's keySystems and their pssh values, if available.
  45512. *
  45513. * @param {Object[]} playlists
  45514. * The playlists to look through
  45515. * @param {string[]} keySystems
  45516. * The keySystems to collect pssh values for
  45517. *
  45518. * @return {KeySystems[]}
  45519. * An array of KeySystems objects containing available key systems and their
  45520. * pssh values
  45521. */
  45522. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  45523. return playlists.reduce((keySystemsArr, playlist) => {
  45524. if (!playlist.contentProtection) {
  45525. return keySystemsArr;
  45526. }
  45527. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  45528. const keySystemOptions = playlist.contentProtection[keySystem];
  45529. if (keySystemOptions && keySystemOptions.pssh) {
  45530. keySystemsObj[keySystem] = {
  45531. pssh: keySystemOptions.pssh
  45532. };
  45533. }
  45534. return keySystemsObj;
  45535. }, {});
  45536. if (Object.keys(keySystemsOptions).length) {
  45537. keySystemsArr.push(keySystemsOptions);
  45538. }
  45539. return keySystemsArr;
  45540. }, []);
  45541. };
  45542. /**
  45543. * Returns a promise that waits for the
  45544. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  45545. *
  45546. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  45547. * browsers.
  45548. *
  45549. * As per the above ticket, this is particularly important for Chrome, where, if
  45550. * unencrypted content is appended before encrypted content and the key session has not
  45551. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  45552. * during playback.
  45553. *
  45554. * @param {Object} player
  45555. * The player instance
  45556. * @param {Object[]} sourceKeySystems
  45557. * The key systems options from the player source
  45558. * @param {Object} [audioMedia]
  45559. * The active audio media playlist (optional)
  45560. * @param {Object[]} mainPlaylists
  45561. * The playlists found on the main playlist object
  45562. *
  45563. * @return {Object}
  45564. * Promise that resolves when the key session has been created
  45565. */
  45566. const waitForKeySessionCreation = ({
  45567. player,
  45568. sourceKeySystems,
  45569. audioMedia,
  45570. mainPlaylists
  45571. }) => {
  45572. if (!player.eme.initializeMediaKeys) {
  45573. return Promise.resolve();
  45574. } // TODO should all audio PSSH values be initialized for DRM?
  45575. //
  45576. // All unique video rendition pssh values are initialized for DRM, but here only
  45577. // the initial audio playlist license is initialized. In theory, an encrypted
  45578. // event should be fired if the user switches to an alternative audio playlist
  45579. // where a license is required, but this case hasn't yet been tested. In addition, there
  45580. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  45581. // languages).
  45582. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  45583. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  45584. const initializationFinishedPromises = [];
  45585. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  45586. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  45587. // return for IE11 above, and the existence of modern EME APIs in addition to
  45588. // ms-prefixed APIs on Edge should prevent this from being a concern.
  45589. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  45590. keySystemsOptionsArr.forEach(keySystemsOptions => {
  45591. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  45592. player.tech_.one('keysessioncreated', resolve);
  45593. }));
  45594. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  45595. player.eme.initializeMediaKeys({
  45596. keySystems: keySystemsOptions
  45597. }, err => {
  45598. if (err) {
  45599. reject(err);
  45600. return;
  45601. }
  45602. resolve();
  45603. });
  45604. }));
  45605. }); // The reasons Promise.race is chosen over Promise.any:
  45606. //
  45607. // * Promise.any is only available in Safari 14+.
  45608. // * None of these promises are expected to reject. If they do reject, it might be
  45609. // better here for the race to surface the rejection, rather than mask it by using
  45610. // Promise.any.
  45611. return Promise.race([
  45612. // If a session was previously created, these will all finish resolving without
  45613. // creating a new session, otherwise it will take until the end of all license
  45614. // requests, which is why the key session check is used (to make setup much faster).
  45615. Promise.all(initializationFinishedPromises),
  45616. // Once a single session is created, the browser knows DRM will be used.
  45617. Promise.race(keySessionCreatedPromises)]);
  45618. };
  45619. /**
  45620. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  45621. * there are keySystems on the source, sets up source options to prepare the source for
  45622. * eme.
  45623. *
  45624. * @param {Object} player
  45625. * The player instance
  45626. * @param {Object[]} sourceKeySystems
  45627. * The key systems options from the player source
  45628. * @param {Object} media
  45629. * The active media playlist
  45630. * @param {Object} [audioMedia]
  45631. * The active audio media playlist (optional)
  45632. *
  45633. * @return {boolean}
  45634. * Whether or not options were configured and EME is available
  45635. */
  45636. const setupEmeOptions = ({
  45637. player,
  45638. sourceKeySystems,
  45639. media,
  45640. audioMedia
  45641. }) => {
  45642. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  45643. if (!sourceOptions) {
  45644. return false;
  45645. }
  45646. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  45647. // do nothing.
  45648. if (sourceOptions && !player.eme) {
  45649. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  45650. return false;
  45651. }
  45652. return true;
  45653. };
  45654. const getVhsLocalStorage = () => {
  45655. if (!window__default["default"].localStorage) {
  45656. return null;
  45657. }
  45658. const storedObject = window__default["default"].localStorage.getItem(LOCAL_STORAGE_KEY);
  45659. if (!storedObject) {
  45660. return null;
  45661. }
  45662. try {
  45663. return JSON.parse(storedObject);
  45664. } catch (e) {
  45665. // someone may have tampered with the value
  45666. return null;
  45667. }
  45668. };
  45669. const updateVhsLocalStorage = options => {
  45670. if (!window__default["default"].localStorage) {
  45671. return false;
  45672. }
  45673. let objectToStore = getVhsLocalStorage();
  45674. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  45675. try {
  45676. window__default["default"].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  45677. } catch (e) {
  45678. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  45679. // storage is set to 0).
  45680. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  45681. // No need to perform any operation.
  45682. return false;
  45683. }
  45684. return objectToStore;
  45685. };
  45686. /**
  45687. * Parses VHS-supported media types from data URIs. See
  45688. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  45689. * for information on data URIs.
  45690. *
  45691. * @param {string} dataUri
  45692. * The data URI
  45693. *
  45694. * @return {string|Object}
  45695. * The parsed object/string, or the original string if no supported media type
  45696. * was found
  45697. */
  45698. const expandDataUri = dataUri => {
  45699. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  45700. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  45701. } // no known case for this data URI, return the string as-is
  45702. return dataUri;
  45703. };
  45704. /**
  45705. * Whether the browser has built-in HLS support.
  45706. */
  45707. Vhs.supportsNativeHls = function () {
  45708. if (!document__default["default"] || !document__default["default"].createElement) {
  45709. return false;
  45710. }
  45711. const video = document__default["default"].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  45712. if (!videojs.getTech('Html5').isSupported()) {
  45713. return false;
  45714. } // HLS manifests can go by many mime-types
  45715. const canPlay = [
  45716. // Apple santioned
  45717. 'application/vnd.apple.mpegurl',
  45718. // Apple sanctioned for backwards compatibility
  45719. 'audio/mpegurl',
  45720. // Very common
  45721. 'audio/x-mpegurl',
  45722. // Very common
  45723. 'application/x-mpegurl',
  45724. // Included for completeness
  45725. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  45726. return canPlay.some(function (canItPlay) {
  45727. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  45728. });
  45729. }();
  45730. Vhs.supportsNativeDash = function () {
  45731. if (!document__default["default"] || !document__default["default"].createElement || !videojs.getTech('Html5').isSupported()) {
  45732. return false;
  45733. }
  45734. return /maybe|probably/i.test(document__default["default"].createElement('video').canPlayType('application/dash+xml'));
  45735. }();
  45736. Vhs.supportsTypeNatively = type => {
  45737. if (type === 'hls') {
  45738. return Vhs.supportsNativeHls;
  45739. }
  45740. if (type === 'dash') {
  45741. return Vhs.supportsNativeDash;
  45742. }
  45743. return false;
  45744. };
  45745. /**
  45746. * VHS is a source handler, not a tech. Make sure attempts to use it
  45747. * as one do not cause exceptions.
  45748. */
  45749. Vhs.isSupported = function () {
  45750. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45751. };
  45752. const Component = videojs.getComponent('Component');
  45753. /**
  45754. * The Vhs Handler object, where we orchestrate all of the parts
  45755. * of VHS to interact with video.js
  45756. *
  45757. * @class VhsHandler
  45758. * @extends videojs.Component
  45759. * @param {Object} source the soruce object
  45760. * @param {Tech} tech the parent tech object
  45761. * @param {Object} options optional and required options
  45762. */
  45763. class VhsHandler extends Component {
  45764. constructor(source, tech, options) {
  45765. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  45766. // use that over the VHS level `bandwidth` option
  45767. if (typeof options.initialBandwidth === 'number') {
  45768. this.options_.bandwidth = options.initialBandwidth;
  45769. }
  45770. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  45771. // so, get it from Video.js via the `playerId`
  45772. if (tech.options_ && tech.options_.playerId) {
  45773. const _player = videojs.getPlayer(tech.options_.playerId);
  45774. this.player_ = _player;
  45775. }
  45776. this.tech_ = tech;
  45777. this.source_ = source;
  45778. this.stats = {};
  45779. this.ignoreNextSeekingEvent_ = false;
  45780. this.setOptions_();
  45781. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  45782. tech.overrideNativeAudioTracks(true);
  45783. tech.overrideNativeVideoTracks(true);
  45784. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  45785. // overriding native VHS only works if audio tracks have been emulated
  45786. // error early if we're misconfigured
  45787. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  45788. } // listen for fullscreenchange events for this player so that we
  45789. // can adjust our quality selection quickly
  45790. this.on(document__default["default"], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  45791. const fullscreenElement = document__default["default"].fullscreenElement || document__default["default"].webkitFullscreenElement || document__default["default"].mozFullScreenElement || document__default["default"].msFullscreenElement;
  45792. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  45793. this.playlistController_.fastQualityChange_();
  45794. } else {
  45795. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  45796. // than full screen, see if there should be a rendition switch down to preserve
  45797. // bandwidth.
  45798. this.playlistController_.checkABR_();
  45799. }
  45800. });
  45801. this.on(this.tech_, 'seeking', function () {
  45802. if (this.ignoreNextSeekingEvent_) {
  45803. this.ignoreNextSeekingEvent_ = false;
  45804. return;
  45805. }
  45806. this.setCurrentTime(this.tech_.currentTime());
  45807. });
  45808. this.on(this.tech_, 'error', function () {
  45809. // verify that the error was real and we are loaded
  45810. // enough to have pc loaded.
  45811. if (this.tech_.error() && this.playlistController_) {
  45812. this.playlistController_.pauseLoading();
  45813. }
  45814. });
  45815. this.on(this.tech_, 'play', this.play);
  45816. }
  45817. setOptions_() {
  45818. // defaults
  45819. this.options_.withCredentials = this.options_.withCredentials || false;
  45820. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  45821. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  45822. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  45823. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  45824. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  45825. this.options_.customTagParsers = this.options_.customTagParsers || [];
  45826. this.options_.customTagMappers = this.options_.customTagMappers || [];
  45827. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  45828. this.options_.llhls = this.options_.llhls === false ? false : true;
  45829. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  45830. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  45831. this.options_.playlistExclusionDuration = 5 * 60;
  45832. }
  45833. if (typeof this.options_.bandwidth !== 'number') {
  45834. if (this.options_.useBandwidthFromLocalStorage) {
  45835. const storedObject = getVhsLocalStorage();
  45836. if (storedObject && storedObject.bandwidth) {
  45837. this.options_.bandwidth = storedObject.bandwidth;
  45838. this.tech_.trigger({
  45839. type: 'usage',
  45840. name: 'vhs-bandwidth-from-local-storage'
  45841. });
  45842. }
  45843. if (storedObject && storedObject.throughput) {
  45844. this.options_.throughput = storedObject.throughput;
  45845. this.tech_.trigger({
  45846. type: 'usage',
  45847. name: 'vhs-throughput-from-local-storage'
  45848. });
  45849. }
  45850. }
  45851. } // if bandwidth was not set by options or pulled from local storage, start playlist
  45852. // selection at a reasonable bandwidth
  45853. if (typeof this.options_.bandwidth !== 'number') {
  45854. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  45855. } // If the bandwidth number is unchanged from the initial setting
  45856. // then this takes precedence over the enableLowInitialPlaylist option
  45857. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  45858. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  45859. if (typeof this.source_[option] !== 'undefined') {
  45860. this.options_[option] = this.source_[option];
  45861. }
  45862. });
  45863. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  45864. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  45865. }
  45866. /**
  45867. * called when player.src gets called, handle a new source
  45868. *
  45869. * @param {Object} src the source object to handle
  45870. */
  45871. src(src, type) {
  45872. // do nothing if the src is falsey
  45873. if (!src) {
  45874. return;
  45875. }
  45876. this.setOptions_(); // add main playlist controller options
  45877. this.options_.src = expandDataUri(this.source_.src);
  45878. this.options_.tech = this.tech_;
  45879. this.options_.externVhs = Vhs;
  45880. this.options_.sourceType = mediaTypes_js.simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  45881. this.options_.seekTo = time => {
  45882. this.tech_.setCurrentTime(time);
  45883. };
  45884. this.playlistController_ = new PlaylistController(this.options_);
  45885. const playbackWatcherOptions = merge({
  45886. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  45887. }, this.options_, {
  45888. seekable: () => this.seekable(),
  45889. media: () => this.playlistController_.media(),
  45890. playlistController: this.playlistController_
  45891. });
  45892. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  45893. this.playlistController_.on('error', () => {
  45894. const player = videojs.players[this.tech_.options_.playerId];
  45895. let error = this.playlistController_.error;
  45896. if (typeof error === 'object' && !error.code) {
  45897. error.code = 3;
  45898. } else if (typeof error === 'string') {
  45899. error = {
  45900. message: error,
  45901. code: 3
  45902. };
  45903. }
  45904. player.error(error);
  45905. });
  45906. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  45907. // compatibility with < v2
  45908. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  45909. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  45910. this.playlists = this.playlistController_.mainPlaylistLoader_;
  45911. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  45912. // controller. Using a custom property for backwards compatibility
  45913. // with < v2
  45914. Object.defineProperties(this, {
  45915. selectPlaylist: {
  45916. get() {
  45917. return this.playlistController_.selectPlaylist;
  45918. },
  45919. set(selectPlaylist) {
  45920. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  45921. }
  45922. },
  45923. throughput: {
  45924. get() {
  45925. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  45926. },
  45927. set(throughput) {
  45928. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  45929. // for the cumulative average
  45930. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  45931. }
  45932. },
  45933. bandwidth: {
  45934. get() {
  45935. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  45936. const networkInformation = window__default["default"].navigator.connection || window__default["default"].navigator.mozConnection || window__default["default"].navigator.webkitConnection;
  45937. const tenMbpsAsBitsPerSecond = 10e6;
  45938. if (this.options_.useNetworkInformationApi && networkInformation) {
  45939. // downlink returns Mbps
  45940. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  45941. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  45942. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  45943. // high quality streams are not filtered out.
  45944. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  45945. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  45946. } else {
  45947. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  45948. }
  45949. }
  45950. return playerBandwidthEst;
  45951. },
  45952. set(bandwidth) {
  45953. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  45954. // `count` is set to zero that current value of `rate` isn't included
  45955. // in the cumulative average
  45956. this.playlistController_.mainSegmentLoader_.throughput = {
  45957. rate: 0,
  45958. count: 0
  45959. };
  45960. }
  45961. },
  45962. /**
  45963. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  45964. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  45965. * the entire process after that - decryption, transmuxing, and appending - provided
  45966. * by `throughput`.
  45967. *
  45968. * Since the two process are serial, the overall system bandwidth is given by:
  45969. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  45970. */
  45971. systemBandwidth: {
  45972. get() {
  45973. const invBandwidth = 1 / (this.bandwidth || 1);
  45974. let invThroughput;
  45975. if (this.throughput > 0) {
  45976. invThroughput = 1 / this.throughput;
  45977. } else {
  45978. invThroughput = 0;
  45979. }
  45980. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  45981. return systemBitrate;
  45982. },
  45983. set() {
  45984. videojs.log.error('The "systemBandwidth" property is read-only');
  45985. }
  45986. }
  45987. });
  45988. if (this.options_.bandwidth) {
  45989. this.bandwidth = this.options_.bandwidth;
  45990. }
  45991. if (this.options_.throughput) {
  45992. this.throughput = this.options_.throughput;
  45993. }
  45994. Object.defineProperties(this.stats, {
  45995. bandwidth: {
  45996. get: () => this.bandwidth || 0,
  45997. enumerable: true
  45998. },
  45999. mediaRequests: {
  46000. get: () => this.playlistController_.mediaRequests_() || 0,
  46001. enumerable: true
  46002. },
  46003. mediaRequestsAborted: {
  46004. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  46005. enumerable: true
  46006. },
  46007. mediaRequestsTimedout: {
  46008. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  46009. enumerable: true
  46010. },
  46011. mediaRequestsErrored: {
  46012. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  46013. enumerable: true
  46014. },
  46015. mediaTransferDuration: {
  46016. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  46017. enumerable: true
  46018. },
  46019. mediaBytesTransferred: {
  46020. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  46021. enumerable: true
  46022. },
  46023. mediaSecondsLoaded: {
  46024. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  46025. enumerable: true
  46026. },
  46027. mediaAppends: {
  46028. get: () => this.playlistController_.mediaAppends_() || 0,
  46029. enumerable: true
  46030. },
  46031. mainAppendsToLoadedData: {
  46032. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  46033. enumerable: true
  46034. },
  46035. audioAppendsToLoadedData: {
  46036. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  46037. enumerable: true
  46038. },
  46039. appendsToLoadedData: {
  46040. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  46041. enumerable: true
  46042. },
  46043. timeToLoadedData: {
  46044. get: () => this.playlistController_.timeToLoadedData_() || 0,
  46045. enumerable: true
  46046. },
  46047. buffered: {
  46048. get: () => timeRangesToArray(this.tech_.buffered()),
  46049. enumerable: true
  46050. },
  46051. currentTime: {
  46052. get: () => this.tech_.currentTime(),
  46053. enumerable: true
  46054. },
  46055. currentSource: {
  46056. get: () => this.tech_.currentSource_,
  46057. enumerable: true
  46058. },
  46059. currentTech: {
  46060. get: () => this.tech_.name_,
  46061. enumerable: true
  46062. },
  46063. duration: {
  46064. get: () => this.tech_.duration(),
  46065. enumerable: true
  46066. },
  46067. main: {
  46068. get: () => this.playlists.main,
  46069. enumerable: true
  46070. },
  46071. playerDimensions: {
  46072. get: () => this.tech_.currentDimensions(),
  46073. enumerable: true
  46074. },
  46075. seekable: {
  46076. get: () => timeRangesToArray(this.tech_.seekable()),
  46077. enumerable: true
  46078. },
  46079. timestamp: {
  46080. get: () => Date.now(),
  46081. enumerable: true
  46082. },
  46083. videoPlaybackQuality: {
  46084. get: () => this.tech_.getVideoPlaybackQuality(),
  46085. enumerable: true
  46086. }
  46087. });
  46088. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  46089. this.tech_.on('bandwidthupdate', () => {
  46090. if (this.options_.useBandwidthFromLocalStorage) {
  46091. updateVhsLocalStorage({
  46092. bandwidth: this.bandwidth,
  46093. throughput: Math.round(this.throughput)
  46094. });
  46095. }
  46096. });
  46097. this.playlistController_.on('selectedinitialmedia', () => {
  46098. // Add the manual rendition mix-in to VhsHandler
  46099. renditionSelectionMixin(this);
  46100. });
  46101. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  46102. this.setupEme_();
  46103. }); // the bandwidth of the primary segment loader is our best
  46104. // estimate of overall bandwidth
  46105. this.on(this.playlistController_, 'progress', function () {
  46106. this.tech_.trigger('progress');
  46107. }); // In the live case, we need to ignore the very first `seeking` event since
  46108. // that will be the result of the seek-to-live behavior
  46109. this.on(this.playlistController_, 'firstplay', function () {
  46110. this.ignoreNextSeekingEvent_ = true;
  46111. });
  46112. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  46113. // this can occur if someone sets the src in player.ready(), for instance
  46114. if (!this.tech_.el()) {
  46115. return;
  46116. }
  46117. this.mediaSourceUrl_ = window__default["default"].URL.createObjectURL(this.playlistController_.mediaSource);
  46118. this.tech_.src(this.mediaSourceUrl_);
  46119. }
  46120. createKeySessions_() {
  46121. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46122. this.logger_('waiting for EME key session creation');
  46123. waitForKeySessionCreation({
  46124. player: this.player_,
  46125. sourceKeySystems: this.source_.keySystems,
  46126. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  46127. mainPlaylists: this.playlists.main.playlists
  46128. }).then(() => {
  46129. this.logger_('created EME key session');
  46130. this.playlistController_.sourceUpdater_.initializedEme();
  46131. }).catch(err => {
  46132. this.logger_('error while creating EME key session', err);
  46133. this.player_.error({
  46134. message: 'Failed to initialize media keys for EME',
  46135. code: 3
  46136. });
  46137. });
  46138. }
  46139. handleWaitingForKey_() {
  46140. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  46141. // the key is in the manifest. While this should've happened on initial source load, it
  46142. // may happen again in live streams where the keys change, and the manifest info
  46143. // reflects the update.
  46144. //
  46145. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  46146. // already requested keys for, we don't have to worry about this generating extraneous
  46147. // requests.
  46148. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  46149. this.createKeySessions_();
  46150. }
  46151. /**
  46152. * If necessary and EME is available, sets up EME options and waits for key session
  46153. * creation.
  46154. *
  46155. * This function also updates the source updater so taht it can be used, as for some
  46156. * browsers, EME must be configured before content is appended (if appending unencrypted
  46157. * content before encrypted content).
  46158. */
  46159. setupEme_() {
  46160. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46161. const didSetupEmeOptions = setupEmeOptions({
  46162. player: this.player_,
  46163. sourceKeySystems: this.source_.keySystems,
  46164. media: this.playlists.media(),
  46165. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  46166. });
  46167. this.player_.tech_.on('keystatuschange', e => {
  46168. if (e.status !== 'output-restricted') {
  46169. return;
  46170. }
  46171. const mainPlaylist = this.playlistController_.main();
  46172. if (!mainPlaylist || !mainPlaylist.playlists) {
  46173. return;
  46174. }
  46175. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  46176. mainPlaylist.playlists.forEach(playlist => {
  46177. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  46178. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  46179. playlist.excludeUntil = Infinity;
  46180. excludedHDPlaylists.push(playlist);
  46181. }
  46182. }
  46183. });
  46184. if (excludedHDPlaylists.length) {
  46185. videojs.log.warn('DRM keystatus changed to "output-restricted." Removing the following HD playlists ' + 'that will most likely fail to play and clearing the buffer. ' + 'This may be due to HDCP restrictions on the stream and the capabilities of the current device.', ...excludedHDPlaylists); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  46186. this.playlistController_.fastQualityChange_();
  46187. }
  46188. });
  46189. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  46190. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  46191. // promises.
  46192. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  46193. // If EME options were not set up, we've done all we could to initialize EME.
  46194. this.playlistController_.sourceUpdater_.initializedEme();
  46195. return;
  46196. }
  46197. this.createKeySessions_();
  46198. }
  46199. /**
  46200. * Initializes the quality levels and sets listeners to update them.
  46201. *
  46202. * @method setupQualityLevels_
  46203. * @private
  46204. */
  46205. setupQualityLevels_() {
  46206. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  46207. // or qualityLevels_ listeners have already been setup, do nothing.
  46208. if (!player || !player.qualityLevels || this.qualityLevels_) {
  46209. return;
  46210. }
  46211. this.qualityLevels_ = player.qualityLevels();
  46212. this.playlistController_.on('selectedinitialmedia', () => {
  46213. handleVhsLoadedMetadata(this.qualityLevels_, this);
  46214. });
  46215. this.playlists.on('mediachange', () => {
  46216. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  46217. });
  46218. }
  46219. /**
  46220. * return the version
  46221. */
  46222. static version() {
  46223. return {
  46224. '@videojs/http-streaming': version$4,
  46225. 'mux.js': version$3,
  46226. 'mpd-parser': version$2,
  46227. 'm3u8-parser': version$1,
  46228. 'aes-decrypter': version
  46229. };
  46230. }
  46231. /**
  46232. * return the version
  46233. */
  46234. version() {
  46235. return this.constructor.version();
  46236. }
  46237. canChangeType() {
  46238. return SourceUpdater.canChangeType();
  46239. }
  46240. /**
  46241. * Begin playing the video.
  46242. */
  46243. play() {
  46244. this.playlistController_.play();
  46245. }
  46246. /**
  46247. * a wrapper around the function in PlaylistController
  46248. */
  46249. setCurrentTime(currentTime) {
  46250. this.playlistController_.setCurrentTime(currentTime);
  46251. }
  46252. /**
  46253. * a wrapper around the function in PlaylistController
  46254. */
  46255. duration() {
  46256. return this.playlistController_.duration();
  46257. }
  46258. /**
  46259. * a wrapper around the function in PlaylistController
  46260. */
  46261. seekable() {
  46262. return this.playlistController_.seekable();
  46263. }
  46264. /**
  46265. * Abort all outstanding work and cleanup.
  46266. */
  46267. dispose() {
  46268. if (this.playbackWatcher_) {
  46269. this.playbackWatcher_.dispose();
  46270. }
  46271. if (this.playlistController_) {
  46272. this.playlistController_.dispose();
  46273. }
  46274. if (this.qualityLevels_) {
  46275. this.qualityLevels_.dispose();
  46276. }
  46277. if (this.tech_ && this.tech_.vhs) {
  46278. delete this.tech_.vhs;
  46279. }
  46280. if (this.mediaSourceUrl_ && window__default["default"].URL.revokeObjectURL) {
  46281. window__default["default"].URL.revokeObjectURL(this.mediaSourceUrl_);
  46282. this.mediaSourceUrl_ = null;
  46283. }
  46284. if (this.tech_) {
  46285. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  46286. }
  46287. super.dispose();
  46288. }
  46289. convertToProgramTime(time, callback) {
  46290. return getProgramTime({
  46291. playlist: this.playlistController_.media(),
  46292. time,
  46293. callback
  46294. });
  46295. } // the player must be playing before calling this
  46296. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  46297. return seekToProgramTime({
  46298. programTime,
  46299. playlist: this.playlistController_.media(),
  46300. retryCount,
  46301. pauseAfterSeek,
  46302. seekTo: this.options_.seekTo,
  46303. tech: this.options_.tech,
  46304. callback
  46305. });
  46306. }
  46307. }
  46308. /**
  46309. * The Source Handler object, which informs video.js what additional
  46310. * MIME types are supported and sets up playback. It is registered
  46311. * automatically to the appropriate tech based on the capabilities of
  46312. * the browser it is running in. It is not necessary to use or modify
  46313. * this object in normal usage.
  46314. */
  46315. const VhsSourceHandler = {
  46316. name: 'videojs-http-streaming',
  46317. VERSION: version$4,
  46318. canHandleSource(srcObj, options = {}) {
  46319. const localOptions = merge(videojs.options, options);
  46320. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  46321. },
  46322. handleSource(source, tech, options = {}) {
  46323. const localOptions = merge(videojs.options, options);
  46324. tech.vhs = new VhsHandler(source, tech, localOptions);
  46325. tech.vhs.xhr = xhrFactory();
  46326. tech.vhs.src(source.src, source.type);
  46327. return tech.vhs;
  46328. },
  46329. canPlayType(type, options) {
  46330. const simpleType = mediaTypes_js.simpleTypeFromSourceType(type);
  46331. if (!simpleType) {
  46332. return '';
  46333. }
  46334. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  46335. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  46336. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  46337. return canUseMsePlayback ? 'maybe' : '';
  46338. },
  46339. getOverrideNative(options = {}) {
  46340. const {
  46341. vhs = {}
  46342. } = options;
  46343. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  46344. const {
  46345. overrideNative = defaultOverrideNative
  46346. } = vhs;
  46347. return overrideNative;
  46348. }
  46349. };
  46350. /**
  46351. * Check to see if the native MediaSource object exists and supports
  46352. * an MP4 container with both H.264 video and AAC-LC audio.
  46353. *
  46354. * @return {boolean} if native media sources are supported
  46355. */
  46356. const supportsNativeMediaSources = () => {
  46357. return codecs_js.browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  46358. }; // register source handlers with the appropriate techs
  46359. if (supportsNativeMediaSources()) {
  46360. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  46361. }
  46362. videojs.VhsHandler = VhsHandler;
  46363. videojs.VhsSourceHandler = VhsSourceHandler;
  46364. videojs.Vhs = Vhs;
  46365. if (!videojs.use) {
  46366. videojs.registerComponent('Vhs', Vhs);
  46367. }
  46368. videojs.options.vhs = videojs.options.vhs || {};
  46369. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  46370. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  46371. }
  46372. module.exports = videojs;