video.cjs.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385
  1. /**
  2. * @license
  3. * Video.js 7.21.4 <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 _extends = require('@babel/runtime/helpers/extends');
  16. var keycode = require('keycode');
  17. var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
  18. var _inheritsLoose = require('@babel/runtime/helpers/inheritsLoose');
  19. var safeParseTuple = require('safe-json-parse/tuple');
  20. var XHR = require('@videojs/xhr');
  21. var vtt = require('videojs-vtt.js');
  22. var _construct = require('@babel/runtime/helpers/construct');
  23. var _inherits = require('@babel/runtime/helpers/inherits');
  24. var _resolveUrl = require('@videojs/vhs-utils/cjs/resolve-url.js');
  25. var m3u8Parser = require('m3u8-parser');
  26. var codecs_js = require('@videojs/vhs-utils/cjs/codecs.js');
  27. var mediaTypes_js = require('@videojs/vhs-utils/cjs/media-types.js');
  28. var byteHelpers = require('@videojs/vhs-utils/cjs/byte-helpers');
  29. var mpdParser = require('mpd-parser');
  30. var parseSidx = require('mux.js/lib/tools/parse-sidx');
  31. var id3Helpers = require('@videojs/vhs-utils/cjs/id3-helpers');
  32. var containers = require('@videojs/vhs-utils/cjs/containers');
  33. var clock = require('mux.js/lib/utils/clock');
  34. var _wrapNativeSuper = require('@babel/runtime/helpers/wrapNativeSuper');
  35. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  36. var window__default = /*#__PURE__*/_interopDefaultLegacy(window$1);
  37. var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
  38. var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);
  39. var keycode__default = /*#__PURE__*/_interopDefaultLegacy(keycode);
  40. var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
  41. var _inheritsLoose__default = /*#__PURE__*/_interopDefaultLegacy(_inheritsLoose);
  42. var safeParseTuple__default = /*#__PURE__*/_interopDefaultLegacy(safeParseTuple);
  43. var XHR__default = /*#__PURE__*/_interopDefaultLegacy(XHR);
  44. var vtt__default = /*#__PURE__*/_interopDefaultLegacy(vtt);
  45. var _construct__default = /*#__PURE__*/_interopDefaultLegacy(_construct);
  46. var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
  47. var _resolveUrl__default = /*#__PURE__*/_interopDefaultLegacy(_resolveUrl);
  48. var parseSidx__default = /*#__PURE__*/_interopDefaultLegacy(parseSidx);
  49. var _wrapNativeSuper__default = /*#__PURE__*/_interopDefaultLegacy(_wrapNativeSuper);
  50. var version$5 = "7.21.4";
  51. /**
  52. * An Object that contains lifecycle hooks as keys which point to an array
  53. * of functions that are run when a lifecycle is triggered
  54. *
  55. * @private
  56. */
  57. var hooks_ = {};
  58. /**
  59. * Get a list of hooks for a specific lifecycle
  60. *
  61. * @param {string} type
  62. * the lifecyle to get hooks from
  63. *
  64. * @param {Function|Function[]} [fn]
  65. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  66. *
  67. * @return {Array}
  68. * an array of hooks, or an empty array if there are none.
  69. */
  70. var hooks = function hooks(type, fn) {
  71. hooks_[type] = hooks_[type] || [];
  72. if (fn) {
  73. hooks_[type] = hooks_[type].concat(fn);
  74. }
  75. return hooks_[type];
  76. };
  77. /**
  78. * Add a function hook to a specific videojs lifecycle.
  79. *
  80. * @param {string} type
  81. * the lifecycle to hook the function to.
  82. *
  83. * @param {Function|Function[]}
  84. * The function or array of functions to attach.
  85. */
  86. var hook = function hook(type, fn) {
  87. hooks(type, fn);
  88. };
  89. /**
  90. * Remove a hook from a specific videojs lifecycle.
  91. *
  92. * @param {string} type
  93. * the lifecycle that the function hooked to
  94. *
  95. * @param {Function} fn
  96. * The hooked function to remove
  97. *
  98. * @return {boolean}
  99. * The function that was removed or undef
  100. */
  101. var removeHook = function removeHook(type, fn) {
  102. var index = hooks(type).indexOf(fn);
  103. if (index <= -1) {
  104. return false;
  105. }
  106. hooks_[type] = hooks_[type].slice();
  107. hooks_[type].splice(index, 1);
  108. return true;
  109. };
  110. /**
  111. * Add a function hook that will only run once to a specific videojs lifecycle.
  112. *
  113. * @param {string} type
  114. * the lifecycle to hook the function to.
  115. *
  116. * @param {Function|Function[]}
  117. * The function or array of functions to attach.
  118. */
  119. var hookOnce = function hookOnce(type, fn) {
  120. hooks(type, [].concat(fn).map(function (original) {
  121. var wrapper = function wrapper() {
  122. removeHook(type, wrapper);
  123. return original.apply(void 0, arguments);
  124. };
  125. return wrapper;
  126. }));
  127. };
  128. /**
  129. * @file fullscreen-api.js
  130. * @module fullscreen-api
  131. * @private
  132. */
  133. /**
  134. * Store the browser-specific methods for the fullscreen API.
  135. *
  136. * @type {Object}
  137. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  138. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  139. */
  140. var FullscreenApi = {
  141. prefixed: true
  142. }; // browser API methods
  143. var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'], // WebKit
  144. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'], // Mozilla
  145. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'], // Microsoft
  146. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  147. var specApi = apiMap[0];
  148. var browserApi; // determine the supported set of functions
  149. for (var i = 0; i < apiMap.length; i++) {
  150. // check for exitFullscreen function
  151. if (apiMap[i][1] in document__default['default']) {
  152. browserApi = apiMap[i];
  153. break;
  154. }
  155. } // map the browser API names to the spec API names
  156. if (browserApi) {
  157. for (var _i = 0; _i < browserApi.length; _i++) {
  158. FullscreenApi[specApi[_i]] = browserApi[_i];
  159. }
  160. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  161. }
  162. /**
  163. * @file create-logger.js
  164. * @module create-logger
  165. */
  166. var history = [];
  167. /**
  168. * Log messages to the console and history based on the type of message
  169. *
  170. * @private
  171. * @param {string} type
  172. * The name of the console method to use.
  173. *
  174. * @param {Array} args
  175. * The arguments to be passed to the matching console method.
  176. */
  177. var LogByTypeFactory = function LogByTypeFactory(name, log) {
  178. return function (type, level, args) {
  179. var lvl = log.levels[level];
  180. var lvlRegExp = new RegExp("^(" + lvl + ")$");
  181. if (type !== 'log') {
  182. // Add the type to the front of the message when it's not "log".
  183. args.unshift(type.toUpperCase() + ':');
  184. } // Add console prefix after adding to history.
  185. args.unshift(name + ':'); // Add a clone of the args at this point to history.
  186. if (history) {
  187. history.push([].concat(args)); // only store 1000 history entries
  188. var splice = history.length - 1000;
  189. history.splice(0, splice > 0 ? splice : 0);
  190. } // If there's no console then don't try to output messages, but they will
  191. // still be stored in history.
  192. if (!window__default['default'].console) {
  193. return;
  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. var 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. } // Bail out if there's no console or if this type is not allowed by the
  203. // current logging level.
  204. if (!fn || !lvl || !lvlRegExp.test(type)) {
  205. return;
  206. }
  207. fn[Array.isArray(args) ? 'apply' : 'call'](window__default['default'].console, args);
  208. };
  209. };
  210. function createLogger$1(name) {
  211. // This is the private tracking variable for logging level.
  212. var level = 'info'; // the curried logByType bound to the specific log and history
  213. var logByType;
  214. /**
  215. * Logs plain debug messages. Similar to `console.log`.
  216. *
  217. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  218. * of our JSDoc template, we cannot properly document this as both a function
  219. * and a namespace, so its function signature is documented here.
  220. *
  221. * #### Arguments
  222. * ##### *args
  223. * Mixed[]
  224. *
  225. * Any combination of values that could be passed to `console.log()`.
  226. *
  227. * #### Return Value
  228. *
  229. * `undefined`
  230. *
  231. * @namespace
  232. * @param {Mixed[]} args
  233. * One or more messages or objects that should be logged.
  234. */
  235. var log = function log() {
  236. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  237. args[_key] = arguments[_key];
  238. }
  239. logByType('log', level, args);
  240. }; // This is the logByType helper that the logging methods below use
  241. logByType = LogByTypeFactory(name, log);
  242. /**
  243. * Create a new sublogger which chains the old name to the new name.
  244. *
  245. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  246. * ```js
  247. * mylogger('foo');
  248. * // > VIDEOJS: player: foo
  249. * ```
  250. *
  251. * @param {string} name
  252. * The name to add call the new logger
  253. * @return {Object}
  254. */
  255. log.createLogger = function (subname) {
  256. return createLogger$1(name + ': ' + subname);
  257. };
  258. /**
  259. * Enumeration of available logging levels, where the keys are the level names
  260. * and the values are `|`-separated strings containing logging methods allowed
  261. * in that logging level. These strings are used to create a regular expression
  262. * matching the function name being called.
  263. *
  264. * Levels provided by Video.js are:
  265. *
  266. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  267. * this effect. The most restrictive.
  268. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  269. * `log.warn`, and `log.error`).
  270. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  271. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  272. * - `warn`: Matches `log.warn` and `log.error` calls.
  273. * - `error`: Matches only `log.error` calls.
  274. *
  275. * @type {Object}
  276. */
  277. log.levels = {
  278. all: 'debug|log|warn|error',
  279. off: '',
  280. debug: 'debug|log|warn|error',
  281. info: 'log|warn|error',
  282. warn: 'warn|error',
  283. error: 'error',
  284. DEFAULT: level
  285. };
  286. /**
  287. * Get or set the current logging level.
  288. *
  289. * If a string matching a key from {@link module:log.levels} is provided, acts
  290. * as a setter.
  291. *
  292. * @param {string} [lvl]
  293. * Pass a valid level to set a new logging level.
  294. *
  295. * @return {string}
  296. * The current logging level.
  297. */
  298. log.level = function (lvl) {
  299. if (typeof lvl === 'string') {
  300. if (!log.levels.hasOwnProperty(lvl)) {
  301. throw new Error("\"" + lvl + "\" in not a valid log level");
  302. }
  303. level = lvl;
  304. }
  305. return level;
  306. };
  307. /**
  308. * Returns an array containing everything that has been logged to the history.
  309. *
  310. * This array is a shallow clone of the internal history record. However, its
  311. * contents are _not_ cloned; so, mutating objects inside this array will
  312. * mutate them in history.
  313. *
  314. * @return {Array}
  315. */
  316. log.history = function () {
  317. return history ? [].concat(history) : [];
  318. };
  319. /**
  320. * Allows you to filter the history by the given logger name
  321. *
  322. * @param {string} fname
  323. * The name to filter by
  324. *
  325. * @return {Array}
  326. * The filtered list to return
  327. */
  328. log.history.filter = function (fname) {
  329. return (history || []).filter(function (historyItem) {
  330. // if the first item in each historyItem includes `fname`, then it's a match
  331. return new RegExp(".*" + fname + ".*").test(historyItem[0]);
  332. });
  333. };
  334. /**
  335. * Clears the internal history tracking, but does not prevent further history
  336. * tracking.
  337. */
  338. log.history.clear = function () {
  339. if (history) {
  340. history.length = 0;
  341. }
  342. };
  343. /**
  344. * Disable history tracking if it is currently enabled.
  345. */
  346. log.history.disable = function () {
  347. if (history !== null) {
  348. history.length = 0;
  349. history = null;
  350. }
  351. };
  352. /**
  353. * Enable history tracking if it is currently disabled.
  354. */
  355. log.history.enable = function () {
  356. if (history === null) {
  357. history = [];
  358. }
  359. };
  360. /**
  361. * Logs error messages. Similar to `console.error`.
  362. *
  363. * @param {Mixed[]} args
  364. * One or more messages or objects that should be logged as an error
  365. */
  366. log.error = function () {
  367. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  368. args[_key2] = arguments[_key2];
  369. }
  370. return logByType('error', level, args);
  371. };
  372. /**
  373. * Logs warning messages. Similar to `console.warn`.
  374. *
  375. * @param {Mixed[]} args
  376. * One or more messages or objects that should be logged as a warning.
  377. */
  378. log.warn = function () {
  379. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  380. args[_key3] = arguments[_key3];
  381. }
  382. return logByType('warn', level, args);
  383. };
  384. /**
  385. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  386. * log if `console.debug` is not available
  387. *
  388. * @param {Mixed[]} args
  389. * One or more messages or objects that should be logged as debug.
  390. */
  391. log.debug = function () {
  392. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  393. args[_key4] = arguments[_key4];
  394. }
  395. return logByType('debug', level, args);
  396. };
  397. return log;
  398. }
  399. /**
  400. * @file log.js
  401. * @module log
  402. */
  403. var log$1 = createLogger$1('VIDEOJS');
  404. var createLogger = log$1.createLogger;
  405. /**
  406. * @file obj.js
  407. * @module obj
  408. */
  409. /**
  410. * @callback obj:EachCallback
  411. *
  412. * @param {Mixed} value
  413. * The current key for the object that is being iterated over.
  414. *
  415. * @param {string} key
  416. * The current key-value for object that is being iterated over
  417. */
  418. /**
  419. * @callback obj:ReduceCallback
  420. *
  421. * @param {Mixed} accum
  422. * The value that is accumulating over the reduce loop.
  423. *
  424. * @param {Mixed} value
  425. * The current key for the object that is being iterated over.
  426. *
  427. * @param {string} key
  428. * The current key-value for object that is being iterated over
  429. *
  430. * @return {Mixed}
  431. * The new accumulated value.
  432. */
  433. var toString = Object.prototype.toString;
  434. /**
  435. * Get the keys of an Object
  436. *
  437. * @param {Object}
  438. * The Object to get the keys from
  439. *
  440. * @return {string[]}
  441. * An array of the keys from the object. Returns an empty array if the
  442. * object passed in was invalid or had no keys.
  443. *
  444. * @private
  445. */
  446. var keys = function keys(object) {
  447. return isObject(object) ? Object.keys(object) : [];
  448. };
  449. /**
  450. * Array-like iteration for objects.
  451. *
  452. * @param {Object} object
  453. * The object to iterate over
  454. *
  455. * @param {obj:EachCallback} fn
  456. * The callback function which is called for each key in the object.
  457. */
  458. function each(object, fn) {
  459. keys(object).forEach(function (key) {
  460. return fn(object[key], key);
  461. });
  462. }
  463. /**
  464. * Array-like reduce for objects.
  465. *
  466. * @param {Object} object
  467. * The Object that you want to reduce.
  468. *
  469. * @param {Function} fn
  470. * A callback function which is called for each key in the object. It
  471. * receives the accumulated value and the per-iteration value and key
  472. * as arguments.
  473. *
  474. * @param {Mixed} [initial = 0]
  475. * Starting value
  476. *
  477. * @return {Mixed}
  478. * The final accumulated value.
  479. */
  480. function reduce(object, fn, initial) {
  481. if (initial === void 0) {
  482. initial = 0;
  483. }
  484. return keys(object).reduce(function (accum, key) {
  485. return fn(accum, object[key], key);
  486. }, initial);
  487. }
  488. /**
  489. * Object.assign-style object shallow merge/extend.
  490. *
  491. * @param {Object} target
  492. * @param {Object} ...sources
  493. * @return {Object}
  494. */
  495. function assign(target) {
  496. for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  497. sources[_key - 1] = arguments[_key];
  498. }
  499. if (Object.assign) {
  500. return _extends__default['default'].apply(void 0, [target].concat(sources));
  501. }
  502. sources.forEach(function (source) {
  503. if (!source) {
  504. return;
  505. }
  506. each(source, function (value, key) {
  507. target[key] = value;
  508. });
  509. });
  510. return target;
  511. }
  512. /**
  513. * Returns whether a value is an object of any kind - including DOM nodes,
  514. * arrays, regular expressions, etc. Not functions, though.
  515. *
  516. * This avoids the gotcha where using `typeof` on a `null` value
  517. * results in `'object'`.
  518. *
  519. * @param {Object} value
  520. * @return {boolean}
  521. */
  522. function isObject(value) {
  523. return !!value && typeof value === 'object';
  524. }
  525. /**
  526. * Returns whether an object appears to be a "plain" object - that is, a
  527. * direct instance of `Object`.
  528. *
  529. * @param {Object} value
  530. * @return {boolean}
  531. */
  532. function isPlain(value) {
  533. return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object;
  534. }
  535. /**
  536. * @file computed-style.js
  537. * @module computed-style
  538. */
  539. /**
  540. * A safe getComputedStyle.
  541. *
  542. * This is needed because in Firefox, if the player is loaded in an iframe with
  543. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  544. * null-check to make sure that the player doesn't break in these cases.
  545. *
  546. * @function
  547. * @param {Element} el
  548. * The element you want the computed style of
  549. *
  550. * @param {string} prop
  551. * The property name you want
  552. *
  553. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  554. */
  555. function computedStyle(el, prop) {
  556. if (!el || !prop) {
  557. return '';
  558. }
  559. if (typeof window__default['default'].getComputedStyle === 'function') {
  560. var computedStyleValue;
  561. try {
  562. computedStyleValue = window__default['default'].getComputedStyle(el);
  563. } catch (e) {
  564. return '';
  565. }
  566. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  567. }
  568. return '';
  569. }
  570. /**
  571. * @file browser.js
  572. * @module browser
  573. */
  574. var USER_AGENT = window__default['default'].navigator && window__default['default'].navigator.userAgent || '';
  575. var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
  576. var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
  577. /**
  578. * Whether or not this device is an iPod.
  579. *
  580. * @static
  581. * @const
  582. * @type {Boolean}
  583. */
  584. var IS_IPOD = /iPod/i.test(USER_AGENT);
  585. /**
  586. * The detected iOS version - or `null`.
  587. *
  588. * @static
  589. * @const
  590. * @type {string|null}
  591. */
  592. var IOS_VERSION = function () {
  593. var match = USER_AGENT.match(/OS (\d+)_/i);
  594. if (match && match[1]) {
  595. return match[1];
  596. }
  597. return null;
  598. }();
  599. /**
  600. * Whether or not this is an Android device.
  601. *
  602. * @static
  603. * @const
  604. * @type {Boolean}
  605. */
  606. var IS_ANDROID = /Android/i.test(USER_AGENT);
  607. /**
  608. * The detected Android version - or `null`.
  609. *
  610. * @static
  611. * @const
  612. * @type {number|string|null}
  613. */
  614. var ANDROID_VERSION = function () {
  615. // This matches Android Major.Minor.Patch versions
  616. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  617. var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  618. if (!match) {
  619. return null;
  620. }
  621. var major = match[1] && parseFloat(match[1]);
  622. var minor = match[2] && parseFloat(match[2]);
  623. if (major && minor) {
  624. return parseFloat(match[1] + '.' + match[2]);
  625. } else if (major) {
  626. return major;
  627. }
  628. return null;
  629. }();
  630. /**
  631. * Whether or not this is a native Android browser.
  632. *
  633. * @static
  634. * @const
  635. * @type {Boolean}
  636. */
  637. var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
  638. /**
  639. * Whether or not this is Mozilla Firefox.
  640. *
  641. * @static
  642. * @const
  643. * @type {Boolean}
  644. */
  645. var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  646. /**
  647. * Whether or not this is Microsoft Edge.
  648. *
  649. * @static
  650. * @const
  651. * @type {Boolean}
  652. */
  653. var IS_EDGE = /Edg/i.test(USER_AGENT);
  654. /**
  655. * Whether or not this is Google Chrome.
  656. *
  657. * This will also be `true` for Chrome on iOS, which will have different support
  658. * as it is actually Safari under the hood.
  659. *
  660. * @static
  661. * @const
  662. * @type {Boolean}
  663. */
  664. var IS_CHROME = !IS_EDGE && (/Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT));
  665. /**
  666. * The detected Google Chrome version - or `null`.
  667. *
  668. * @static
  669. * @const
  670. * @type {number|null}
  671. */
  672. var CHROME_VERSION = function () {
  673. var match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  674. if (match && match[2]) {
  675. return parseFloat(match[2]);
  676. }
  677. return null;
  678. }();
  679. /**
  680. * The detected Internet Explorer version - or `null`.
  681. *
  682. * @static
  683. * @const
  684. * @type {number|null}
  685. */
  686. var IE_VERSION = function () {
  687. var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  688. var version = result && parseFloat(result[1]);
  689. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  690. // IE 11 has a different user agent string than other IE versions
  691. version = 11.0;
  692. }
  693. return version;
  694. }();
  695. /**
  696. * Whether or not this is desktop Safari.
  697. *
  698. * @static
  699. * @const
  700. * @type {Boolean}
  701. */
  702. var IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  703. /**
  704. * Whether or not this is a Windows machine.
  705. *
  706. * @static
  707. * @const
  708. * @type {Boolean}
  709. */
  710. var IS_WINDOWS = /Windows/i.test(USER_AGENT);
  711. /**
  712. * Whether or not this device is touch-enabled.
  713. *
  714. * @static
  715. * @const
  716. * @type {Boolean}
  717. */
  718. var 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));
  719. /**
  720. * Whether or not this device is an iPad.
  721. *
  722. * @static
  723. * @const
  724. * @type {Boolean}
  725. */
  726. var IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  727. /**
  728. * Whether or not this device is an iPhone.
  729. *
  730. * @static
  731. * @const
  732. * @type {Boolean}
  733. */
  734. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  735. // to identify iPhones, we need to exclude iPads.
  736. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  737. var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  738. /**
  739. * Whether or not this is an iOS device.
  740. *
  741. * @static
  742. * @const
  743. * @type {Boolean}
  744. */
  745. var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  746. /**
  747. * Whether or not this is any flavor of Safari - including iOS.
  748. *
  749. * @static
  750. * @const
  751. * @type {Boolean}
  752. */
  753. var IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  754. var browser = /*#__PURE__*/Object.freeze({
  755. __proto__: null,
  756. IS_IPOD: IS_IPOD,
  757. IOS_VERSION: IOS_VERSION,
  758. IS_ANDROID: IS_ANDROID,
  759. ANDROID_VERSION: ANDROID_VERSION,
  760. IS_NATIVE_ANDROID: IS_NATIVE_ANDROID,
  761. IS_FIREFOX: IS_FIREFOX,
  762. IS_EDGE: IS_EDGE,
  763. IS_CHROME: IS_CHROME,
  764. CHROME_VERSION: CHROME_VERSION,
  765. IE_VERSION: IE_VERSION,
  766. IS_SAFARI: IS_SAFARI,
  767. IS_WINDOWS: IS_WINDOWS,
  768. TOUCH_ENABLED: TOUCH_ENABLED,
  769. IS_IPAD: IS_IPAD,
  770. IS_IPHONE: IS_IPHONE,
  771. IS_IOS: IS_IOS,
  772. IS_ANY_SAFARI: IS_ANY_SAFARI
  773. });
  774. /**
  775. * @file dom.js
  776. * @module dom
  777. */
  778. /**
  779. * Detect if a value is a string with any non-whitespace characters.
  780. *
  781. * @private
  782. * @param {string} str
  783. * The string to check
  784. *
  785. * @return {boolean}
  786. * Will be `true` if the string is non-blank, `false` otherwise.
  787. *
  788. */
  789. function isNonBlankString(str) {
  790. // we use str.trim as it will trim any whitespace characters
  791. // from the front or back of non-whitespace characters. aka
  792. // Any string that contains non-whitespace characters will
  793. // still contain them after `trim` but whitespace only strings
  794. // will have a length of 0, failing this check.
  795. return typeof str === 'string' && Boolean(str.trim());
  796. }
  797. /**
  798. * Throws an error if the passed string has whitespace. This is used by
  799. * class methods to be relatively consistent with the classList API.
  800. *
  801. * @private
  802. * @param {string} str
  803. * The string to check for whitespace.
  804. *
  805. * @throws {Error}
  806. * Throws an error if there is whitespace in the string.
  807. */
  808. function throwIfWhitespace(str) {
  809. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  810. if (str.indexOf(' ') >= 0) {
  811. throw new Error('class has illegal whitespace characters');
  812. }
  813. }
  814. /**
  815. * Produce a regular expression for matching a className within an elements className.
  816. *
  817. * @private
  818. * @param {string} className
  819. * The className to generate the RegExp for.
  820. *
  821. * @return {RegExp}
  822. * The RegExp that will check for a specific `className` in an elements
  823. * className.
  824. */
  825. function classRegExp(className) {
  826. return new RegExp('(^|\\s)' + className + '($|\\s)');
  827. }
  828. /**
  829. * Whether the current DOM interface appears to be real (i.e. not simulated).
  830. *
  831. * @return {boolean}
  832. * Will be `true` if the DOM appears to be real, `false` otherwise.
  833. */
  834. function isReal() {
  835. // Both document and window will never be undefined thanks to `global`.
  836. return document__default['default'] === window__default['default'].document;
  837. }
  838. /**
  839. * Determines, via duck typing, whether or not a value is a DOM element.
  840. *
  841. * @param {Mixed} value
  842. * The value to check.
  843. *
  844. * @return {boolean}
  845. * Will be `true` if the value is a DOM element, `false` otherwise.
  846. */
  847. function isEl(value) {
  848. return isObject(value) && value.nodeType === 1;
  849. }
  850. /**
  851. * Determines if the current DOM is embedded in an iframe.
  852. *
  853. * @return {boolean}
  854. * Will be `true` if the DOM is embedded in an iframe, `false`
  855. * otherwise.
  856. */
  857. function isInFrame() {
  858. // We need a try/catch here because Safari will throw errors when attempting
  859. // to get either `parent` or `self`
  860. try {
  861. return window__default['default'].parent !== window__default['default'].self;
  862. } catch (x) {
  863. return true;
  864. }
  865. }
  866. /**
  867. * Creates functions to query the DOM using a given method.
  868. *
  869. * @private
  870. * @param {string} method
  871. * The method to create the query with.
  872. *
  873. * @return {Function}
  874. * The query method
  875. */
  876. function createQuerier(method) {
  877. return function (selector, context) {
  878. if (!isNonBlankString(selector)) {
  879. return document__default['default'][method](null);
  880. }
  881. if (isNonBlankString(context)) {
  882. context = document__default['default'].querySelector(context);
  883. }
  884. var ctx = isEl(context) ? context : document__default['default'];
  885. return ctx[method] && ctx[method](selector);
  886. };
  887. }
  888. /**
  889. * Creates an element and applies properties, attributes, and inserts content.
  890. *
  891. * @param {string} [tagName='div']
  892. * Name of tag to be created.
  893. *
  894. * @param {Object} [properties={}]
  895. * Element properties to be applied.
  896. *
  897. * @param {Object} [attributes={}]
  898. * Element attributes to be applied.
  899. *
  900. * @param {module:dom~ContentDescriptor} content
  901. * A content descriptor object.
  902. *
  903. * @return {Element}
  904. * The element that was created.
  905. */
  906. function createEl(tagName, properties, attributes, content) {
  907. if (tagName === void 0) {
  908. tagName = 'div';
  909. }
  910. if (properties === void 0) {
  911. properties = {};
  912. }
  913. if (attributes === void 0) {
  914. attributes = {};
  915. }
  916. var el = document__default['default'].createElement(tagName);
  917. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  918. var val = properties[propName]; // See #2176
  919. // We originally were accepting both properties and attributes in the
  920. // same object, but that doesn't work so well.
  921. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
  922. log$1.warn('Setting attributes in the second argument of createEl()\n' + 'has been deprecated. Use the third argument instead.\n' + ("createEl(type, properties, attributes). Attempting to set " + propName + " to " + val + "."));
  923. el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a
  924. // method for it.
  925. } else if (propName === 'textContent') {
  926. textContent(el, val);
  927. } else if (el[propName] !== val || propName === 'tabIndex') {
  928. el[propName] = val;
  929. }
  930. });
  931. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  932. el.setAttribute(attrName, attributes[attrName]);
  933. });
  934. if (content) {
  935. appendContent(el, content);
  936. }
  937. return el;
  938. }
  939. /**
  940. * Injects text into an element, replacing any existing contents entirely.
  941. *
  942. * @param {Element} el
  943. * The element to add text content into
  944. *
  945. * @param {string} text
  946. * The text content to add.
  947. *
  948. * @return {Element}
  949. * The element with added text content.
  950. */
  951. function textContent(el, text) {
  952. if (typeof el.textContent === 'undefined') {
  953. el.innerText = text;
  954. } else {
  955. el.textContent = text;
  956. }
  957. return el;
  958. }
  959. /**
  960. * Insert an element as the first child node of another
  961. *
  962. * @param {Element} child
  963. * Element to insert
  964. *
  965. * @param {Element} parent
  966. * Element to insert child into
  967. */
  968. function prependTo(child, parent) {
  969. if (parent.firstChild) {
  970. parent.insertBefore(child, parent.firstChild);
  971. } else {
  972. parent.appendChild(child);
  973. }
  974. }
  975. /**
  976. * Check if an element has a class name.
  977. *
  978. * @param {Element} element
  979. * Element to check
  980. *
  981. * @param {string} classToCheck
  982. * Class name to check for
  983. *
  984. * @return {boolean}
  985. * Will be `true` if the element has a class, `false` otherwise.
  986. *
  987. * @throws {Error}
  988. * Throws an error if `classToCheck` has white space.
  989. */
  990. function hasClass(element, classToCheck) {
  991. throwIfWhitespace(classToCheck);
  992. if (element.classList) {
  993. return element.classList.contains(classToCheck);
  994. }
  995. return classRegExp(classToCheck).test(element.className);
  996. }
  997. /**
  998. * Add a class name to an element.
  999. *
  1000. * @param {Element} element
  1001. * Element to add class name to.
  1002. *
  1003. * @param {string} classToAdd
  1004. * Class name to add.
  1005. *
  1006. * @return {Element}
  1007. * The DOM element with the added class name.
  1008. */
  1009. function addClass(element, classToAdd) {
  1010. if (element.classList) {
  1011. element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it
  1012. // in the case of classList not being supported.
  1013. } else if (!hasClass(element, classToAdd)) {
  1014. element.className = (element.className + ' ' + classToAdd).trim();
  1015. }
  1016. return element;
  1017. }
  1018. /**
  1019. * Remove a class name from an element.
  1020. *
  1021. * @param {Element} element
  1022. * Element to remove a class name from.
  1023. *
  1024. * @param {string} classToRemove
  1025. * Class name to remove
  1026. *
  1027. * @return {Element}
  1028. * The DOM element with class name removed.
  1029. */
  1030. function removeClass(element, classToRemove) {
  1031. // Protect in case the player gets disposed
  1032. if (!element) {
  1033. log$1.warn("removeClass was called with an element that doesn't exist");
  1034. return null;
  1035. }
  1036. if (element.classList) {
  1037. element.classList.remove(classToRemove);
  1038. } else {
  1039. throwIfWhitespace(classToRemove);
  1040. element.className = element.className.split(/\s+/).filter(function (c) {
  1041. return c !== classToRemove;
  1042. }).join(' ');
  1043. }
  1044. return element;
  1045. }
  1046. /**
  1047. * The callback definition for toggleClass.
  1048. *
  1049. * @callback module:dom~PredicateCallback
  1050. * @param {Element} element
  1051. * The DOM element of the Component.
  1052. *
  1053. * @param {string} classToToggle
  1054. * The `className` that wants to be toggled
  1055. *
  1056. * @return {boolean|undefined}
  1057. * If `true` is returned, the `classToToggle` will be added to the
  1058. * `element`. If `false`, the `classToToggle` will be removed from
  1059. * the `element`. If `undefined`, the callback will be ignored.
  1060. */
  1061. /**
  1062. * Adds or removes a class name to/from an element depending on an optional
  1063. * condition or the presence/absence of the class name.
  1064. *
  1065. * @param {Element} element
  1066. * The element to toggle a class name on.
  1067. *
  1068. * @param {string} classToToggle
  1069. * The class that should be toggled.
  1070. *
  1071. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1072. * See the return value for {@link module:dom~PredicateCallback}
  1073. *
  1074. * @return {Element}
  1075. * The element with a class that has been toggled.
  1076. */
  1077. function toggleClass(element, classToToggle, predicate) {
  1078. // This CANNOT use `classList` internally because IE11 does not support the
  1079. // second parameter to the `classList.toggle()` method! Which is fine because
  1080. // `classList` will be used by the add/remove functions.
  1081. var has = hasClass(element, classToToggle);
  1082. if (typeof predicate === 'function') {
  1083. predicate = predicate(element, classToToggle);
  1084. }
  1085. if (typeof predicate !== 'boolean') {
  1086. predicate = !has;
  1087. } // If the necessary class operation matches the current state of the
  1088. // element, no action is required.
  1089. if (predicate === has) {
  1090. return;
  1091. }
  1092. if (predicate) {
  1093. addClass(element, classToToggle);
  1094. } else {
  1095. removeClass(element, classToToggle);
  1096. }
  1097. return element;
  1098. }
  1099. /**
  1100. * Apply attributes to an HTML element.
  1101. *
  1102. * @param {Element} el
  1103. * Element to add attributes to.
  1104. *
  1105. * @param {Object} [attributes]
  1106. * Attributes to be applied.
  1107. */
  1108. function setAttributes(el, attributes) {
  1109. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1110. var attrValue = attributes[attrName];
  1111. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1112. el.removeAttribute(attrName);
  1113. } else {
  1114. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1115. }
  1116. });
  1117. }
  1118. /**
  1119. * Get an element's attribute values, as defined on the HTML tag.
  1120. *
  1121. * Attributes are not the same as properties. They're defined on the tag
  1122. * or with setAttribute.
  1123. *
  1124. * @param {Element} tag
  1125. * Element from which to get tag attributes.
  1126. *
  1127. * @return {Object}
  1128. * All attributes of the element. Boolean attributes will be `true` or
  1129. * `false`, others will be strings.
  1130. */
  1131. function getAttributes(tag) {
  1132. var obj = {}; // known boolean attributes
  1133. // we can check for matching boolean properties, but not all browsers
  1134. // and not all tags know about these attributes, so, we still want to check them manually
  1135. var knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1136. if (tag && tag.attributes && tag.attributes.length > 0) {
  1137. var attrs = tag.attributes;
  1138. for (var i = attrs.length - 1; i >= 0; i--) {
  1139. var attrName = attrs[i].name;
  1140. var attrVal = attrs[i].value; // check for known booleans
  1141. // the matching element property will return a value for typeof
  1142. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1143. // the value of an included boolean attribute is typically an empty
  1144. // string ('') which would equal false if we just check for a false value.
  1145. // we also don't want support bad code like autoplay='false'
  1146. attrVal = attrVal !== null ? true : false;
  1147. }
  1148. obj[attrName] = attrVal;
  1149. }
  1150. }
  1151. return obj;
  1152. }
  1153. /**
  1154. * Get the value of an element's attribute.
  1155. *
  1156. * @param {Element} el
  1157. * A DOM element.
  1158. *
  1159. * @param {string} attribute
  1160. * Attribute to get the value of.
  1161. *
  1162. * @return {string}
  1163. * The value of the attribute.
  1164. */
  1165. function getAttribute(el, attribute) {
  1166. return el.getAttribute(attribute);
  1167. }
  1168. /**
  1169. * Set the value of an element's attribute.
  1170. *
  1171. * @param {Element} el
  1172. * A DOM element.
  1173. *
  1174. * @param {string} attribute
  1175. * Attribute to set.
  1176. *
  1177. * @param {string} value
  1178. * Value to set the attribute to.
  1179. */
  1180. function setAttribute(el, attribute, value) {
  1181. el.setAttribute(attribute, value);
  1182. }
  1183. /**
  1184. * Remove an element's attribute.
  1185. *
  1186. * @param {Element} el
  1187. * A DOM element.
  1188. *
  1189. * @param {string} attribute
  1190. * Attribute to remove.
  1191. */
  1192. function removeAttribute(el, attribute) {
  1193. el.removeAttribute(attribute);
  1194. }
  1195. /**
  1196. * Attempt to block the ability to select text.
  1197. */
  1198. function blockTextSelection() {
  1199. document__default['default'].body.focus();
  1200. document__default['default'].onselectstart = function () {
  1201. return false;
  1202. };
  1203. }
  1204. /**
  1205. * Turn off text selection blocking.
  1206. */
  1207. function unblockTextSelection() {
  1208. document__default['default'].onselectstart = function () {
  1209. return true;
  1210. };
  1211. }
  1212. /**
  1213. * Identical to the native `getBoundingClientRect` function, but ensures that
  1214. * the method is supported at all (it is in all browsers we claim to support)
  1215. * and that the element is in the DOM before continuing.
  1216. *
  1217. * This wrapper function also shims properties which are not provided by some
  1218. * older browsers (namely, IE8).
  1219. *
  1220. * Additionally, some browsers do not support adding properties to a
  1221. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1222. * properties (except `x` and `y` which are not widely supported). This helps
  1223. * avoid implementations where keys are non-enumerable.
  1224. *
  1225. * @param {Element} el
  1226. * Element whose `ClientRect` we want to calculate.
  1227. *
  1228. * @return {Object|undefined}
  1229. * Always returns a plain object - or `undefined` if it cannot.
  1230. */
  1231. function getBoundingClientRect(el) {
  1232. if (el && el.getBoundingClientRect && el.parentNode) {
  1233. var rect = el.getBoundingClientRect();
  1234. var result = {};
  1235. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(function (k) {
  1236. if (rect[k] !== undefined) {
  1237. result[k] = rect[k];
  1238. }
  1239. });
  1240. if (!result.height) {
  1241. result.height = parseFloat(computedStyle(el, 'height'));
  1242. }
  1243. if (!result.width) {
  1244. result.width = parseFloat(computedStyle(el, 'width'));
  1245. }
  1246. return result;
  1247. }
  1248. }
  1249. /**
  1250. * Represents the position of a DOM element on the page.
  1251. *
  1252. * @typedef {Object} module:dom~Position
  1253. *
  1254. * @property {number} left
  1255. * Pixels to the left.
  1256. *
  1257. * @property {number} top
  1258. * Pixels from the top.
  1259. */
  1260. /**
  1261. * Get the position of an element in the DOM.
  1262. *
  1263. * Uses `getBoundingClientRect` technique from John Resig.
  1264. *
  1265. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1266. *
  1267. * @param {Element} el
  1268. * Element from which to get offset.
  1269. *
  1270. * @return {module:dom~Position}
  1271. * The position of the element that was passed in.
  1272. */
  1273. function findPosition(el) {
  1274. if (!el || el && !el.offsetParent) {
  1275. return {
  1276. left: 0,
  1277. top: 0,
  1278. width: 0,
  1279. height: 0
  1280. };
  1281. }
  1282. var width = el.offsetWidth;
  1283. var height = el.offsetHeight;
  1284. var left = 0;
  1285. var top = 0;
  1286. while (el.offsetParent && el !== document__default['default'][FullscreenApi.fullscreenElement]) {
  1287. left += el.offsetLeft;
  1288. top += el.offsetTop;
  1289. el = el.offsetParent;
  1290. }
  1291. return {
  1292. left: left,
  1293. top: top,
  1294. width: width,
  1295. height: height
  1296. };
  1297. }
  1298. /**
  1299. * Represents x and y coordinates for a DOM element or mouse pointer.
  1300. *
  1301. * @typedef {Object} module:dom~Coordinates
  1302. *
  1303. * @property {number} x
  1304. * x coordinate in pixels
  1305. *
  1306. * @property {number} y
  1307. * y coordinate in pixels
  1308. */
  1309. /**
  1310. * Get the pointer position within an element.
  1311. *
  1312. * The base on the coordinates are the bottom left of the element.
  1313. *
  1314. * @param {Element} el
  1315. * Element on which to get the pointer position on.
  1316. *
  1317. * @param {EventTarget~Event} event
  1318. * Event object.
  1319. *
  1320. * @return {module:dom~Coordinates}
  1321. * A coordinates object corresponding to the mouse position.
  1322. *
  1323. */
  1324. function getPointerPosition(el, event) {
  1325. var translated = {
  1326. x: 0,
  1327. y: 0
  1328. };
  1329. if (IS_IOS) {
  1330. var item = el;
  1331. while (item && item.nodeName.toLowerCase() !== 'html') {
  1332. var transform = computedStyle(item, 'transform');
  1333. if (/^matrix/.test(transform)) {
  1334. var values = transform.slice(7, -1).split(/,\s/).map(Number);
  1335. translated.x += values[4];
  1336. translated.y += values[5];
  1337. } else if (/^matrix3d/.test(transform)) {
  1338. var _values = transform.slice(9, -1).split(/,\s/).map(Number);
  1339. translated.x += _values[12];
  1340. translated.y += _values[13];
  1341. }
  1342. item = item.parentNode;
  1343. }
  1344. }
  1345. var position = {};
  1346. var boxTarget = findPosition(event.target);
  1347. var box = findPosition(el);
  1348. var boxW = box.width;
  1349. var boxH = box.height;
  1350. var offsetY = event.offsetY - (box.top - boxTarget.top);
  1351. var offsetX = event.offsetX - (box.left - boxTarget.left);
  1352. if (event.changedTouches) {
  1353. offsetX = event.changedTouches[0].pageX - box.left;
  1354. offsetY = event.changedTouches[0].pageY + box.top;
  1355. if (IS_IOS) {
  1356. offsetX -= translated.x;
  1357. offsetY -= translated.y;
  1358. }
  1359. }
  1360. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1361. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1362. return position;
  1363. }
  1364. /**
  1365. * Determines, via duck typing, whether or not a value is a text node.
  1366. *
  1367. * @param {Mixed} value
  1368. * Check if this value is a text node.
  1369. *
  1370. * @return {boolean}
  1371. * Will be `true` if the value is a text node, `false` otherwise.
  1372. */
  1373. function isTextNode(value) {
  1374. return isObject(value) && value.nodeType === 3;
  1375. }
  1376. /**
  1377. * Empties the contents of an element.
  1378. *
  1379. * @param {Element} el
  1380. * The element to empty children from
  1381. *
  1382. * @return {Element}
  1383. * The element with no children
  1384. */
  1385. function emptyEl(el) {
  1386. while (el.firstChild) {
  1387. el.removeChild(el.firstChild);
  1388. }
  1389. return el;
  1390. }
  1391. /**
  1392. * This is a mixed value that describes content to be injected into the DOM
  1393. * via some method. It can be of the following types:
  1394. *
  1395. * Type | Description
  1396. * -----------|-------------
  1397. * `string` | The value will be normalized into a text node.
  1398. * `Element` | The value will be accepted as-is.
  1399. * `TextNode` | The value will be accepted as-is.
  1400. * `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).
  1401. * `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.
  1402. *
  1403. * @typedef {string|Element|TextNode|Array|Function} module:dom~ContentDescriptor
  1404. */
  1405. /**
  1406. * Normalizes content for eventual insertion into the DOM.
  1407. *
  1408. * This allows a wide range of content definition methods, but helps protect
  1409. * from falling into the trap of simply writing to `innerHTML`, which could
  1410. * be an XSS concern.
  1411. *
  1412. * The content for an element can be passed in multiple types and
  1413. * combinations, whose behavior is as follows:
  1414. *
  1415. * @param {module:dom~ContentDescriptor} content
  1416. * A content descriptor value.
  1417. *
  1418. * @return {Array}
  1419. * All of the content that was passed in, normalized to an array of
  1420. * elements or text nodes.
  1421. */
  1422. function normalizeContent(content) {
  1423. // First, invoke content if it is a function. If it produces an array,
  1424. // that needs to happen before normalization.
  1425. if (typeof content === 'function') {
  1426. content = content();
  1427. } // Next up, normalize to an array, so one or many items can be normalized,
  1428. // filtered, and returned.
  1429. return (Array.isArray(content) ? content : [content]).map(function (value) {
  1430. // First, invoke value if it is a function to produce a new value,
  1431. // which will be subsequently normalized to a Node of some kind.
  1432. if (typeof value === 'function') {
  1433. value = value();
  1434. }
  1435. if (isEl(value) || isTextNode(value)) {
  1436. return value;
  1437. }
  1438. if (typeof value === 'string' && /\S/.test(value)) {
  1439. return document__default['default'].createTextNode(value);
  1440. }
  1441. }).filter(function (value) {
  1442. return value;
  1443. });
  1444. }
  1445. /**
  1446. * Normalizes and appends content to an element.
  1447. *
  1448. * @param {Element} el
  1449. * Element to append normalized content to.
  1450. *
  1451. * @param {module:dom~ContentDescriptor} content
  1452. * A content descriptor value.
  1453. *
  1454. * @return {Element}
  1455. * The element with appended normalized content.
  1456. */
  1457. function appendContent(el, content) {
  1458. normalizeContent(content).forEach(function (node) {
  1459. return el.appendChild(node);
  1460. });
  1461. return el;
  1462. }
  1463. /**
  1464. * Normalizes and inserts content into an element; this is identical to
  1465. * `appendContent()`, except it empties the element first.
  1466. *
  1467. * @param {Element} el
  1468. * Element to insert normalized content into.
  1469. *
  1470. * @param {module:dom~ContentDescriptor} content
  1471. * A content descriptor value.
  1472. *
  1473. * @return {Element}
  1474. * The element with inserted normalized content.
  1475. */
  1476. function insertContent(el, content) {
  1477. return appendContent(emptyEl(el), content);
  1478. }
  1479. /**
  1480. * Check if an event was a single left click.
  1481. *
  1482. * @param {EventTarget~Event} event
  1483. * Event object.
  1484. *
  1485. * @return {boolean}
  1486. * Will be `true` if a single left click, `false` otherwise.
  1487. */
  1488. function isSingleLeftClick(event) {
  1489. // Note: if you create something draggable, be sure to
  1490. // call it on both `mousedown` and `mousemove` event,
  1491. // otherwise `mousedown` should be enough for a button
  1492. if (event.button === undefined && event.buttons === undefined) {
  1493. // Why do we need `buttons` ?
  1494. // Because, middle mouse sometimes have this:
  1495. // e.button === 0 and e.buttons === 4
  1496. // Furthermore, we want to prevent combination click, something like
  1497. // HOLD middlemouse then left click, that would be
  1498. // e.button === 0, e.buttons === 5
  1499. // just `button` is not gonna work
  1500. // Alright, then what this block does ?
  1501. // this is for chrome `simulate mobile devices`
  1502. // I want to support this as well
  1503. return true;
  1504. }
  1505. if (event.button === 0 && event.buttons === undefined) {
  1506. // Touch screen, sometimes on some specific device, `buttons`
  1507. // doesn't have anything (safari on ios, blackberry...)
  1508. return true;
  1509. } // `mouseup` event on a single left click has
  1510. // `button` and `buttons` equal to 0
  1511. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1512. return true;
  1513. }
  1514. if (event.button !== 0 || event.buttons !== 1) {
  1515. // This is the reason we have those if else block above
  1516. // if any special case we can catch and let it slide
  1517. // we do it above, when get to here, this definitely
  1518. // is-not-left-click
  1519. return false;
  1520. }
  1521. return true;
  1522. }
  1523. /**
  1524. * Finds a single DOM element matching `selector` within the optional
  1525. * `context` of another DOM element (defaulting to `document`).
  1526. *
  1527. * @param {string} selector
  1528. * A valid CSS selector, which will be passed to `querySelector`.
  1529. *
  1530. * @param {Element|String} [context=document]
  1531. * A DOM element within which to query. Can also be a selector
  1532. * string in which case the first matching element will be used
  1533. * as context. If missing (or no element matches selector), falls
  1534. * back to `document`.
  1535. *
  1536. * @return {Element|null}
  1537. * The element that was found or null.
  1538. */
  1539. var $ = createQuerier('querySelector');
  1540. /**
  1541. * Finds a all DOM elements matching `selector` within the optional
  1542. * `context` of another DOM element (defaulting to `document`).
  1543. *
  1544. * @param {string} selector
  1545. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1546. *
  1547. * @param {Element|String} [context=document]
  1548. * A DOM element within which to query. Can also be a selector
  1549. * string in which case the first matching element will be used
  1550. * as context. If missing (or no element matches selector), falls
  1551. * back to `document`.
  1552. *
  1553. * @return {NodeList}
  1554. * A element list of elements that were found. Will be empty if none
  1555. * were found.
  1556. *
  1557. */
  1558. var $$ = createQuerier('querySelectorAll');
  1559. var Dom = /*#__PURE__*/Object.freeze({
  1560. __proto__: null,
  1561. isReal: isReal,
  1562. isEl: isEl,
  1563. isInFrame: isInFrame,
  1564. createEl: createEl,
  1565. textContent: textContent,
  1566. prependTo: prependTo,
  1567. hasClass: hasClass,
  1568. addClass: addClass,
  1569. removeClass: removeClass,
  1570. toggleClass: toggleClass,
  1571. setAttributes: setAttributes,
  1572. getAttributes: getAttributes,
  1573. getAttribute: getAttribute,
  1574. setAttribute: setAttribute,
  1575. removeAttribute: removeAttribute,
  1576. blockTextSelection: blockTextSelection,
  1577. unblockTextSelection: unblockTextSelection,
  1578. getBoundingClientRect: getBoundingClientRect,
  1579. findPosition: findPosition,
  1580. getPointerPosition: getPointerPosition,
  1581. isTextNode: isTextNode,
  1582. emptyEl: emptyEl,
  1583. normalizeContent: normalizeContent,
  1584. appendContent: appendContent,
  1585. insertContent: insertContent,
  1586. isSingleLeftClick: isSingleLeftClick,
  1587. $: $,
  1588. $$: $$
  1589. });
  1590. /**
  1591. * @file setup.js - Functions for setting up a player without
  1592. * user interaction based on the data-setup `attribute` of the video tag.
  1593. *
  1594. * @module setup
  1595. */
  1596. var _windowLoaded = false;
  1597. var videojs$1;
  1598. /**
  1599. * Set up any tags that have a data-setup `attribute` when the player is started.
  1600. */
  1601. var autoSetup = function autoSetup() {
  1602. if (videojs$1.options.autoSetup === false) {
  1603. return;
  1604. }
  1605. var vids = Array.prototype.slice.call(document__default['default'].getElementsByTagName('video'));
  1606. var audios = Array.prototype.slice.call(document__default['default'].getElementsByTagName('audio'));
  1607. var divs = Array.prototype.slice.call(document__default['default'].getElementsByTagName('video-js'));
  1608. var mediaEls = vids.concat(audios, divs); // Check if any media elements exist
  1609. if (mediaEls && mediaEls.length > 0) {
  1610. for (var i = 0, e = mediaEls.length; i < e; i++) {
  1611. var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func.
  1612. if (mediaEl && mediaEl.getAttribute) {
  1613. // Make sure this player hasn't already been set up.
  1614. if (mediaEl.player === undefined) {
  1615. var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists.
  1616. // We only auto-setup if they've added the data-setup attr.
  1617. if (options !== null) {
  1618. // Create new video.js instance.
  1619. videojs$1(mediaEl);
  1620. }
  1621. } // If getAttribute isn't defined, we need to wait for the DOM.
  1622. } else {
  1623. autoSetupTimeout(1);
  1624. break;
  1625. }
  1626. } // No videos were found, so keep looping unless page is finished loading.
  1627. } else if (!_windowLoaded) {
  1628. autoSetupTimeout(1);
  1629. }
  1630. };
  1631. /**
  1632. * Wait until the page is loaded before running autoSetup. This will be called in
  1633. * autoSetup if `hasLoaded` returns false.
  1634. *
  1635. * @param {number} wait
  1636. * How long to wait in ms
  1637. *
  1638. * @param {module:videojs} [vjs]
  1639. * The videojs library function
  1640. */
  1641. function autoSetupTimeout(wait, vjs) {
  1642. // Protect against breakage in non-browser environments
  1643. if (!isReal()) {
  1644. return;
  1645. }
  1646. if (vjs) {
  1647. videojs$1 = vjs;
  1648. }
  1649. window__default['default'].setTimeout(autoSetup, wait);
  1650. }
  1651. /**
  1652. * Used to set the internal tracking of window loaded state to true.
  1653. *
  1654. * @private
  1655. */
  1656. function setWindowLoaded() {
  1657. _windowLoaded = true;
  1658. window__default['default'].removeEventListener('load', setWindowLoaded);
  1659. }
  1660. if (isReal()) {
  1661. if (document__default['default'].readyState === 'complete') {
  1662. setWindowLoaded();
  1663. } else {
  1664. /**
  1665. * Listen for the load event on window, and set _windowLoaded to true.
  1666. *
  1667. * We use a standard event listener here to avoid incrementing the GUID
  1668. * before any players are created.
  1669. *
  1670. * @listens load
  1671. */
  1672. window__default['default'].addEventListener('load', setWindowLoaded);
  1673. }
  1674. }
  1675. /**
  1676. * @file stylesheet.js
  1677. * @module stylesheet
  1678. */
  1679. /**
  1680. * Create a DOM syle element given a className for it.
  1681. *
  1682. * @param {string} className
  1683. * The className to add to the created style element.
  1684. *
  1685. * @return {Element}
  1686. * The element that was created.
  1687. */
  1688. var createStyleElement = function createStyleElement(className) {
  1689. var style = document__default['default'].createElement('style');
  1690. style.className = className;
  1691. return style;
  1692. };
  1693. /**
  1694. * Add text to a DOM element.
  1695. *
  1696. * @param {Element} el
  1697. * The Element to add text content to.
  1698. *
  1699. * @param {string} content
  1700. * The text to add to the element.
  1701. */
  1702. var setTextContent = function setTextContent(el, content) {
  1703. if (el.styleSheet) {
  1704. el.styleSheet.cssText = content;
  1705. } else {
  1706. el.textContent = content;
  1707. }
  1708. };
  1709. /**
  1710. * @file guid.js
  1711. * @module guid
  1712. */
  1713. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1714. //
  1715. // The initial GUID is 3 because some users have come to rely on the first
  1716. // default player ID ending up as `vjs_video_3`.
  1717. //
  1718. // See: https://github.com/videojs/video.js/pull/6216
  1719. var _initialGuid = 3;
  1720. /**
  1721. * Unique ID for an element or function
  1722. *
  1723. * @type {Number}
  1724. */
  1725. var _guid = _initialGuid;
  1726. /**
  1727. * Get a unique auto-incrementing ID by number that has not been returned before.
  1728. *
  1729. * @return {number}
  1730. * A new unique ID.
  1731. */
  1732. function newGUID() {
  1733. return _guid++;
  1734. }
  1735. /**
  1736. * @file dom-data.js
  1737. * @module dom-data
  1738. */
  1739. var FakeWeakMap;
  1740. if (!window__default['default'].WeakMap) {
  1741. FakeWeakMap = /*#__PURE__*/function () {
  1742. function FakeWeakMap() {
  1743. this.vdata = 'vdata' + Math.floor(window__default['default'].performance && window__default['default'].performance.now() || Date.now());
  1744. this.data = {};
  1745. }
  1746. var _proto = FakeWeakMap.prototype;
  1747. _proto.set = function set(key, value) {
  1748. var access = key[this.vdata] || newGUID();
  1749. if (!key[this.vdata]) {
  1750. key[this.vdata] = access;
  1751. }
  1752. this.data[access] = value;
  1753. return this;
  1754. };
  1755. _proto.get = function get(key) {
  1756. var access = key[this.vdata]; // we have data, return it
  1757. if (access) {
  1758. return this.data[access];
  1759. } // we don't have data, return nothing.
  1760. // return undefined explicitly as that's the contract for this method
  1761. log$1('We have no data for this element', key);
  1762. return undefined;
  1763. };
  1764. _proto.has = function has(key) {
  1765. var access = key[this.vdata];
  1766. return access in this.data;
  1767. };
  1768. _proto["delete"] = function _delete(key) {
  1769. var access = key[this.vdata];
  1770. if (access) {
  1771. delete this.data[access];
  1772. delete key[this.vdata];
  1773. }
  1774. };
  1775. return FakeWeakMap;
  1776. }();
  1777. }
  1778. /**
  1779. * Element Data Store.
  1780. *
  1781. * Allows for binding data to an element without putting it directly on the
  1782. * element. Ex. Event listeners are stored here.
  1783. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1784. *
  1785. * @type {Object}
  1786. * @private
  1787. */
  1788. var DomData = window__default['default'].WeakMap ? new WeakMap() : new FakeWeakMap();
  1789. /**
  1790. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1791. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1792. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1793. * robust as jquery's, so there's probably some differences.
  1794. *
  1795. * @file events.js
  1796. * @module events
  1797. */
  1798. /**
  1799. * Clean up the listener cache and dispatchers
  1800. *
  1801. * @param {Element|Object} elem
  1802. * Element to clean up
  1803. *
  1804. * @param {string} type
  1805. * Type of event to clean up
  1806. */
  1807. function _cleanUpEvents(elem, type) {
  1808. if (!DomData.has(elem)) {
  1809. return;
  1810. }
  1811. var data = DomData.get(elem); // Remove the events of a particular type if there are none left
  1812. if (data.handlers[type].length === 0) {
  1813. delete data.handlers[type]; // data.handlers[type] = null;
  1814. // Setting to null was causing an error with data.handlers
  1815. // Remove the meta-handler from the element
  1816. if (elem.removeEventListener) {
  1817. elem.removeEventListener(type, data.dispatcher, false);
  1818. } else if (elem.detachEvent) {
  1819. elem.detachEvent('on' + type, data.dispatcher);
  1820. }
  1821. } // Remove the events object if there are no types left
  1822. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1823. delete data.handlers;
  1824. delete data.dispatcher;
  1825. delete data.disabled;
  1826. } // Finally remove the element data if there is no data left
  1827. if (Object.getOwnPropertyNames(data).length === 0) {
  1828. DomData["delete"](elem);
  1829. }
  1830. }
  1831. /**
  1832. * Loops through an array of event types and calls the requested method for each type.
  1833. *
  1834. * @param {Function} fn
  1835. * The event method we want to use.
  1836. *
  1837. * @param {Element|Object} elem
  1838. * Element or object to bind listeners to
  1839. *
  1840. * @param {string} type
  1841. * Type of event to bind to.
  1842. *
  1843. * @param {EventTarget~EventListener} callback
  1844. * Event listener.
  1845. */
  1846. function _handleMultipleEvents(fn, elem, types, callback) {
  1847. types.forEach(function (type) {
  1848. // Call the event method for each one of the types
  1849. fn(elem, type, callback);
  1850. });
  1851. }
  1852. /**
  1853. * Fix a native event to have standard property values
  1854. *
  1855. * @param {Object} event
  1856. * Event object to fix.
  1857. *
  1858. * @return {Object}
  1859. * Fixed event object.
  1860. */
  1861. function fixEvent(event) {
  1862. if (event.fixed_) {
  1863. return event;
  1864. }
  1865. function returnTrue() {
  1866. return true;
  1867. }
  1868. function returnFalse() {
  1869. return false;
  1870. } // Test if fixing up is needed
  1871. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1872. // But native events return true for stopPropagation, but don't have
  1873. // other expected methods like isPropagationStopped. Seems to be a problem
  1874. // with the Javascript Ninja code. So we're just overriding all events now.
  1875. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1876. var old = event || window__default['default'].event;
  1877. event = {}; // Clone the old object so that we can modify the values event = {};
  1878. // IE8 Doesn't like when you mess with native event properties
  1879. // Firefox returns false for event.hasOwnProperty('type') and other props
  1880. // which makes copying more difficult.
  1881. // TODO: Probably best to create a whitelist of event props
  1882. for (var key in old) {
  1883. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1884. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1885. // and webkitMovementX/Y
  1886. // Lighthouse complains if Event.path is copied
  1887. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1888. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1889. // we still want to if preventDefault isn't supported (IE8).
  1890. if (!(key === 'returnValue' && old.preventDefault)) {
  1891. event[key] = old[key];
  1892. }
  1893. }
  1894. } // The event occurred on this element
  1895. if (!event.target) {
  1896. event.target = event.srcElement || document__default['default'];
  1897. } // Handle which other element the event is related to
  1898. if (!event.relatedTarget) {
  1899. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1900. } // Stop the default browser action
  1901. event.preventDefault = function () {
  1902. if (old.preventDefault) {
  1903. old.preventDefault();
  1904. }
  1905. event.returnValue = false;
  1906. old.returnValue = false;
  1907. event.defaultPrevented = true;
  1908. };
  1909. event.defaultPrevented = false; // Stop the event from bubbling
  1910. event.stopPropagation = function () {
  1911. if (old.stopPropagation) {
  1912. old.stopPropagation();
  1913. }
  1914. event.cancelBubble = true;
  1915. old.cancelBubble = true;
  1916. event.isPropagationStopped = returnTrue;
  1917. };
  1918. event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers
  1919. event.stopImmediatePropagation = function () {
  1920. if (old.stopImmediatePropagation) {
  1921. old.stopImmediatePropagation();
  1922. }
  1923. event.isImmediatePropagationStopped = returnTrue;
  1924. event.stopPropagation();
  1925. };
  1926. event.isImmediatePropagationStopped = returnFalse; // Handle mouse position
  1927. if (event.clientX !== null && event.clientX !== undefined) {
  1928. var doc = document__default['default'].documentElement;
  1929. var body = document__default['default'].body;
  1930. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1931. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1932. } // Handle key presses
  1933. event.which = event.charCode || event.keyCode; // Fix button for mouse clicks:
  1934. // 0 == left; 1 == middle; 2 == right
  1935. if (event.button !== null && event.button !== undefined) {
  1936. // The following is disabled because it does not pass videojs-standard
  1937. // and... yikes.
  1938. /* eslint-disable */
  1939. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1940. /* eslint-enable */
  1941. }
  1942. }
  1943. event.fixed_ = true; // Returns fixed-up instance
  1944. return event;
  1945. }
  1946. /**
  1947. * Whether passive event listeners are supported
  1948. */
  1949. var _supportsPassive;
  1950. var supportsPassive = function supportsPassive() {
  1951. if (typeof _supportsPassive !== 'boolean') {
  1952. _supportsPassive = false;
  1953. try {
  1954. var opts = Object.defineProperty({}, 'passive', {
  1955. get: function get() {
  1956. _supportsPassive = true;
  1957. }
  1958. });
  1959. window__default['default'].addEventListener('test', null, opts);
  1960. window__default['default'].removeEventListener('test', null, opts);
  1961. } catch (e) {// disregard
  1962. }
  1963. }
  1964. return _supportsPassive;
  1965. };
  1966. /**
  1967. * Touch events Chrome expects to be passive
  1968. */
  1969. var passiveEvents = ['touchstart', 'touchmove'];
  1970. /**
  1971. * Add an event listener to element
  1972. * It stores the handler function in a separate cache object
  1973. * and adds a generic handler to the element's event,
  1974. * along with a unique id (guid) to the element.
  1975. *
  1976. * @param {Element|Object} elem
  1977. * Element or object to bind listeners to
  1978. *
  1979. * @param {string|string[]} type
  1980. * Type of event to bind to.
  1981. *
  1982. * @param {EventTarget~EventListener} fn
  1983. * Event listener.
  1984. */
  1985. function on(elem, type, fn) {
  1986. if (Array.isArray(type)) {
  1987. return _handleMultipleEvents(on, elem, type, fn);
  1988. }
  1989. if (!DomData.has(elem)) {
  1990. DomData.set(elem, {});
  1991. }
  1992. var data = DomData.get(elem); // We need a place to store all our handler data
  1993. if (!data.handlers) {
  1994. data.handlers = {};
  1995. }
  1996. if (!data.handlers[type]) {
  1997. data.handlers[type] = [];
  1998. }
  1999. if (!fn.guid) {
  2000. fn.guid = newGUID();
  2001. }
  2002. data.handlers[type].push(fn);
  2003. if (!data.dispatcher) {
  2004. data.disabled = false;
  2005. data.dispatcher = function (event, hash) {
  2006. if (data.disabled) {
  2007. return;
  2008. }
  2009. event = fixEvent(event);
  2010. var handlers = data.handlers[event.type];
  2011. if (handlers) {
  2012. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  2013. var handlersCopy = handlers.slice(0);
  2014. for (var m = 0, n = handlersCopy.length; m < n; m++) {
  2015. if (event.isImmediatePropagationStopped()) {
  2016. break;
  2017. } else {
  2018. try {
  2019. handlersCopy[m].call(elem, event, hash);
  2020. } catch (e) {
  2021. log$1.error(e);
  2022. }
  2023. }
  2024. }
  2025. }
  2026. };
  2027. }
  2028. if (data.handlers[type].length === 1) {
  2029. if (elem.addEventListener) {
  2030. var options = false;
  2031. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  2032. options = {
  2033. passive: true
  2034. };
  2035. }
  2036. elem.addEventListener(type, data.dispatcher, options);
  2037. } else if (elem.attachEvent) {
  2038. elem.attachEvent('on' + type, data.dispatcher);
  2039. }
  2040. }
  2041. }
  2042. /**
  2043. * Removes event listeners from an element
  2044. *
  2045. * @param {Element|Object} elem
  2046. * Object to remove listeners from.
  2047. *
  2048. * @param {string|string[]} [type]
  2049. * Type of listener to remove. Don't include to remove all events from element.
  2050. *
  2051. * @param {EventTarget~EventListener} [fn]
  2052. * Specific listener to remove. Don't include to remove listeners for an event
  2053. * type.
  2054. */
  2055. function off(elem, type, fn) {
  2056. // Don't want to add a cache object through getElData if not needed
  2057. if (!DomData.has(elem)) {
  2058. return;
  2059. }
  2060. var data = DomData.get(elem); // If no events exist, nothing to unbind
  2061. if (!data.handlers) {
  2062. return;
  2063. }
  2064. if (Array.isArray(type)) {
  2065. return _handleMultipleEvents(off, elem, type, fn);
  2066. } // Utility function
  2067. var removeType = function removeType(el, t) {
  2068. data.handlers[t] = [];
  2069. _cleanUpEvents(el, t);
  2070. }; // Are we removing all bound events?
  2071. if (type === undefined) {
  2072. for (var t in data.handlers) {
  2073. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2074. removeType(elem, t);
  2075. }
  2076. }
  2077. return;
  2078. }
  2079. var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind
  2080. if (!handlers) {
  2081. return;
  2082. } // If no listener was provided, remove all listeners for type
  2083. if (!fn) {
  2084. removeType(elem, type);
  2085. return;
  2086. } // We're only removing a single handler
  2087. if (fn.guid) {
  2088. for (var n = 0; n < handlers.length; n++) {
  2089. if (handlers[n].guid === fn.guid) {
  2090. handlers.splice(n--, 1);
  2091. }
  2092. }
  2093. }
  2094. _cleanUpEvents(elem, type);
  2095. }
  2096. /**
  2097. * Trigger an event for an element
  2098. *
  2099. * @param {Element|Object} elem
  2100. * Element to trigger an event on
  2101. *
  2102. * @param {EventTarget~Event|string} event
  2103. * A string (the type) or an event object with a type attribute
  2104. *
  2105. * @param {Object} [hash]
  2106. * data hash to pass along with the event
  2107. *
  2108. * @return {boolean|undefined}
  2109. * Returns the opposite of `defaultPrevented` if default was
  2110. * prevented. Otherwise, returns `undefined`
  2111. */
  2112. function trigger(elem, event, hash) {
  2113. // Fetches element data and a reference to the parent (for bubbling).
  2114. // Don't want to add a data object to cache for every parent,
  2115. // so checking hasElData first.
  2116. var elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2117. var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event,
  2118. // handler;
  2119. // If an event name was passed as a string, creates an event out of it
  2120. if (typeof event === 'string') {
  2121. event = {
  2122. type: event,
  2123. target: elem
  2124. };
  2125. } else if (!event.target) {
  2126. event.target = elem;
  2127. } // Normalizes the event properties.
  2128. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers.
  2129. if (elemData.dispatcher) {
  2130. elemData.dispatcher.call(elem, event, hash);
  2131. } // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2132. // recursively calls this function to bubble the event up the DOM.
  2133. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2134. trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled.
  2135. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2136. if (!DomData.has(event.target)) {
  2137. DomData.set(event.target, {});
  2138. }
  2139. var targetData = DomData.get(event.target); // Checks if the target has a default action for this event.
  2140. if (event.target[event.type]) {
  2141. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2142. targetData.disabled = true; // Executes the default action.
  2143. if (typeof event.target[event.type] === 'function') {
  2144. event.target[event.type]();
  2145. } // Re-enables event dispatching.
  2146. targetData.disabled = false;
  2147. }
  2148. } // Inform the triggerer if the default was prevented by returning false
  2149. return !event.defaultPrevented;
  2150. }
  2151. /**
  2152. * Trigger a listener only once for an event.
  2153. *
  2154. * @param {Element|Object} elem
  2155. * Element or object to bind to.
  2156. *
  2157. * @param {string|string[]} type
  2158. * Name/type of event
  2159. *
  2160. * @param {Event~EventListener} fn
  2161. * Event listener function
  2162. */
  2163. function one(elem, type, fn) {
  2164. if (Array.isArray(type)) {
  2165. return _handleMultipleEvents(one, elem, type, fn);
  2166. }
  2167. var func = function func() {
  2168. off(elem, type, func);
  2169. fn.apply(this, arguments);
  2170. }; // copy the guid to the new function so it can removed using the original function's ID
  2171. func.guid = fn.guid = fn.guid || newGUID();
  2172. on(elem, type, func);
  2173. }
  2174. /**
  2175. * Trigger a listener only once and then turn if off for all
  2176. * configured events
  2177. *
  2178. * @param {Element|Object} elem
  2179. * Element or object to bind to.
  2180. *
  2181. * @param {string|string[]} type
  2182. * Name/type of event
  2183. *
  2184. * @param {Event~EventListener} fn
  2185. * Event listener function
  2186. */
  2187. function any(elem, type, fn) {
  2188. var func = function func() {
  2189. off(elem, type, func);
  2190. fn.apply(this, arguments);
  2191. }; // copy the guid to the new function so it can removed using the original function's ID
  2192. func.guid = fn.guid = fn.guid || newGUID(); // multiple ons, but one off for everything
  2193. on(elem, type, func);
  2194. }
  2195. var Events = /*#__PURE__*/Object.freeze({
  2196. __proto__: null,
  2197. fixEvent: fixEvent,
  2198. on: on,
  2199. off: off,
  2200. trigger: trigger,
  2201. one: one,
  2202. any: any
  2203. });
  2204. /**
  2205. * @file fn.js
  2206. * @module fn
  2207. */
  2208. var UPDATE_REFRESH_INTERVAL = 30;
  2209. /**
  2210. * Bind (a.k.a proxy or context). A simple method for changing the context of
  2211. * a function.
  2212. *
  2213. * It also stores a unique id on the function so it can be easily removed from
  2214. * events.
  2215. *
  2216. * @function
  2217. * @param {Mixed} context
  2218. * The object to bind as scope.
  2219. *
  2220. * @param {Function} fn
  2221. * The function to be bound to a scope.
  2222. *
  2223. * @param {number} [uid]
  2224. * An optional unique ID for the function to be set
  2225. *
  2226. * @return {Function}
  2227. * The new function that will be bound into the context given
  2228. */
  2229. var bind = function bind(context, fn, uid) {
  2230. // Make sure the function has a unique ID
  2231. if (!fn.guid) {
  2232. fn.guid = newGUID();
  2233. } // Create the new function that changes the context
  2234. var bound = fn.bind(context); // Allow for the ability to individualize this function
  2235. // Needed in the case where multiple objects might share the same prototype
  2236. // IF both items add an event listener with the same function, then you try to remove just one
  2237. // it will remove both because they both have the same guid.
  2238. // when using this, you need to use the bind method when you remove the listener as well.
  2239. // currently used in text tracks
  2240. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2241. return bound;
  2242. };
  2243. /**
  2244. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2245. * at most once per every `wait` milliseconds.
  2246. *
  2247. * @function
  2248. * @param {Function} fn
  2249. * The function to be throttled.
  2250. *
  2251. * @param {number} wait
  2252. * The number of milliseconds by which to throttle.
  2253. *
  2254. * @return {Function}
  2255. */
  2256. var throttle = function throttle(fn, wait) {
  2257. var last = window__default['default'].performance.now();
  2258. var throttled = function throttled() {
  2259. var now = window__default['default'].performance.now();
  2260. if (now - last >= wait) {
  2261. fn.apply(void 0, arguments);
  2262. last = now;
  2263. }
  2264. };
  2265. return throttled;
  2266. };
  2267. /**
  2268. * Creates a debounced function that delays invoking `func` until after `wait`
  2269. * milliseconds have elapsed since the last time the debounced function was
  2270. * invoked.
  2271. *
  2272. * Inspired by lodash and underscore implementations.
  2273. *
  2274. * @function
  2275. * @param {Function} func
  2276. * The function to wrap with debounce behavior.
  2277. *
  2278. * @param {number} wait
  2279. * The number of milliseconds to wait after the last invocation.
  2280. *
  2281. * @param {boolean} [immediate]
  2282. * Whether or not to invoke the function immediately upon creation.
  2283. *
  2284. * @param {Object} [context=window]
  2285. * The "context" in which the debounced function should debounce. For
  2286. * example, if this function should be tied to a Video.js player,
  2287. * the player can be passed here. Alternatively, defaults to the
  2288. * global `window` object.
  2289. *
  2290. * @return {Function}
  2291. * A debounced function.
  2292. */
  2293. var debounce = function debounce(func, wait, immediate, context) {
  2294. if (context === void 0) {
  2295. context = window__default['default'];
  2296. }
  2297. var timeout;
  2298. var cancel = function cancel() {
  2299. context.clearTimeout(timeout);
  2300. timeout = null;
  2301. };
  2302. /* eslint-disable consistent-this */
  2303. var debounced = function debounced() {
  2304. var self = this;
  2305. var args = arguments;
  2306. var _later = function later() {
  2307. timeout = null;
  2308. _later = null;
  2309. if (!immediate) {
  2310. func.apply(self, args);
  2311. }
  2312. };
  2313. if (!timeout && immediate) {
  2314. func.apply(self, args);
  2315. }
  2316. context.clearTimeout(timeout);
  2317. timeout = context.setTimeout(_later, wait);
  2318. };
  2319. /* eslint-enable consistent-this */
  2320. debounced.cancel = cancel;
  2321. return debounced;
  2322. };
  2323. /**
  2324. * @file src/js/event-target.js
  2325. */
  2326. /**
  2327. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2328. * adds shorthand functions that wrap around lengthy functions. For example:
  2329. * the `on` function is a wrapper around `addEventListener`.
  2330. *
  2331. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2332. * @class EventTarget
  2333. */
  2334. var EventTarget$2 = function EventTarget() {};
  2335. /**
  2336. * A Custom DOM event.
  2337. *
  2338. * @typedef {Object} EventTarget~Event
  2339. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2340. */
  2341. /**
  2342. * All event listeners should follow the following format.
  2343. *
  2344. * @callback EventTarget~EventListener
  2345. * @this {EventTarget}
  2346. *
  2347. * @param {EventTarget~Event} event
  2348. * the event that triggered this function
  2349. *
  2350. * @param {Object} [hash]
  2351. * hash of data sent during the event
  2352. */
  2353. /**
  2354. * An object containing event names as keys and booleans as values.
  2355. *
  2356. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2357. * will have extra functionality. See that function for more information.
  2358. *
  2359. * @property EventTarget.prototype.allowedEvents_
  2360. * @private
  2361. */
  2362. EventTarget$2.prototype.allowedEvents_ = {};
  2363. /**
  2364. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2365. * function that will get called when an event with a certain name gets triggered.
  2366. *
  2367. * @param {string|string[]} type
  2368. * An event name or an array of event names.
  2369. *
  2370. * @param {EventTarget~EventListener} fn
  2371. * The function to call with `EventTarget`s
  2372. */
  2373. EventTarget$2.prototype.on = function (type, fn) {
  2374. // Remove the addEventListener alias before calling Events.on
  2375. // so we don't get into an infinite type loop
  2376. var ael = this.addEventListener;
  2377. this.addEventListener = function () {};
  2378. on(this, type, fn);
  2379. this.addEventListener = ael;
  2380. };
  2381. /**
  2382. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2383. * the standard DOM API.
  2384. *
  2385. * @function
  2386. * @see {@link EventTarget#on}
  2387. */
  2388. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2389. /**
  2390. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2391. * This makes it so that the `event listener` will no longer get called when the
  2392. * named event happens.
  2393. *
  2394. * @param {string|string[]} type
  2395. * An event name or an array of event names.
  2396. *
  2397. * @param {EventTarget~EventListener} fn
  2398. * The function to remove.
  2399. */
  2400. EventTarget$2.prototype.off = function (type, fn) {
  2401. off(this, type, fn);
  2402. };
  2403. /**
  2404. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2405. * the standard DOM API.
  2406. *
  2407. * @function
  2408. * @see {@link EventTarget#off}
  2409. */
  2410. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2411. /**
  2412. * This function will add an `event listener` that gets triggered only once. After the
  2413. * first trigger it will get removed. This is like adding an `event listener`
  2414. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2415. *
  2416. * @param {string|string[]} type
  2417. * An event name or an array of event names.
  2418. *
  2419. * @param {EventTarget~EventListener} fn
  2420. * The function to be called once for each event name.
  2421. */
  2422. EventTarget$2.prototype.one = function (type, fn) {
  2423. // Remove the addEventListener aliasing Events.on
  2424. // so we don't get into an infinite type loop
  2425. var ael = this.addEventListener;
  2426. this.addEventListener = function () {};
  2427. one(this, type, fn);
  2428. this.addEventListener = ael;
  2429. };
  2430. EventTarget$2.prototype.any = function (type, fn) {
  2431. // Remove the addEventListener aliasing Events.on
  2432. // so we don't get into an infinite type loop
  2433. var ael = this.addEventListener;
  2434. this.addEventListener = function () {};
  2435. any(this, type, fn);
  2436. this.addEventListener = ael;
  2437. };
  2438. /**
  2439. * This function causes an event to happen. This will then cause any `event listeners`
  2440. * that are waiting for that event, to get called. If there are no `event listeners`
  2441. * for an event then nothing will happen.
  2442. *
  2443. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2444. * Trigger will also call the `on` + `uppercaseEventName` function.
  2445. *
  2446. * Example:
  2447. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2448. * `onClick` if it exists.
  2449. *
  2450. * @param {string|EventTarget~Event|Object} event
  2451. * The name of the event, an `Event`, or an object with a key of type set to
  2452. * an event name.
  2453. */
  2454. EventTarget$2.prototype.trigger = function (event) {
  2455. var type = event.type || event; // deprecation
  2456. // In a future version we should default target to `this`
  2457. // similar to how we default the target to `elem` in
  2458. // `Events.trigger`. Right now the default `target` will be
  2459. // `document` due to the `Event.fixEvent` call.
  2460. if (typeof event === 'string') {
  2461. event = {
  2462. type: type
  2463. };
  2464. }
  2465. event = fixEvent(event);
  2466. if (this.allowedEvents_[type] && this['on' + type]) {
  2467. this['on' + type](event);
  2468. }
  2469. trigger(this, event);
  2470. };
  2471. /**
  2472. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2473. * the standard DOM API.
  2474. *
  2475. * @function
  2476. * @see {@link EventTarget#trigger}
  2477. */
  2478. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2479. var EVENT_MAP;
  2480. EventTarget$2.prototype.queueTrigger = function (event) {
  2481. var _this = this;
  2482. // only set up EVENT_MAP if it'll be used
  2483. if (!EVENT_MAP) {
  2484. EVENT_MAP = new Map();
  2485. }
  2486. var type = event.type || event;
  2487. var map = EVENT_MAP.get(this);
  2488. if (!map) {
  2489. map = new Map();
  2490. EVENT_MAP.set(this, map);
  2491. }
  2492. var oldTimeout = map.get(type);
  2493. map["delete"](type);
  2494. window__default['default'].clearTimeout(oldTimeout);
  2495. var timeout = window__default['default'].setTimeout(function () {
  2496. map["delete"](type); // if we cleared out all timeouts for the current target, delete its map
  2497. if (map.size === 0) {
  2498. map = null;
  2499. EVENT_MAP["delete"](_this);
  2500. }
  2501. _this.trigger(event);
  2502. }, 0);
  2503. map.set(type, timeout);
  2504. };
  2505. /**
  2506. * @file mixins/evented.js
  2507. * @module evented
  2508. */
  2509. var objName = function objName(obj) {
  2510. if (typeof obj.name === 'function') {
  2511. return obj.name();
  2512. }
  2513. if (typeof obj.name === 'string') {
  2514. return obj.name;
  2515. }
  2516. if (obj.name_) {
  2517. return obj.name_;
  2518. }
  2519. if (obj.constructor && obj.constructor.name) {
  2520. return obj.constructor.name;
  2521. }
  2522. return typeof obj;
  2523. };
  2524. /**
  2525. * Returns whether or not an object has had the evented mixin applied.
  2526. *
  2527. * @param {Object} object
  2528. * An object to test.
  2529. *
  2530. * @return {boolean}
  2531. * Whether or not the object appears to be evented.
  2532. */
  2533. var isEvented = function isEvented(object) {
  2534. return object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(function (k) {
  2535. return typeof object[k] === 'function';
  2536. });
  2537. };
  2538. /**
  2539. * Adds a callback to run after the evented mixin applied.
  2540. *
  2541. * @param {Object} object
  2542. * An object to Add
  2543. * @param {Function} callback
  2544. * The callback to run.
  2545. */
  2546. var addEventedCallback = function addEventedCallback(target, callback) {
  2547. if (isEvented(target)) {
  2548. callback();
  2549. } else {
  2550. if (!target.eventedCallbacks) {
  2551. target.eventedCallbacks = [];
  2552. }
  2553. target.eventedCallbacks.push(callback);
  2554. }
  2555. };
  2556. /**
  2557. * Whether a value is a valid event type - non-empty string or array.
  2558. *
  2559. * @private
  2560. * @param {string|Array} type
  2561. * The type value to test.
  2562. *
  2563. * @return {boolean}
  2564. * Whether or not the type is a valid event type.
  2565. */
  2566. var isValidEventType = function isValidEventType(type) {
  2567. return (// The regex here verifies that the `type` contains at least one non-
  2568. // whitespace character.
  2569. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length
  2570. );
  2571. };
  2572. /**
  2573. * Validates a value to determine if it is a valid event target. Throws if not.
  2574. *
  2575. * @private
  2576. * @throws {Error}
  2577. * If the target does not appear to be a valid event target.
  2578. *
  2579. * @param {Object} target
  2580. * The object to test.
  2581. *
  2582. * @param {Object} obj
  2583. * The evented object we are validating for
  2584. *
  2585. * @param {string} fnName
  2586. * The name of the evented mixin function that called this.
  2587. */
  2588. var validateTarget = function validateTarget(target, obj, fnName) {
  2589. if (!target || !target.nodeName && !isEvented(target)) {
  2590. throw new Error("Invalid target for " + objName(obj) + "#" + fnName + "; must be a DOM node or evented object.");
  2591. }
  2592. };
  2593. /**
  2594. * Validates a value to determine if it is a valid event target. Throws if not.
  2595. *
  2596. * @private
  2597. * @throws {Error}
  2598. * If the type does not appear to be a valid event type.
  2599. *
  2600. * @param {string|Array} type
  2601. * The type to test.
  2602. *
  2603. * @param {Object} obj
  2604. * The evented object we are validating for
  2605. *
  2606. * @param {string} fnName
  2607. * The name of the evented mixin function that called this.
  2608. */
  2609. var validateEventType = function validateEventType(type, obj, fnName) {
  2610. if (!isValidEventType(type)) {
  2611. throw new Error("Invalid event type for " + objName(obj) + "#" + fnName + "; must be a non-empty string or array.");
  2612. }
  2613. };
  2614. /**
  2615. * Validates a value to determine if it is a valid listener. Throws if not.
  2616. *
  2617. * @private
  2618. * @throws {Error}
  2619. * If the listener is not a function.
  2620. *
  2621. * @param {Function} listener
  2622. * The listener to test.
  2623. *
  2624. * @param {Object} obj
  2625. * The evented object we are validating for
  2626. *
  2627. * @param {string} fnName
  2628. * The name of the evented mixin function that called this.
  2629. */
  2630. var validateListener = function validateListener(listener, obj, fnName) {
  2631. if (typeof listener !== 'function') {
  2632. throw new Error("Invalid listener for " + objName(obj) + "#" + fnName + "; must be a function.");
  2633. }
  2634. };
  2635. /**
  2636. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2637. * normalizes them into an object.
  2638. *
  2639. * @private
  2640. * @param {Object} self
  2641. * The evented object on which `on()` or `one()` was called. This
  2642. * object will be bound as the `this` value for the listener.
  2643. *
  2644. * @param {Array} args
  2645. * An array of arguments passed to `on()` or `one()`.
  2646. *
  2647. * @param {string} fnName
  2648. * The name of the evented mixin function that called this.
  2649. *
  2650. * @return {Object}
  2651. * An object containing useful values for `on()` or `one()` calls.
  2652. */
  2653. var normalizeListenArgs = function normalizeListenArgs(self, args, fnName) {
  2654. // If the number of arguments is less than 3, the target is always the
  2655. // evented object itself.
  2656. var isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2657. var target;
  2658. var type;
  2659. var listener;
  2660. if (isTargetingSelf) {
  2661. target = self.eventBusEl_; // Deal with cases where we got 3 arguments, but we are still listening to
  2662. // the evented object itself.
  2663. if (args.length >= 3) {
  2664. args.shift();
  2665. }
  2666. type = args[0];
  2667. listener = args[1];
  2668. } else {
  2669. target = args[0];
  2670. type = args[1];
  2671. listener = args[2];
  2672. }
  2673. validateTarget(target, self, fnName);
  2674. validateEventType(type, self, fnName);
  2675. validateListener(listener, self, fnName);
  2676. listener = bind(self, listener);
  2677. return {
  2678. isTargetingSelf: isTargetingSelf,
  2679. target: target,
  2680. type: type,
  2681. listener: listener
  2682. };
  2683. };
  2684. /**
  2685. * Adds the listener to the event type(s) on the target, normalizing for
  2686. * the type of target.
  2687. *
  2688. * @private
  2689. * @param {Element|Object} target
  2690. * A DOM node or evented object.
  2691. *
  2692. * @param {string} method
  2693. * The event binding method to use ("on" or "one").
  2694. *
  2695. * @param {string|Array} type
  2696. * One or more event type(s).
  2697. *
  2698. * @param {Function} listener
  2699. * A listener function.
  2700. */
  2701. var listen = function listen(target, method, type, listener) {
  2702. validateTarget(target, target, method);
  2703. if (target.nodeName) {
  2704. Events[method](target, type, listener);
  2705. } else {
  2706. target[method](type, listener);
  2707. }
  2708. };
  2709. /**
  2710. * Contains methods that provide event capabilities to an object which is passed
  2711. * to {@link module:evented|evented}.
  2712. *
  2713. * @mixin EventedMixin
  2714. */
  2715. var EventedMixin = {
  2716. /**
  2717. * Add a listener to an event (or events) on this object or another evented
  2718. * object.
  2719. *
  2720. * @param {string|Array|Element|Object} targetOrType
  2721. * If this is a string or array, it represents the event type(s)
  2722. * that will trigger the listener.
  2723. *
  2724. * Another evented object can be passed here instead, which will
  2725. * cause the listener to listen for events on _that_ object.
  2726. *
  2727. * In either case, the listener's `this` value will be bound to
  2728. * this object.
  2729. *
  2730. * @param {string|Array|Function} typeOrListener
  2731. * If the first argument was a string or array, this should be the
  2732. * listener function. Otherwise, this is a string or array of event
  2733. * type(s).
  2734. *
  2735. * @param {Function} [listener]
  2736. * If the first argument was another evented object, this will be
  2737. * the listener function.
  2738. */
  2739. on: function on() {
  2740. var _this = this;
  2741. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2742. args[_key] = arguments[_key];
  2743. }
  2744. var _normalizeListenArgs = normalizeListenArgs(this, args, 'on'),
  2745. isTargetingSelf = _normalizeListenArgs.isTargetingSelf,
  2746. target = _normalizeListenArgs.target,
  2747. type = _normalizeListenArgs.type,
  2748. listener = _normalizeListenArgs.listener;
  2749. listen(target, 'on', type, listener); // If this object is listening to another evented object.
  2750. if (!isTargetingSelf) {
  2751. // If this object is disposed, remove the listener.
  2752. var removeListenerOnDispose = function removeListenerOnDispose() {
  2753. return _this.off(target, type, listener);
  2754. }; // Use the same function ID as the listener so we can remove it later it
  2755. // using the ID of the original listener.
  2756. removeListenerOnDispose.guid = listener.guid; // Add a listener to the target's dispose event as well. This ensures
  2757. // that if the target is disposed BEFORE this object, we remove the
  2758. // removal listener that was just added. Otherwise, we create a memory leak.
  2759. var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose() {
  2760. return _this.off('dispose', removeListenerOnDispose);
  2761. }; // Use the same function ID as the listener so we can remove it later
  2762. // it using the ID of the original listener.
  2763. removeRemoverOnTargetDispose.guid = listener.guid;
  2764. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2765. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2766. }
  2767. },
  2768. /**
  2769. * Add a listener to an event (or events) on this object or another evented
  2770. * object. The listener will be called once per event and then removed.
  2771. *
  2772. * @param {string|Array|Element|Object} targetOrType
  2773. * If this is a string or array, it represents the event type(s)
  2774. * that will trigger the listener.
  2775. *
  2776. * Another evented object can be passed here instead, which will
  2777. * cause the listener to listen for events on _that_ object.
  2778. *
  2779. * In either case, the listener's `this` value will be bound to
  2780. * this object.
  2781. *
  2782. * @param {string|Array|Function} typeOrListener
  2783. * If the first argument was a string or array, this should be the
  2784. * listener function. Otherwise, this is a string or array of event
  2785. * type(s).
  2786. *
  2787. * @param {Function} [listener]
  2788. * If the first argument was another evented object, this will be
  2789. * the listener function.
  2790. */
  2791. one: function one() {
  2792. var _this2 = this;
  2793. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  2794. args[_key2] = arguments[_key2];
  2795. }
  2796. var _normalizeListenArgs2 = normalizeListenArgs(this, args, 'one'),
  2797. isTargetingSelf = _normalizeListenArgs2.isTargetingSelf,
  2798. target = _normalizeListenArgs2.target,
  2799. type = _normalizeListenArgs2.type,
  2800. listener = _normalizeListenArgs2.listener; // Targeting this evented object.
  2801. if (isTargetingSelf) {
  2802. listen(target, 'one', type, listener); // Targeting another evented object.
  2803. } else {
  2804. // TODO: This wrapper is incorrect! It should only
  2805. // remove the wrapper for the event type that called it.
  2806. // Instead all listners are removed on the first trigger!
  2807. // see https://github.com/videojs/video.js/issues/5962
  2808. var wrapper = function wrapper() {
  2809. _this2.off(target, type, wrapper);
  2810. for (var _len3 = arguments.length, largs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  2811. largs[_key3] = arguments[_key3];
  2812. }
  2813. listener.apply(null, largs);
  2814. }; // Use the same function ID as the listener so we can remove it later
  2815. // it using the ID of the original listener.
  2816. wrapper.guid = listener.guid;
  2817. listen(target, 'one', type, wrapper);
  2818. }
  2819. },
  2820. /**
  2821. * Add a listener to an event (or events) on this object or another evented
  2822. * object. The listener will only be called once for the first event that is triggered
  2823. * then removed.
  2824. *
  2825. * @param {string|Array|Element|Object} targetOrType
  2826. * If this is a string or array, it represents the event type(s)
  2827. * that will trigger the listener.
  2828. *
  2829. * Another evented object can be passed here instead, which will
  2830. * cause the listener to listen for events on _that_ object.
  2831. *
  2832. * In either case, the listener's `this` value will be bound to
  2833. * this object.
  2834. *
  2835. * @param {string|Array|Function} typeOrListener
  2836. * If the first argument was a string or array, this should be the
  2837. * listener function. Otherwise, this is a string or array of event
  2838. * type(s).
  2839. *
  2840. * @param {Function} [listener]
  2841. * If the first argument was another evented object, this will be
  2842. * the listener function.
  2843. */
  2844. any: function any() {
  2845. var _this3 = this;
  2846. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  2847. args[_key4] = arguments[_key4];
  2848. }
  2849. var _normalizeListenArgs3 = normalizeListenArgs(this, args, 'any'),
  2850. isTargetingSelf = _normalizeListenArgs3.isTargetingSelf,
  2851. target = _normalizeListenArgs3.target,
  2852. type = _normalizeListenArgs3.type,
  2853. listener = _normalizeListenArgs3.listener; // Targeting this evented object.
  2854. if (isTargetingSelf) {
  2855. listen(target, 'any', type, listener); // Targeting another evented object.
  2856. } else {
  2857. var wrapper = function wrapper() {
  2858. _this3.off(target, type, wrapper);
  2859. for (var _len5 = arguments.length, largs = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  2860. largs[_key5] = arguments[_key5];
  2861. }
  2862. listener.apply(null, largs);
  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: function off$1(targetOrType, typeOrListener, listener) {
  2889. // Targeting this evented object.
  2890. if (!targetOrType || isValidEventType(targetOrType)) {
  2891. off(this.eventBusEl_, targetOrType, typeOrListener); // Targeting another evented object.
  2892. } else {
  2893. var target = targetOrType;
  2894. var type = typeOrListener; // Fail fast and in a meaningful way!
  2895. validateTarget(target, this, 'off');
  2896. validateEventType(type, this, 'off');
  2897. validateListener(listener, this, 'off'); // Ensure there's at least a guid, even if the function hasn't been used
  2898. listener = bind(this, listener); // Remove the dispose listener on this evented object, which was given
  2899. // the same guid as the event listener in on().
  2900. this.off('dispose', listener);
  2901. if (target.nodeName) {
  2902. off(target, type, listener);
  2903. off(target, 'dispose', listener);
  2904. } else if (isEvented(target)) {
  2905. target.off(type, listener);
  2906. target.off('dispose', listener);
  2907. }
  2908. }
  2909. },
  2910. /**
  2911. * Fire an event on this evented object, causing its listeners to be called.
  2912. *
  2913. * @param {string|Object} event
  2914. * An event type or an object with a type property.
  2915. *
  2916. * @param {Object} [hash]
  2917. * An additional object to pass along to listeners.
  2918. *
  2919. * @return {boolean}
  2920. * Whether or not the default behavior was prevented.
  2921. */
  2922. trigger: function trigger$1(event, hash) {
  2923. validateTarget(this.eventBusEl_, this, 'trigger');
  2924. var type = event && typeof event !== 'string' ? event.type : event;
  2925. if (!isValidEventType(type)) {
  2926. var 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.';
  2927. if (event) {
  2928. (this.log || log$1).error(error);
  2929. } else {
  2930. throw new Error(error);
  2931. }
  2932. }
  2933. return trigger(this.eventBusEl_, event, hash);
  2934. }
  2935. };
  2936. /**
  2937. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2938. *
  2939. * @param {Object} target
  2940. * The object to which to add event methods.
  2941. *
  2942. * @param {Object} [options={}]
  2943. * Options for customizing the mixin behavior.
  2944. *
  2945. * @param {string} [options.eventBusKey]
  2946. * By default, adds a `eventBusEl_` DOM element to the target object,
  2947. * which is used as an event bus. If the target object already has a
  2948. * DOM element that should be used, pass its key here.
  2949. *
  2950. * @return {Object}
  2951. * The target object.
  2952. */
  2953. function evented(target, options) {
  2954. if (options === void 0) {
  2955. options = {};
  2956. }
  2957. var _options = options,
  2958. eventBusKey = _options.eventBusKey; // Set or create the eventBusEl_.
  2959. if (eventBusKey) {
  2960. if (!target[eventBusKey].nodeName) {
  2961. throw new Error("The eventBusKey \"" + eventBusKey + "\" does not refer to an element.");
  2962. }
  2963. target.eventBusEl_ = target[eventBusKey];
  2964. } else {
  2965. target.eventBusEl_ = createEl('span', {
  2966. className: 'vjs-event-bus'
  2967. });
  2968. }
  2969. assign(target, EventedMixin);
  2970. if (target.eventedCallbacks) {
  2971. target.eventedCallbacks.forEach(function (callback) {
  2972. callback();
  2973. });
  2974. } // When any evented object is disposed, it removes all its listeners.
  2975. target.on('dispose', function () {
  2976. target.off();
  2977. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2978. if (val && DomData.has(val)) {
  2979. DomData["delete"](val);
  2980. }
  2981. });
  2982. window__default['default'].setTimeout(function () {
  2983. target.eventBusEl_ = null;
  2984. }, 0);
  2985. });
  2986. return target;
  2987. }
  2988. /**
  2989. * @file mixins/stateful.js
  2990. * @module stateful
  2991. */
  2992. /**
  2993. * Contains methods that provide statefulness to an object which is passed
  2994. * to {@link module:stateful}.
  2995. *
  2996. * @mixin StatefulMixin
  2997. */
  2998. var StatefulMixin = {
  2999. /**
  3000. * A hash containing arbitrary keys and values representing the state of
  3001. * the object.
  3002. *
  3003. * @type {Object}
  3004. */
  3005. state: {},
  3006. /**
  3007. * Set the state of an object by mutating its
  3008. * {@link module:stateful~StatefulMixin.state|state} object in place.
  3009. *
  3010. * @fires module:stateful~StatefulMixin#statechanged
  3011. * @param {Object|Function} stateUpdates
  3012. * A new set of properties to shallow-merge into the plugin state.
  3013. * Can be a plain object or a function returning a plain object.
  3014. *
  3015. * @return {Object|undefined}
  3016. * An object containing changes that occurred. If no changes
  3017. * occurred, returns `undefined`.
  3018. */
  3019. setState: function setState(stateUpdates) {
  3020. var _this = this;
  3021. // Support providing the `stateUpdates` state as a function.
  3022. if (typeof stateUpdates === 'function') {
  3023. stateUpdates = stateUpdates();
  3024. }
  3025. var changes;
  3026. each(stateUpdates, function (value, key) {
  3027. // Record the change if the value is different from what's in the
  3028. // current state.
  3029. if (_this.state[key] !== value) {
  3030. changes = changes || {};
  3031. changes[key] = {
  3032. from: _this.state[key],
  3033. to: value
  3034. };
  3035. }
  3036. _this.state[key] = value;
  3037. }); // Only trigger "statechange" if there were changes AND we have a trigger
  3038. // function. This allows us to not require that the target object be an
  3039. // evented object.
  3040. if (changes && isEvented(this)) {
  3041. /**
  3042. * An event triggered on an object that is both
  3043. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3044. * indicating that its state has changed.
  3045. *
  3046. * @event module:stateful~StatefulMixin#statechanged
  3047. * @type {Object}
  3048. * @property {Object} changes
  3049. * A hash containing the properties that were changed and
  3050. * the values they were changed `from` and `to`.
  3051. */
  3052. this.trigger({
  3053. changes: changes,
  3054. type: 'statechanged'
  3055. });
  3056. }
  3057. return changes;
  3058. }
  3059. };
  3060. /**
  3061. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3062. * object.
  3063. *
  3064. * If the target object is {@link module:evented|evented} and has a
  3065. * `handleStateChanged` method, that method will be automatically bound to the
  3066. * `statechanged` event on itself.
  3067. *
  3068. * @param {Object} target
  3069. * The object to be made stateful.
  3070. *
  3071. * @param {Object} [defaultState]
  3072. * A default set of properties to populate the newly-stateful object's
  3073. * `state` property.
  3074. *
  3075. * @return {Object}
  3076. * Returns the `target`.
  3077. */
  3078. function stateful(target, defaultState) {
  3079. assign(target, StatefulMixin); // This happens after the mixing-in because we need to replace the `state`
  3080. // added in that step.
  3081. target.state = assign({}, target.state, defaultState); // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3082. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3083. target.on('statechanged', target.handleStateChanged);
  3084. }
  3085. return target;
  3086. }
  3087. /**
  3088. * @file string-cases.js
  3089. * @module to-lower-case
  3090. */
  3091. /**
  3092. * Lowercase the first letter of a string.
  3093. *
  3094. * @param {string} string
  3095. * String to be lowercased
  3096. *
  3097. * @return {string}
  3098. * The string with a lowercased first letter
  3099. */
  3100. var toLowerCase = function toLowerCase(string) {
  3101. if (typeof string !== 'string') {
  3102. return string;
  3103. }
  3104. return string.replace(/./, function (w) {
  3105. return w.toLowerCase();
  3106. });
  3107. };
  3108. /**
  3109. * Uppercase the first letter of a string.
  3110. *
  3111. * @param {string} string
  3112. * String to be uppercased
  3113. *
  3114. * @return {string}
  3115. * The string with an uppercased first letter
  3116. */
  3117. var toTitleCase$1 = function toTitleCase(string) {
  3118. if (typeof string !== 'string') {
  3119. return string;
  3120. }
  3121. return string.replace(/./, function (w) {
  3122. return w.toUpperCase();
  3123. });
  3124. };
  3125. /**
  3126. * Compares the TitleCase versions of the two strings for equality.
  3127. *
  3128. * @param {string} str1
  3129. * The first string to compare
  3130. *
  3131. * @param {string} str2
  3132. * The second string to compare
  3133. *
  3134. * @return {boolean}
  3135. * Whether the TitleCase versions of the strings are equal
  3136. */
  3137. var titleCaseEquals = function titleCaseEquals(str1, str2) {
  3138. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3139. };
  3140. /**
  3141. * @file merge-options.js
  3142. * @module merge-options
  3143. */
  3144. /**
  3145. * Merge two objects recursively.
  3146. *
  3147. * Performs a deep merge like
  3148. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  3149. * plain objects (not arrays, elements, or anything else).
  3150. *
  3151. * Non-plain object values will be copied directly from the right-most
  3152. * argument.
  3153. *
  3154. * @static
  3155. * @param {Object[]} sources
  3156. * One or more objects to merge into a new object.
  3157. *
  3158. * @return {Object}
  3159. * A new object that is the merged result of all sources.
  3160. */
  3161. function mergeOptions$3() {
  3162. var result = {};
  3163. for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
  3164. sources[_key] = arguments[_key];
  3165. }
  3166. sources.forEach(function (source) {
  3167. if (!source) {
  3168. return;
  3169. }
  3170. each(source, function (value, key) {
  3171. if (!isPlain(value)) {
  3172. result[key] = value;
  3173. return;
  3174. }
  3175. if (!isPlain(result[key])) {
  3176. result[key] = {};
  3177. }
  3178. result[key] = mergeOptions$3(result[key], value);
  3179. });
  3180. });
  3181. return result;
  3182. }
  3183. var MapSham = /*#__PURE__*/function () {
  3184. function MapSham() {
  3185. this.map_ = {};
  3186. }
  3187. var _proto = MapSham.prototype;
  3188. _proto.has = function has(key) {
  3189. return key in this.map_;
  3190. };
  3191. _proto["delete"] = function _delete(key) {
  3192. var has = this.has(key);
  3193. delete this.map_[key];
  3194. return has;
  3195. };
  3196. _proto.set = function set(key, value) {
  3197. this.map_[key] = value;
  3198. return this;
  3199. };
  3200. _proto.forEach = function forEach(callback, thisArg) {
  3201. for (var key in this.map_) {
  3202. callback.call(thisArg, this.map_[key], key, this);
  3203. }
  3204. };
  3205. return MapSham;
  3206. }();
  3207. var Map$1 = window__default['default'].Map ? window__default['default'].Map : MapSham;
  3208. var SetSham = /*#__PURE__*/function () {
  3209. function SetSham() {
  3210. this.set_ = {};
  3211. }
  3212. var _proto = SetSham.prototype;
  3213. _proto.has = function has(key) {
  3214. return key in this.set_;
  3215. };
  3216. _proto["delete"] = function _delete(key) {
  3217. var has = this.has(key);
  3218. delete this.set_[key];
  3219. return has;
  3220. };
  3221. _proto.add = function add(key) {
  3222. this.set_[key] = 1;
  3223. return this;
  3224. };
  3225. _proto.forEach = function forEach(callback, thisArg) {
  3226. for (var key in this.set_) {
  3227. callback.call(thisArg, key, key, this);
  3228. }
  3229. };
  3230. return SetSham;
  3231. }();
  3232. var Set$1 = window__default['default'].Set ? window__default['default'].Set : SetSham;
  3233. /**
  3234. * Player Component - Base class for all UI objects
  3235. *
  3236. * @file component.js
  3237. */
  3238. /**
  3239. * Base class for all UI Components.
  3240. * Components are UI objects which represent both a javascript object and an element
  3241. * in the DOM. They can be children of other components, and can have
  3242. * children themselves.
  3243. *
  3244. * Components can also use methods from {@link EventTarget}
  3245. */
  3246. var Component$1 = /*#__PURE__*/function () {
  3247. /**
  3248. * A callback that is called when a component is ready. Does not have any
  3249. * paramters and any callback value will be ignored.
  3250. *
  3251. * @callback Component~ReadyCallback
  3252. * @this Component
  3253. */
  3254. /**
  3255. * Creates an instance of this class.
  3256. *
  3257. * @param {Player} player
  3258. * The `Player` that this class should be attached to.
  3259. *
  3260. * @param {Object} [options]
  3261. * The key/value store of component options.
  3262. *
  3263. * @param {Object[]} [options.children]
  3264. * An array of children objects to intialize this component with. Children objects have
  3265. * a name property that will be used if more than one component of the same type needs to be
  3266. * added.
  3267. *
  3268. * @param {string} [options.className]
  3269. * A class or space separated list of classes to add the component
  3270. *
  3271. * @param {Component~ReadyCallback} [ready]
  3272. * Function that gets called when the `Component` is ready.
  3273. */
  3274. function Component(player, options, ready) {
  3275. var _this = this;
  3276. // The component might be the player itself and we can't pass `this` to super
  3277. if (!player && this.play) {
  3278. this.player_ = player = this; // eslint-disable-line
  3279. } else {
  3280. this.player_ = player;
  3281. }
  3282. this.isDisposed_ = false; // Hold the reference to the parent component via `addChild` method
  3283. this.parentComponent_ = null; // Make a copy of prototype.options_ to protect against overriding defaults
  3284. this.options_ = mergeOptions$3({}, this.options_); // Updated options with supplied options
  3285. options = this.options_ = mergeOptions$3(this.options_, options); // Get ID from options or options element if one is supplied
  3286. this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one
  3287. if (!this.id_) {
  3288. // Don't require the player ID function in the case of mock players
  3289. var id = player && player.id && player.id() || 'no_player';
  3290. this.id_ = id + "_component_" + newGUID();
  3291. }
  3292. this.name_ = options.name || null; // Create element if one wasn't provided in options
  3293. if (options.el) {
  3294. this.el_ = options.el;
  3295. } else if (options.createEl !== false) {
  3296. this.el_ = this.createEl();
  3297. }
  3298. if (options.className && this.el_) {
  3299. options.className.split(' ').forEach(function (c) {
  3300. return _this.addClass(c);
  3301. });
  3302. } // if evented is anything except false, we want to mixin in evented
  3303. if (options.evented !== false) {
  3304. // Make this an evented object and use `el_`, if available, as its event bus
  3305. evented(this, {
  3306. eventBusKey: this.el_ ? 'el_' : null
  3307. });
  3308. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3309. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3310. }
  3311. stateful(this, this.constructor.defaultState);
  3312. this.children_ = [];
  3313. this.childIndex_ = {};
  3314. this.childNameIndex_ = {};
  3315. this.setTimeoutIds_ = new Set$1();
  3316. this.setIntervalIds_ = new Set$1();
  3317. this.rafIds_ = new Set$1();
  3318. this.namedRafs_ = new Map$1();
  3319. this.clearingTimersOnDispose_ = false; // Add any child components in options
  3320. if (options.initChildren !== false) {
  3321. this.initChildren();
  3322. } // Don't want to trigger ready here or it will go before init is actually
  3323. // finished for all children that run this constructor
  3324. this.ready(ready);
  3325. if (options.reportTouchActivity !== false) {
  3326. this.enableTouchActivity();
  3327. }
  3328. }
  3329. /**
  3330. * Dispose of the `Component` and all child components.
  3331. *
  3332. * @fires Component#dispose
  3333. *
  3334. * @param {Object} options
  3335. * @param {Element} options.originalEl element with which to replace player element
  3336. */
  3337. var _proto = Component.prototype;
  3338. _proto.dispose = function dispose(options) {
  3339. if (options === void 0) {
  3340. options = {};
  3341. }
  3342. // Bail out if the component has already been disposed.
  3343. if (this.isDisposed_) {
  3344. return;
  3345. }
  3346. if (this.readyQueue_) {
  3347. this.readyQueue_.length = 0;
  3348. }
  3349. /**
  3350. * Triggered when a `Component` is disposed.
  3351. *
  3352. * @event Component#dispose
  3353. * @type {EventTarget~Event}
  3354. *
  3355. * @property {boolean} [bubbles=false]
  3356. * set to false so that the dispose event does not
  3357. * bubble up
  3358. */
  3359. this.trigger({
  3360. type: 'dispose',
  3361. bubbles: false
  3362. });
  3363. this.isDisposed_ = true; // Dispose all children.
  3364. if (this.children_) {
  3365. for (var i = this.children_.length - 1; i >= 0; i--) {
  3366. if (this.children_[i].dispose) {
  3367. this.children_[i].dispose();
  3368. }
  3369. }
  3370. } // Delete child references
  3371. this.children_ = null;
  3372. this.childIndex_ = null;
  3373. this.childNameIndex_ = null;
  3374. this.parentComponent_ = null;
  3375. if (this.el_) {
  3376. // Remove element from DOM
  3377. if (this.el_.parentNode) {
  3378. if (options.restoreEl) {
  3379. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3380. } else {
  3381. this.el_.parentNode.removeChild(this.el_);
  3382. }
  3383. }
  3384. this.el_ = null;
  3385. } // remove reference to the player after disposing of the element
  3386. this.player_ = null;
  3387. }
  3388. /**
  3389. * Determine whether or not this component has been disposed.
  3390. *
  3391. * @return {boolean}
  3392. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3393. */
  3394. ;
  3395. _proto.isDisposed = function isDisposed() {
  3396. return Boolean(this.isDisposed_);
  3397. }
  3398. /**
  3399. * Return the {@link Player} that the `Component` has attached to.
  3400. *
  3401. * @return {Player}
  3402. * The player that this `Component` has attached to.
  3403. */
  3404. ;
  3405. _proto.player = function player() {
  3406. return this.player_;
  3407. }
  3408. /**
  3409. * Deep merge of options objects with new options.
  3410. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3411. * The two properties get merged using {@link module:mergeOptions}
  3412. *
  3413. * @param {Object} obj
  3414. * The object that contains new options.
  3415. *
  3416. * @return {Object}
  3417. * A new object of `this.options_` and `obj` merged together.
  3418. */
  3419. ;
  3420. _proto.options = function options(obj) {
  3421. if (!obj) {
  3422. return this.options_;
  3423. }
  3424. this.options_ = mergeOptions$3(this.options_, obj);
  3425. return this.options_;
  3426. }
  3427. /**
  3428. * Get the `Component`s DOM element
  3429. *
  3430. * @return {Element}
  3431. * The DOM element for this `Component`.
  3432. */
  3433. ;
  3434. _proto.el = function el() {
  3435. return this.el_;
  3436. }
  3437. /**
  3438. * Create the `Component`s DOM element.
  3439. *
  3440. * @param {string} [tagName]
  3441. * Element's DOM node type. e.g. 'div'
  3442. *
  3443. * @param {Object} [properties]
  3444. * An object of properties that should be set.
  3445. *
  3446. * @param {Object} [attributes]
  3447. * An object of attributes that should be set.
  3448. *
  3449. * @return {Element}
  3450. * The element that gets created.
  3451. */
  3452. ;
  3453. _proto.createEl = function createEl$1(tagName, properties, attributes) {
  3454. return createEl(tagName, properties, attributes);
  3455. }
  3456. /**
  3457. * Localize a string given the string in english.
  3458. *
  3459. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3460. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3461. *
  3462. * If a `defaultValue` is provided, it'll use that over `string`,
  3463. * if a value isn't found in provided language files.
  3464. * This is useful if you want to have a descriptive key for token replacement
  3465. * but have a succinct localized string and not require `en.json` to be included.
  3466. *
  3467. * Currently, it is used for the progress bar timing.
  3468. * ```js
  3469. * {
  3470. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3471. * }
  3472. * ```
  3473. * It is then used like so:
  3474. * ```js
  3475. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3476. * [this.player_.currentTime(), this.player_.duration()],
  3477. * '{1} of {2}');
  3478. * ```
  3479. *
  3480. * Which outputs something like: `01:23 of 24:56`.
  3481. *
  3482. *
  3483. * @param {string} string
  3484. * The string to localize and the key to lookup in the language files.
  3485. * @param {string[]} [tokens]
  3486. * If the current item has token replacements, provide the tokens here.
  3487. * @param {string} [defaultValue]
  3488. * Defaults to `string`. Can be a default value to use for token replacement
  3489. * if the lookup key is needed to be separate.
  3490. *
  3491. * @return {string}
  3492. * The localized string or if no localization exists the english string.
  3493. */
  3494. ;
  3495. _proto.localize = function localize(string, tokens, defaultValue) {
  3496. if (defaultValue === void 0) {
  3497. defaultValue = string;
  3498. }
  3499. var code = this.player_.language && this.player_.language();
  3500. var languages = this.player_.languages && this.player_.languages();
  3501. var language = languages && languages[code];
  3502. var primaryCode = code && code.split('-')[0];
  3503. var primaryLang = languages && languages[primaryCode];
  3504. var localizedString = defaultValue;
  3505. if (language && language[string]) {
  3506. localizedString = language[string];
  3507. } else if (primaryLang && primaryLang[string]) {
  3508. localizedString = primaryLang[string];
  3509. }
  3510. if (tokens) {
  3511. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3512. var value = tokens[index - 1];
  3513. var ret = value;
  3514. if (typeof value === 'undefined') {
  3515. ret = match;
  3516. }
  3517. return ret;
  3518. });
  3519. }
  3520. return localizedString;
  3521. }
  3522. /**
  3523. * Handles language change for the player in components. Should be overriden by sub-components.
  3524. *
  3525. * @abstract
  3526. */
  3527. ;
  3528. _proto.handleLanguagechange = function handleLanguagechange() {}
  3529. /**
  3530. * Return the `Component`s DOM element. This is where children get inserted.
  3531. * This will usually be the the same as the element returned in {@link Component#el}.
  3532. *
  3533. * @return {Element}
  3534. * The content element for this `Component`.
  3535. */
  3536. ;
  3537. _proto.contentEl = function contentEl() {
  3538. return this.contentEl_ || this.el_;
  3539. }
  3540. /**
  3541. * Get this `Component`s ID
  3542. *
  3543. * @return {string}
  3544. * The id of this `Component`
  3545. */
  3546. ;
  3547. _proto.id = function id() {
  3548. return this.id_;
  3549. }
  3550. /**
  3551. * Get the `Component`s name. The name gets used to reference the `Component`
  3552. * and is set during registration.
  3553. *
  3554. * @return {string}
  3555. * The name of this `Component`.
  3556. */
  3557. ;
  3558. _proto.name = function name() {
  3559. return this.name_;
  3560. }
  3561. /**
  3562. * Get an array of all child components
  3563. *
  3564. * @return {Array}
  3565. * The children
  3566. */
  3567. ;
  3568. _proto.children = function children() {
  3569. return this.children_;
  3570. }
  3571. /**
  3572. * Returns the child `Component` with the given `id`.
  3573. *
  3574. * @param {string} id
  3575. * The id of the child `Component` to get.
  3576. *
  3577. * @return {Component|undefined}
  3578. * The child `Component` with the given `id` or undefined.
  3579. */
  3580. ;
  3581. _proto.getChildById = function getChildById(id) {
  3582. return this.childIndex_[id];
  3583. }
  3584. /**
  3585. * Returns the child `Component` with the given `name`.
  3586. *
  3587. * @param {string} name
  3588. * The name of the child `Component` to get.
  3589. *
  3590. * @return {Component|undefined}
  3591. * The child `Component` with the given `name` or undefined.
  3592. */
  3593. ;
  3594. _proto.getChild = function getChild(name) {
  3595. if (!name) {
  3596. return;
  3597. }
  3598. return this.childNameIndex_[name];
  3599. }
  3600. /**
  3601. * Returns the descendant `Component` following the givent
  3602. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3603. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3604. * component and 'baz' on the 'bar' component and return undefined
  3605. * if any of those don't exist.
  3606. *
  3607. * @param {...string[]|...string} names
  3608. * The name of the child `Component` to get.
  3609. *
  3610. * @return {Component|undefined}
  3611. * The descendant `Component` following the given descendant
  3612. * `names` or undefined.
  3613. */
  3614. ;
  3615. _proto.getDescendant = function getDescendant() {
  3616. for (var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++) {
  3617. names[_key] = arguments[_key];
  3618. }
  3619. // flatten array argument into the main array
  3620. names = names.reduce(function (acc, n) {
  3621. return acc.concat(n);
  3622. }, []);
  3623. var currentChild = this;
  3624. for (var i = 0; i < names.length; i++) {
  3625. currentChild = currentChild.getChild(names[i]);
  3626. if (!currentChild || !currentChild.getChild) {
  3627. return;
  3628. }
  3629. }
  3630. return currentChild;
  3631. }
  3632. /**
  3633. * Add a child `Component` inside the current `Component`.
  3634. *
  3635. *
  3636. * @param {string|Component} child
  3637. * The name or instance of a child to add.
  3638. *
  3639. * @param {Object} [options={}]
  3640. * The key/value store of options that will get passed to children of
  3641. * the child.
  3642. *
  3643. * @param {number} [index=this.children_.length]
  3644. * The index to attempt to add a child into.
  3645. *
  3646. * @return {Component}
  3647. * The `Component` that gets added as a child. When using a string the
  3648. * `Component` will get created by this process.
  3649. */
  3650. ;
  3651. _proto.addChild = function addChild(child, options, index) {
  3652. if (options === void 0) {
  3653. options = {};
  3654. }
  3655. if (index === void 0) {
  3656. index = this.children_.length;
  3657. }
  3658. var component;
  3659. var componentName; // If child is a string, create component with options
  3660. if (typeof child === 'string') {
  3661. componentName = toTitleCase$1(child);
  3662. var componentClassName = options.componentClass || componentName; // Set name through options
  3663. options.name = componentName; // Create a new object & element for this controls set
  3664. // If there's no .player_, this is a player
  3665. var ComponentClass = Component.getComponent(componentClassName);
  3666. if (!ComponentClass) {
  3667. throw new Error("Component " + componentClassName + " does not exist");
  3668. } // data stored directly on the videojs object may be
  3669. // misidentified as a component to retain
  3670. // backwards-compatibility with 4.x. check to make sure the
  3671. // component class can be instantiated.
  3672. if (typeof ComponentClass !== 'function') {
  3673. return null;
  3674. }
  3675. component = new ComponentClass(this.player_ || this, options); // child is a component instance
  3676. } else {
  3677. component = child;
  3678. }
  3679. if (component.parentComponent_) {
  3680. component.parentComponent_.removeChild(component);
  3681. }
  3682. this.children_.splice(index, 0, component);
  3683. component.parentComponent_ = this;
  3684. if (typeof component.id === 'function') {
  3685. this.childIndex_[component.id()] = component;
  3686. } // If a name wasn't used to create the component, check if we can use the
  3687. // name function of the component
  3688. componentName = componentName || component.name && toTitleCase$1(component.name());
  3689. if (componentName) {
  3690. this.childNameIndex_[componentName] = component;
  3691. this.childNameIndex_[toLowerCase(componentName)] = component;
  3692. } // Add the UI object's element to the container div (box)
  3693. // Having an element is not required
  3694. if (typeof component.el === 'function' && component.el()) {
  3695. // If inserting before a component, insert before that component's element
  3696. var refNode = null;
  3697. if (this.children_[index + 1]) {
  3698. // Most children are components, but the video tech is an HTML element
  3699. if (this.children_[index + 1].el_) {
  3700. refNode = this.children_[index + 1].el_;
  3701. } else if (isEl(this.children_[index + 1])) {
  3702. refNode = this.children_[index + 1];
  3703. }
  3704. }
  3705. this.contentEl().insertBefore(component.el(), refNode);
  3706. } // Return so it can stored on parent object if desired.
  3707. return component;
  3708. }
  3709. /**
  3710. * Remove a child `Component` from this `Component`s list of children. Also removes
  3711. * the child `Component`s element from this `Component`s element.
  3712. *
  3713. * @param {Component} component
  3714. * The child `Component` to remove.
  3715. */
  3716. ;
  3717. _proto.removeChild = function removeChild(component) {
  3718. if (typeof component === 'string') {
  3719. component = this.getChild(component);
  3720. }
  3721. if (!component || !this.children_) {
  3722. return;
  3723. }
  3724. var childFound = false;
  3725. for (var i = this.children_.length - 1; i >= 0; i--) {
  3726. if (this.children_[i] === component) {
  3727. childFound = true;
  3728. this.children_.splice(i, 1);
  3729. break;
  3730. }
  3731. }
  3732. if (!childFound) {
  3733. return;
  3734. }
  3735. component.parentComponent_ = null;
  3736. this.childIndex_[component.id()] = null;
  3737. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3738. this.childNameIndex_[toLowerCase(component.name())] = null;
  3739. var compEl = component.el();
  3740. if (compEl && compEl.parentNode === this.contentEl()) {
  3741. this.contentEl().removeChild(component.el());
  3742. }
  3743. }
  3744. /**
  3745. * Add and initialize default child `Component`s based upon options.
  3746. */
  3747. ;
  3748. _proto.initChildren = function initChildren() {
  3749. var _this2 = this;
  3750. var children = this.options_.children;
  3751. if (children) {
  3752. // `this` is `parent`
  3753. var parentOptions = this.options_;
  3754. var handleAdd = function handleAdd(child) {
  3755. var name = child.name;
  3756. var opts = child.opts; // Allow options for children to be set at the parent options
  3757. // e.g. videojs(id, { controlBar: false });
  3758. // instead of videojs(id, { children: { controlBar: false });
  3759. if (parentOptions[name] !== undefined) {
  3760. opts = parentOptions[name];
  3761. } // Allow for disabling default components
  3762. // e.g. options['children']['posterImage'] = false
  3763. if (opts === false) {
  3764. return;
  3765. } // Allow options to be passed as a simple boolean if no configuration
  3766. // is necessary.
  3767. if (opts === true) {
  3768. opts = {};
  3769. } // We also want to pass the original player options
  3770. // to each component as well so they don't need to
  3771. // reach back into the player for options later.
  3772. opts.playerOptions = _this2.options_.playerOptions; // Create and add the child component.
  3773. // Add a direct reference to the child by name on the parent instance.
  3774. // If two of the same component are used, different names should be supplied
  3775. // for each
  3776. var newChild = _this2.addChild(name, opts);
  3777. if (newChild) {
  3778. _this2[name] = newChild;
  3779. }
  3780. }; // Allow for an array of children details to passed in the options
  3781. var workingChildren;
  3782. var Tech = Component.getComponent('Tech');
  3783. if (Array.isArray(children)) {
  3784. workingChildren = children;
  3785. } else {
  3786. workingChildren = Object.keys(children);
  3787. }
  3788. workingChildren // children that are in this.options_ but also in workingChildren would
  3789. // give us extra children we do not want. So, we want to filter them out.
  3790. .concat(Object.keys(this.options_).filter(function (child) {
  3791. return !workingChildren.some(function (wchild) {
  3792. if (typeof wchild === 'string') {
  3793. return child === wchild;
  3794. }
  3795. return child === wchild.name;
  3796. });
  3797. })).map(function (child) {
  3798. var name;
  3799. var opts;
  3800. if (typeof child === 'string') {
  3801. name = child;
  3802. opts = children[name] || _this2.options_[name] || {};
  3803. } else {
  3804. name = child.name;
  3805. opts = child;
  3806. }
  3807. return {
  3808. name: name,
  3809. opts: opts
  3810. };
  3811. }).filter(function (child) {
  3812. // we have to make sure that child.name isn't in the techOrder since
  3813. // techs are registerd as Components but can't aren't compatible
  3814. // See https://github.com/videojs/video.js/issues/2772
  3815. var c = Component.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3816. return c && !Tech.isTech(c);
  3817. }).forEach(handleAdd);
  3818. }
  3819. }
  3820. /**
  3821. * Builds the default DOM class name. Should be overriden by sub-components.
  3822. *
  3823. * @return {string}
  3824. * The DOM class name for this object.
  3825. *
  3826. * @abstract
  3827. */
  3828. ;
  3829. _proto.buildCSSClass = function buildCSSClass() {
  3830. // Child classes can include a function that does:
  3831. // return 'CLASS NAME' + this._super();
  3832. return '';
  3833. }
  3834. /**
  3835. * Bind a listener to the component's ready state.
  3836. * Different from event listeners in that if the ready event has already happened
  3837. * it will trigger the function immediately.
  3838. *
  3839. * @return {Component}
  3840. * Returns itself; method can be chained.
  3841. */
  3842. ;
  3843. _proto.ready = function ready(fn, sync) {
  3844. if (sync === void 0) {
  3845. sync = false;
  3846. }
  3847. if (!fn) {
  3848. return;
  3849. }
  3850. if (!this.isReady_) {
  3851. this.readyQueue_ = this.readyQueue_ || [];
  3852. this.readyQueue_.push(fn);
  3853. return;
  3854. }
  3855. if (sync) {
  3856. fn.call(this);
  3857. } else {
  3858. // Call the function asynchronously by default for consistency
  3859. this.setTimeout(fn, 1);
  3860. }
  3861. }
  3862. /**
  3863. * Trigger all the ready listeners for this `Component`.
  3864. *
  3865. * @fires Component#ready
  3866. */
  3867. ;
  3868. _proto.triggerReady = function triggerReady() {
  3869. this.isReady_ = true; // Ensure ready is triggered asynchronously
  3870. this.setTimeout(function () {
  3871. var readyQueue = this.readyQueue_; // Reset Ready Queue
  3872. this.readyQueue_ = [];
  3873. if (readyQueue && readyQueue.length > 0) {
  3874. readyQueue.forEach(function (fn) {
  3875. fn.call(this);
  3876. }, this);
  3877. } // Allow for using event listeners also
  3878. /**
  3879. * Triggered when a `Component` is ready.
  3880. *
  3881. * @event Component#ready
  3882. * @type {EventTarget~Event}
  3883. */
  3884. this.trigger('ready');
  3885. }, 1);
  3886. }
  3887. /**
  3888. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  3889. * `contentEl()` or another custom context.
  3890. *
  3891. * @param {string} selector
  3892. * A valid CSS selector, which will be passed to `querySelector`.
  3893. *
  3894. * @param {Element|string} [context=this.contentEl()]
  3895. * A DOM element within which to query. Can also be a selector string in
  3896. * which case the first matching element will get used as context. If
  3897. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3898. * nothing it falls back to `document`.
  3899. *
  3900. * @return {Element|null}
  3901. * the dom element that was found, or null
  3902. *
  3903. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3904. */
  3905. ;
  3906. _proto.$ = function $$1(selector, context) {
  3907. return $(selector, context || this.contentEl());
  3908. }
  3909. /**
  3910. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  3911. * `contentEl()` or another custom context.
  3912. *
  3913. * @param {string} selector
  3914. * A valid CSS selector, which will be passed to `querySelectorAll`.
  3915. *
  3916. * @param {Element|string} [context=this.contentEl()]
  3917. * A DOM element within which to query. Can also be a selector string in
  3918. * which case the first matching element will get used as context. If
  3919. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  3920. * nothing it falls back to `document`.
  3921. *
  3922. * @return {NodeList}
  3923. * a list of dom elements that were found
  3924. *
  3925. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  3926. */
  3927. ;
  3928. _proto.$$ = function $$$1(selector, context) {
  3929. return $$(selector, context || this.contentEl());
  3930. }
  3931. /**
  3932. * Check if a component's element has a CSS class name.
  3933. *
  3934. * @param {string} classToCheck
  3935. * CSS class name to check.
  3936. *
  3937. * @return {boolean}
  3938. * - True if the `Component` has the class.
  3939. * - False if the `Component` does not have the class`
  3940. */
  3941. ;
  3942. _proto.hasClass = function hasClass$1(classToCheck) {
  3943. return hasClass(this.el_, classToCheck);
  3944. }
  3945. /**
  3946. * Add a CSS class name to the `Component`s element.
  3947. *
  3948. * @param {string} classToAdd
  3949. * CSS class name to add
  3950. */
  3951. ;
  3952. _proto.addClass = function addClass$1(classToAdd) {
  3953. addClass(this.el_, classToAdd);
  3954. }
  3955. /**
  3956. * Remove a CSS class name from the `Component`s element.
  3957. *
  3958. * @param {string} classToRemove
  3959. * CSS class name to remove
  3960. */
  3961. ;
  3962. _proto.removeClass = function removeClass$1(classToRemove) {
  3963. removeClass(this.el_, classToRemove);
  3964. }
  3965. /**
  3966. * Add or remove a CSS class name from the component's element.
  3967. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  3968. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  3969. *
  3970. * @param {string} classToToggle
  3971. * The class to add or remove based on (@link Component#hasClass}
  3972. *
  3973. * @param {boolean|Dom~predicate} [predicate]
  3974. * An {@link Dom~predicate} function or a boolean
  3975. */
  3976. ;
  3977. _proto.toggleClass = function toggleClass$1(classToToggle, predicate) {
  3978. toggleClass(this.el_, classToToggle, predicate);
  3979. }
  3980. /**
  3981. * Show the `Component`s element if it is hidden by removing the
  3982. * 'vjs-hidden' class name from it.
  3983. */
  3984. ;
  3985. _proto.show = function show() {
  3986. this.removeClass('vjs-hidden');
  3987. }
  3988. /**
  3989. * Hide the `Component`s element if it is currently showing by adding the
  3990. * 'vjs-hidden` class name to it.
  3991. */
  3992. ;
  3993. _proto.hide = function hide() {
  3994. this.addClass('vjs-hidden');
  3995. }
  3996. /**
  3997. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  3998. * class name to it. Used during fadeIn/fadeOut.
  3999. *
  4000. * @private
  4001. */
  4002. ;
  4003. _proto.lockShowing = function lockShowing() {
  4004. this.addClass('vjs-lock-showing');
  4005. }
  4006. /**
  4007. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4008. * class name from it. Used during fadeIn/fadeOut.
  4009. *
  4010. * @private
  4011. */
  4012. ;
  4013. _proto.unlockShowing = function unlockShowing() {
  4014. this.removeClass('vjs-lock-showing');
  4015. }
  4016. /**
  4017. * Get the value of an attribute on the `Component`s element.
  4018. *
  4019. * @param {string} attribute
  4020. * Name of the attribute to get the value from.
  4021. *
  4022. * @return {string|null}
  4023. * - The value of the attribute that was asked for.
  4024. * - Can be an empty string on some browsers if the attribute does not exist
  4025. * or has no value
  4026. * - Most browsers will return null if the attibute does not exist or has
  4027. * no value.
  4028. *
  4029. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4030. */
  4031. ;
  4032. _proto.getAttribute = function getAttribute$1(attribute) {
  4033. return getAttribute(this.el_, attribute);
  4034. }
  4035. /**
  4036. * Set the value of an attribute on the `Component`'s element
  4037. *
  4038. * @param {string} attribute
  4039. * Name of the attribute to set.
  4040. *
  4041. * @param {string} value
  4042. * Value to set the attribute to.
  4043. *
  4044. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4045. */
  4046. ;
  4047. _proto.setAttribute = function setAttribute$1(attribute, value) {
  4048. setAttribute(this.el_, attribute, value);
  4049. }
  4050. /**
  4051. * Remove an attribute from the `Component`s element.
  4052. *
  4053. * @param {string} attribute
  4054. * Name of the attribute to remove.
  4055. *
  4056. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4057. */
  4058. ;
  4059. _proto.removeAttribute = function removeAttribute$1(attribute) {
  4060. removeAttribute(this.el_, attribute);
  4061. }
  4062. /**
  4063. * Get or set the width of the component based upon the CSS styles.
  4064. * See {@link Component#dimension} for more detailed information.
  4065. *
  4066. * @param {number|string} [num]
  4067. * The width that you want to set postfixed with '%', 'px' or nothing.
  4068. *
  4069. * @param {boolean} [skipListeners]
  4070. * Skip the componentresize event trigger
  4071. *
  4072. * @return {number|string}
  4073. * The width when getting, zero if there is no width. Can be a string
  4074. * postpixed with '%' or 'px'.
  4075. */
  4076. ;
  4077. _proto.width = function width(num, skipListeners) {
  4078. return this.dimension('width', num, skipListeners);
  4079. }
  4080. /**
  4081. * Get or set the height of the component based upon the CSS styles.
  4082. * See {@link Component#dimension} for more detailed information.
  4083. *
  4084. * @param {number|string} [num]
  4085. * The height that you want to set postfixed with '%', 'px' or nothing.
  4086. *
  4087. * @param {boolean} [skipListeners]
  4088. * Skip the componentresize event trigger
  4089. *
  4090. * @return {number|string}
  4091. * The width when getting, zero if there is no width. Can be a string
  4092. * postpixed with '%' or 'px'.
  4093. */
  4094. ;
  4095. _proto.height = function height(num, skipListeners) {
  4096. return this.dimension('height', num, skipListeners);
  4097. }
  4098. /**
  4099. * Set both the width and height of the `Component` element at the same time.
  4100. *
  4101. * @param {number|string} width
  4102. * Width to set the `Component`s element to.
  4103. *
  4104. * @param {number|string} height
  4105. * Height to set the `Component`s element to.
  4106. */
  4107. ;
  4108. _proto.dimensions = function dimensions(width, height) {
  4109. // Skip componentresize listeners on width for optimization
  4110. this.width(width, true);
  4111. this.height(height);
  4112. }
  4113. /**
  4114. * Get or set width or height of the `Component` element. This is the shared code
  4115. * for the {@link Component#width} and {@link Component#height}.
  4116. *
  4117. * Things to know:
  4118. * - If the width or height in an number this will return the number postfixed with 'px'.
  4119. * - If the width/height is a percent this will return the percent postfixed with '%'
  4120. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4121. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4122. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4123. * for more information
  4124. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4125. * and {@link {Component#currentHeight}
  4126. *
  4127. * @fires Component#componentresize
  4128. *
  4129. * @param {string} widthOrHeight
  4130. 8 'width' or 'height'
  4131. *
  4132. * @param {number|string} [num]
  4133. 8 New dimension
  4134. *
  4135. * @param {boolean} [skipListeners]
  4136. * Skip componentresize event trigger
  4137. *
  4138. * @return {number}
  4139. * The dimension when getting or 0 if unset
  4140. */
  4141. ;
  4142. _proto.dimension = function dimension(widthOrHeight, num, skipListeners) {
  4143. if (num !== undefined) {
  4144. // Set to zero if null or literally NaN (NaN !== NaN)
  4145. if (num === null || num !== num) {
  4146. num = 0;
  4147. } // Check if using css width/height (% or px) and adjust
  4148. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4149. this.el_.style[widthOrHeight] = num;
  4150. } else if (num === 'auto') {
  4151. this.el_.style[widthOrHeight] = '';
  4152. } else {
  4153. this.el_.style[widthOrHeight] = num + 'px';
  4154. } // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4155. if (!skipListeners) {
  4156. /**
  4157. * Triggered when a component is resized.
  4158. *
  4159. * @event Component#componentresize
  4160. * @type {EventTarget~Event}
  4161. */
  4162. this.trigger('componentresize');
  4163. }
  4164. return;
  4165. } // Not setting a value, so getting it
  4166. // Make sure element exists
  4167. if (!this.el_) {
  4168. return 0;
  4169. } // Get dimension value from style
  4170. var val = this.el_.style[widthOrHeight];
  4171. var pxIndex = val.indexOf('px');
  4172. if (pxIndex !== -1) {
  4173. // Return the pixel value with no 'px'
  4174. return parseInt(val.slice(0, pxIndex), 10);
  4175. } // No px so using % or no style was set, so falling back to offsetWidth/height
  4176. // If component has display:none, offset will return 0
  4177. // TODO: handle display:none and no dimension style using px
  4178. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4179. }
  4180. /**
  4181. * Get the computed width or the height of the component's element.
  4182. *
  4183. * Uses `window.getComputedStyle`.
  4184. *
  4185. * @param {string} widthOrHeight
  4186. * A string containing 'width' or 'height'. Whichever one you want to get.
  4187. *
  4188. * @return {number}
  4189. * The dimension that gets asked for or 0 if nothing was set
  4190. * for that dimension.
  4191. */
  4192. ;
  4193. _proto.currentDimension = function currentDimension(widthOrHeight) {
  4194. var computedWidthOrHeight = 0;
  4195. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4196. throw new Error('currentDimension only accepts width or height value');
  4197. }
  4198. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight); // remove 'px' from variable and parse as integer
  4199. computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying
  4200. // and we want to check the offset values.
  4201. // This code also runs wherever getComputedStyle doesn't exist.
  4202. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4203. var rule = "offset" + toTitleCase$1(widthOrHeight);
  4204. computedWidthOrHeight = this.el_[rule];
  4205. }
  4206. return computedWidthOrHeight;
  4207. }
  4208. /**
  4209. * An object that contains width and height values of the `Component`s
  4210. * computed style. Uses `window.getComputedStyle`.
  4211. *
  4212. * @typedef {Object} Component~DimensionObject
  4213. *
  4214. * @property {number} width
  4215. * The width of the `Component`s computed style.
  4216. *
  4217. * @property {number} height
  4218. * The height of the `Component`s computed style.
  4219. */
  4220. /**
  4221. * Get an object that contains computed width and height values of the
  4222. * component's element.
  4223. *
  4224. * Uses `window.getComputedStyle`.
  4225. *
  4226. * @return {Component~DimensionObject}
  4227. * The computed dimensions of the component's element.
  4228. */
  4229. ;
  4230. _proto.currentDimensions = function currentDimensions() {
  4231. return {
  4232. width: this.currentDimension('width'),
  4233. height: this.currentDimension('height')
  4234. };
  4235. }
  4236. /**
  4237. * Get the computed width of the component's element.
  4238. *
  4239. * Uses `window.getComputedStyle`.
  4240. *
  4241. * @return {number}
  4242. * The computed width of the component's element.
  4243. */
  4244. ;
  4245. _proto.currentWidth = function currentWidth() {
  4246. return this.currentDimension('width');
  4247. }
  4248. /**
  4249. * Get the computed height of the component's element.
  4250. *
  4251. * Uses `window.getComputedStyle`.
  4252. *
  4253. * @return {number}
  4254. * The computed height of the component's element.
  4255. */
  4256. ;
  4257. _proto.currentHeight = function currentHeight() {
  4258. return this.currentDimension('height');
  4259. }
  4260. /**
  4261. * Set the focus to this component
  4262. */
  4263. ;
  4264. _proto.focus = function focus() {
  4265. this.el_.focus();
  4266. }
  4267. /**
  4268. * Remove the focus from this component
  4269. */
  4270. ;
  4271. _proto.blur = function blur() {
  4272. this.el_.blur();
  4273. }
  4274. /**
  4275. * When this Component receives a `keydown` event which it does not process,
  4276. * it passes the event to the Player for handling.
  4277. *
  4278. * @param {EventTarget~Event} event
  4279. * The `keydown` event that caused this function to be called.
  4280. */
  4281. ;
  4282. _proto.handleKeyDown = function handleKeyDown(event) {
  4283. if (this.player_) {
  4284. // We only stop propagation here because we want unhandled events to fall
  4285. // back to the browser. Exclude Tab for focus trapping.
  4286. if (!keycode__default['default'].isEventKey(event, 'Tab')) {
  4287. event.stopPropagation();
  4288. }
  4289. this.player_.handleKeyDown(event);
  4290. }
  4291. }
  4292. /**
  4293. * Many components used to have a `handleKeyPress` method, which was poorly
  4294. * named because it listened to a `keydown` event. This method name now
  4295. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4296. * will not see their method calls stop working.
  4297. *
  4298. * @param {EventTarget~Event} event
  4299. * The event that caused this function to be called.
  4300. */
  4301. ;
  4302. _proto.handleKeyPress = function handleKeyPress(event) {
  4303. this.handleKeyDown(event);
  4304. }
  4305. /**
  4306. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4307. * support toggling the controls through a tap on the video. They get enabled
  4308. * because every sub-component would have extra overhead otherwise.
  4309. *
  4310. * @private
  4311. * @fires Component#tap
  4312. * @listens Component#touchstart
  4313. * @listens Component#touchmove
  4314. * @listens Component#touchleave
  4315. * @listens Component#touchcancel
  4316. * @listens Component#touchend
  4317. */
  4318. ;
  4319. _proto.emitTapEvents = function emitTapEvents() {
  4320. // Track the start time so we can determine how long the touch lasted
  4321. var touchStart = 0;
  4322. var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap
  4323. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4324. // so 10 seems like a nice, round number.
  4325. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap
  4326. var touchTimeThreshold = 200;
  4327. var couldBeTap;
  4328. this.on('touchstart', function (event) {
  4329. // If more than one finger, don't consider treating this as a click
  4330. if (event.touches.length === 1) {
  4331. // Copy pageX/pageY from the object
  4332. firstTouch = {
  4333. pageX: event.touches[0].pageX,
  4334. pageY: event.touches[0].pageY
  4335. }; // Record start time so we can detect a tap vs. "touch and hold"
  4336. touchStart = window__default['default'].performance.now(); // Reset couldBeTap tracking
  4337. couldBeTap = true;
  4338. }
  4339. });
  4340. this.on('touchmove', function (event) {
  4341. // If more than one finger, don't consider treating this as a click
  4342. if (event.touches.length > 1) {
  4343. couldBeTap = false;
  4344. } else if (firstTouch) {
  4345. // Some devices will throw touchmoves for all but the slightest of taps.
  4346. // So, if we moved only a small distance, this could still be a tap
  4347. var xdiff = event.touches[0].pageX - firstTouch.pageX;
  4348. var ydiff = event.touches[0].pageY - firstTouch.pageY;
  4349. var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4350. if (touchDistance > tapMovementThreshold) {
  4351. couldBeTap = false;
  4352. }
  4353. }
  4354. });
  4355. var noTap = function noTap() {
  4356. couldBeTap = false;
  4357. }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4358. this.on('touchleave', noTap);
  4359. this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate
  4360. // event
  4361. this.on('touchend', function (event) {
  4362. firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen
  4363. if (couldBeTap === true) {
  4364. // Measure how long the touch lasted
  4365. var touchTime = window__default['default'].performance.now() - touchStart; // Make sure the touch was less than the threshold to be considered a tap
  4366. if (touchTime < touchTimeThreshold) {
  4367. // Don't let browser turn this into a click
  4368. event.preventDefault();
  4369. /**
  4370. * Triggered when a `Component` is tapped.
  4371. *
  4372. * @event Component#tap
  4373. * @type {EventTarget~Event}
  4374. */
  4375. this.trigger('tap'); // It may be good to copy the touchend event object and change the
  4376. // type to tap, if the other event properties aren't exact after
  4377. // Events.fixEvent runs (e.g. event.target)
  4378. }
  4379. }
  4380. });
  4381. }
  4382. /**
  4383. * This function reports user activity whenever touch events happen. This can get
  4384. * turned off by any sub-components that wants touch events to act another way.
  4385. *
  4386. * Report user touch activity when touch events occur. User activity gets used to
  4387. * determine when controls should show/hide. It is simple when it comes to mouse
  4388. * events, because any mouse event should show the controls. So we capture mouse
  4389. * events that bubble up to the player and report activity when that happens.
  4390. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4391. * controls. So touch events can't help us at the player level either.
  4392. *
  4393. * User activity gets checked asynchronously. So what could happen is a tap event
  4394. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4395. * the player. Which, if it reported user activity, would turn the controls right
  4396. * back on. We also don't want to completely block touch events from bubbling up.
  4397. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4398. * controls back on.
  4399. *
  4400. * @listens Component#touchstart
  4401. * @listens Component#touchmove
  4402. * @listens Component#touchend
  4403. * @listens Component#touchcancel
  4404. */
  4405. ;
  4406. _proto.enableTouchActivity = function enableTouchActivity() {
  4407. // Don't continue if the root player doesn't support reporting user activity
  4408. if (!this.player() || !this.player().reportUserActivity) {
  4409. return;
  4410. } // listener for reporting that the user is active
  4411. var report = bind(this.player(), this.player().reportUserActivity);
  4412. var touchHolding;
  4413. this.on('touchstart', function () {
  4414. report(); // For as long as the they are touching the device or have their mouse down,
  4415. // we consider them active even if they're not moving their finger or mouse.
  4416. // So we want to continue to update that they are active
  4417. this.clearInterval(touchHolding); // report at the same interval as activityCheck
  4418. touchHolding = this.setInterval(report, 250);
  4419. });
  4420. var touchEnd = function touchEnd(event) {
  4421. report(); // stop the interval that maintains activity if the touch is holding
  4422. this.clearInterval(touchHolding);
  4423. };
  4424. this.on('touchmove', report);
  4425. this.on('touchend', touchEnd);
  4426. this.on('touchcancel', touchEnd);
  4427. }
  4428. /**
  4429. * A callback that has no parameters and is bound into `Component`s context.
  4430. *
  4431. * @callback Component~GenericCallback
  4432. * @this Component
  4433. */
  4434. /**
  4435. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4436. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4437. * instead though:
  4438. * 1. It gets cleared via {@link Component#clearTimeout} when
  4439. * {@link Component#dispose} gets called.
  4440. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4441. *
  4442. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4443. * will cause its dispose listener not to get cleaned up! Please use
  4444. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4445. *
  4446. * @param {Component~GenericCallback} fn
  4447. * The function that will be run after `timeout`.
  4448. *
  4449. * @param {number} timeout
  4450. * Timeout in milliseconds to delay before executing the specified function.
  4451. *
  4452. * @return {number}
  4453. * Returns a timeout ID that gets used to identify the timeout. It can also
  4454. * get used in {@link Component#clearTimeout} to clear the timeout that
  4455. * was set.
  4456. *
  4457. * @listens Component#dispose
  4458. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4459. */
  4460. ;
  4461. _proto.setTimeout = function setTimeout(fn, timeout) {
  4462. var _this3 = this;
  4463. // declare as variables so they are properly available in timeout function
  4464. // eslint-disable-next-line
  4465. var timeoutId;
  4466. fn = bind(this, fn);
  4467. this.clearTimersOnDispose_();
  4468. timeoutId = window__default['default'].setTimeout(function () {
  4469. if (_this3.setTimeoutIds_.has(timeoutId)) {
  4470. _this3.setTimeoutIds_["delete"](timeoutId);
  4471. }
  4472. fn();
  4473. }, timeout);
  4474. this.setTimeoutIds_.add(timeoutId);
  4475. return timeoutId;
  4476. }
  4477. /**
  4478. * Clears a timeout that gets created via `window.setTimeout` or
  4479. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4480. * use this function instead of `window.clearTimout`. If you don't your dispose
  4481. * listener will not get cleaned up until {@link Component#dispose}!
  4482. *
  4483. * @param {number} timeoutId
  4484. * The id of the timeout to clear. The return value of
  4485. * {@link Component#setTimeout} or `window.setTimeout`.
  4486. *
  4487. * @return {number}
  4488. * Returns the timeout id that was cleared.
  4489. *
  4490. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4491. */
  4492. ;
  4493. _proto.clearTimeout = function clearTimeout(timeoutId) {
  4494. if (this.setTimeoutIds_.has(timeoutId)) {
  4495. this.setTimeoutIds_["delete"](timeoutId);
  4496. window__default['default'].clearTimeout(timeoutId);
  4497. }
  4498. return timeoutId;
  4499. }
  4500. /**
  4501. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4502. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4503. * 1. It gets cleared via {@link Component#clearInterval} when
  4504. * {@link Component#dispose} gets called.
  4505. * 2. The function callback will be a {@link Component~GenericCallback}
  4506. *
  4507. * @param {Component~GenericCallback} fn
  4508. * The function to run every `x` seconds.
  4509. *
  4510. * @param {number} interval
  4511. * Execute the specified function every `x` milliseconds.
  4512. *
  4513. * @return {number}
  4514. * Returns an id that can be used to identify the interval. It can also be be used in
  4515. * {@link Component#clearInterval} to clear the interval.
  4516. *
  4517. * @listens Component#dispose
  4518. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4519. */
  4520. ;
  4521. _proto.setInterval = function setInterval(fn, interval) {
  4522. fn = bind(this, fn);
  4523. this.clearTimersOnDispose_();
  4524. var intervalId = window__default['default'].setInterval(fn, interval);
  4525. this.setIntervalIds_.add(intervalId);
  4526. return intervalId;
  4527. }
  4528. /**
  4529. * Clears an interval that gets created via `window.setInterval` or
  4530. * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval}
  4531. * use this function instead of `window.clearInterval`. If you don't your dispose
  4532. * listener will not get cleaned up until {@link Component#dispose}!
  4533. *
  4534. * @param {number} intervalId
  4535. * The id of the interval to clear. The return value of
  4536. * {@link Component#setInterval} or `window.setInterval`.
  4537. *
  4538. * @return {number}
  4539. * Returns the interval id that was cleared.
  4540. *
  4541. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4542. */
  4543. ;
  4544. _proto.clearInterval = function clearInterval(intervalId) {
  4545. if (this.setIntervalIds_.has(intervalId)) {
  4546. this.setIntervalIds_["delete"](intervalId);
  4547. window__default['default'].clearInterval(intervalId);
  4548. }
  4549. return intervalId;
  4550. }
  4551. /**
  4552. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4553. * with a few extra bonuses:
  4554. *
  4555. * - Supports browsers that do not support rAF by falling back to
  4556. * {@link Component#setTimeout}.
  4557. *
  4558. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4559. * bound to the component).
  4560. *
  4561. * - Automatic cancellation of the rAF callback is handled if the component
  4562. * is disposed before it is called.
  4563. *
  4564. * @param {Component~GenericCallback} fn
  4565. * A function that will be bound to this component and executed just
  4566. * before the browser's next repaint.
  4567. *
  4568. * @return {number}
  4569. * Returns an rAF ID that gets used to identify the timeout. It can
  4570. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4571. * the animation frame callback.
  4572. *
  4573. * @listens Component#dispose
  4574. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4575. */
  4576. ;
  4577. _proto.requestAnimationFrame = function requestAnimationFrame(fn) {
  4578. var _this4 = this;
  4579. // Fall back to using a timer.
  4580. if (!this.supportsRaf_) {
  4581. return this.setTimeout(fn, 1000 / 60);
  4582. }
  4583. this.clearTimersOnDispose_(); // declare as variables so they are properly available in rAF function
  4584. // eslint-disable-next-line
  4585. var id;
  4586. fn = bind(this, fn);
  4587. id = window__default['default'].requestAnimationFrame(function () {
  4588. if (_this4.rafIds_.has(id)) {
  4589. _this4.rafIds_["delete"](id);
  4590. }
  4591. fn();
  4592. });
  4593. this.rafIds_.add(id);
  4594. return id;
  4595. }
  4596. /**
  4597. * Request an animation frame, but only one named animation
  4598. * frame will be queued. Another will never be added until
  4599. * the previous one finishes.
  4600. *
  4601. * @param {string} name
  4602. * The name to give this requestAnimationFrame
  4603. *
  4604. * @param {Component~GenericCallback} fn
  4605. * A function that will be bound to this component and executed just
  4606. * before the browser's next repaint.
  4607. */
  4608. ;
  4609. _proto.requestNamedAnimationFrame = function requestNamedAnimationFrame(name, fn) {
  4610. var _this5 = this;
  4611. if (this.namedRafs_.has(name)) {
  4612. return;
  4613. }
  4614. this.clearTimersOnDispose_();
  4615. fn = bind(this, fn);
  4616. var id = this.requestAnimationFrame(function () {
  4617. fn();
  4618. if (_this5.namedRafs_.has(name)) {
  4619. _this5.namedRafs_["delete"](name);
  4620. }
  4621. });
  4622. this.namedRafs_.set(name, id);
  4623. return name;
  4624. }
  4625. /**
  4626. * Cancels a current named animation frame if it exists.
  4627. *
  4628. * @param {string} name
  4629. * The name of the requestAnimationFrame to cancel.
  4630. */
  4631. ;
  4632. _proto.cancelNamedAnimationFrame = function cancelNamedAnimationFrame(name) {
  4633. if (!this.namedRafs_.has(name)) {
  4634. return;
  4635. }
  4636. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4637. this.namedRafs_["delete"](name);
  4638. }
  4639. /**
  4640. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4641. * (rAF).
  4642. *
  4643. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4644. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4645. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4646. *
  4647. * @param {number} id
  4648. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4649. *
  4650. * @return {number}
  4651. * Returns the rAF ID that was cleared.
  4652. *
  4653. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4654. */
  4655. ;
  4656. _proto.cancelAnimationFrame = function cancelAnimationFrame(id) {
  4657. // Fall back to using a timer.
  4658. if (!this.supportsRaf_) {
  4659. return this.clearTimeout(id);
  4660. }
  4661. if (this.rafIds_.has(id)) {
  4662. this.rafIds_["delete"](id);
  4663. window__default['default'].cancelAnimationFrame(id);
  4664. }
  4665. return id;
  4666. }
  4667. /**
  4668. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4669. * and `setInterval`, clearing on dispose.
  4670. *
  4671. * > Previously each timer added and removed dispose listeners on it's own.
  4672. * For better performance it was decided to batch them all, and use `Set`s
  4673. * to track outstanding timer ids.
  4674. *
  4675. * @private
  4676. */
  4677. ;
  4678. _proto.clearTimersOnDispose_ = function clearTimersOnDispose_() {
  4679. var _this6 = this;
  4680. if (this.clearingTimersOnDispose_) {
  4681. return;
  4682. }
  4683. this.clearingTimersOnDispose_ = true;
  4684. this.one('dispose', function () {
  4685. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(function (_ref) {
  4686. var idName = _ref[0],
  4687. cancelName = _ref[1];
  4688. // for a `Set` key will actually be the value again
  4689. // so forEach((val, val) =>` but for maps we want to use
  4690. // the key.
  4691. _this6[idName].forEach(function (val, key) {
  4692. return _this6[cancelName](key);
  4693. });
  4694. });
  4695. _this6.clearingTimersOnDispose_ = false;
  4696. });
  4697. }
  4698. /**
  4699. * Register a `Component` with `videojs` given the name and the component.
  4700. *
  4701. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4702. * should be registered using {@link Tech.registerTech} or
  4703. * {@link videojs:videojs.registerTech}.
  4704. *
  4705. * > NOTE: This function can also be seen on videojs as
  4706. * {@link videojs:videojs.registerComponent}.
  4707. *
  4708. * @param {string} name
  4709. * The name of the `Component` to register.
  4710. *
  4711. * @param {Component} ComponentToRegister
  4712. * The `Component` class to register.
  4713. *
  4714. * @return {Component}
  4715. * The `Component` that was registered.
  4716. */
  4717. ;
  4718. Component.registerComponent = function registerComponent(name, ComponentToRegister) {
  4719. if (typeof name !== 'string' || !name) {
  4720. throw new Error("Illegal component name, \"" + name + "\"; must be a non-empty string.");
  4721. }
  4722. var Tech = Component.getComponent('Tech'); // We need to make sure this check is only done if Tech has been registered.
  4723. var isTech = Tech && Tech.isTech(ComponentToRegister);
  4724. var isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4725. if (isTech || !isComp) {
  4726. var reason;
  4727. if (isTech) {
  4728. reason = 'techs must be registered using Tech.registerTech()';
  4729. } else {
  4730. reason = 'must be a Component subclass';
  4731. }
  4732. throw new Error("Illegal component, \"" + name + "\"; " + reason + ".");
  4733. }
  4734. name = toTitleCase$1(name);
  4735. if (!Component.components_) {
  4736. Component.components_ = {};
  4737. }
  4738. var Player = Component.getComponent('Player');
  4739. if (name === 'Player' && Player && Player.players) {
  4740. var players = Player.players;
  4741. var playerNames = Object.keys(players); // If we have players that were disposed, then their name will still be
  4742. // in Players.players. So, we must loop through and verify that the value
  4743. // for each item is not null. This allows registration of the Player component
  4744. // after all players have been disposed or before any were created.
  4745. if (players && playerNames.length > 0 && playerNames.map(function (pname) {
  4746. return players[pname];
  4747. }).every(Boolean)) {
  4748. throw new Error('Can not register Player component after player has been created.');
  4749. }
  4750. }
  4751. Component.components_[name] = ComponentToRegister;
  4752. Component.components_[toLowerCase(name)] = ComponentToRegister;
  4753. return ComponentToRegister;
  4754. }
  4755. /**
  4756. * Get a `Component` based on the name it was registered with.
  4757. *
  4758. * @param {string} name
  4759. * The Name of the component to get.
  4760. *
  4761. * @return {Component}
  4762. * The `Component` that got registered under the given name.
  4763. */
  4764. ;
  4765. Component.getComponent = function getComponent(name) {
  4766. if (!name || !Component.components_) {
  4767. return;
  4768. }
  4769. return Component.components_[name];
  4770. };
  4771. return Component;
  4772. }();
  4773. /**
  4774. * Whether or not this component supports `requestAnimationFrame`.
  4775. *
  4776. * This is exposed primarily for testing purposes.
  4777. *
  4778. * @private
  4779. * @type {Boolean}
  4780. */
  4781. Component$1.prototype.supportsRaf_ = typeof window__default['default'].requestAnimationFrame === 'function' && typeof window__default['default'].cancelAnimationFrame === 'function';
  4782. Component$1.registerComponent('Component', Component$1);
  4783. /**
  4784. * @file time-ranges.js
  4785. * @module time-ranges
  4786. */
  4787. /**
  4788. * Returns the time for the specified index at the start or end
  4789. * of a TimeRange object.
  4790. *
  4791. * @typedef {Function} TimeRangeIndex
  4792. *
  4793. * @param {number} [index=0]
  4794. * The range number to return the time for.
  4795. *
  4796. * @return {number}
  4797. * The time offset at the specified index.
  4798. *
  4799. * @deprecated The index argument must be provided.
  4800. * In the future, leaving it out will throw an error.
  4801. */
  4802. /**
  4803. * An object that contains ranges of time.
  4804. *
  4805. * @typedef {Object} TimeRange
  4806. *
  4807. * @property {number} length
  4808. * The number of time ranges represented by this object.
  4809. *
  4810. * @property {module:time-ranges~TimeRangeIndex} start
  4811. * Returns the time offset at which a specified time range begins.
  4812. *
  4813. * @property {module:time-ranges~TimeRangeIndex} end
  4814. * Returns the time offset at which a specified time range ends.
  4815. *
  4816. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4817. */
  4818. /**
  4819. * Check if any of the time ranges are over the maximum index.
  4820. *
  4821. * @private
  4822. * @param {string} fnName
  4823. * The function name to use for logging
  4824. *
  4825. * @param {number} index
  4826. * The index to check
  4827. *
  4828. * @param {number} maxIndex
  4829. * The maximum possible index
  4830. *
  4831. * @throws {Error} if the timeRanges provided are over the maxIndex
  4832. */
  4833. function rangeCheck(fnName, index, maxIndex) {
  4834. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  4835. throw new Error("Failed to execute '" + fnName + "' on 'TimeRanges': The index provided (" + index + ") is non-numeric or out of bounds (0-" + maxIndex + ").");
  4836. }
  4837. }
  4838. /**
  4839. * Get the time for the specified index at the start or end
  4840. * of a TimeRange object.
  4841. *
  4842. * @private
  4843. * @param {string} fnName
  4844. * The function name to use for logging
  4845. *
  4846. * @param {string} valueIndex
  4847. * The property that should be used to get the time. should be
  4848. * 'start' or 'end'
  4849. *
  4850. * @param {Array} ranges
  4851. * An array of time ranges
  4852. *
  4853. * @param {Array} [rangeIndex=0]
  4854. * The index to start the search at
  4855. *
  4856. * @return {number}
  4857. * The time that offset at the specified index.
  4858. *
  4859. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  4860. * @throws {Error} if rangeIndex is more than the length of ranges
  4861. */
  4862. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  4863. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  4864. return ranges[rangeIndex][valueIndex];
  4865. }
  4866. /**
  4867. * Create a time range object given ranges of time.
  4868. *
  4869. * @private
  4870. * @param {Array} [ranges]
  4871. * An array of time ranges.
  4872. */
  4873. function createTimeRangesObj(ranges) {
  4874. var timeRangesObj;
  4875. if (ranges === undefined || ranges.length === 0) {
  4876. timeRangesObj = {
  4877. length: 0,
  4878. start: function start() {
  4879. throw new Error('This TimeRanges object is empty');
  4880. },
  4881. end: function end() {
  4882. throw new Error('This TimeRanges object is empty');
  4883. }
  4884. };
  4885. } else {
  4886. timeRangesObj = {
  4887. length: ranges.length,
  4888. start: getRange.bind(null, 'start', 0, ranges),
  4889. end: getRange.bind(null, 'end', 1, ranges)
  4890. };
  4891. }
  4892. if (window__default['default'].Symbol && window__default['default'].Symbol.iterator) {
  4893. timeRangesObj[window__default['default'].Symbol.iterator] = function () {
  4894. return (ranges || []).values();
  4895. };
  4896. }
  4897. return timeRangesObj;
  4898. }
  4899. /**
  4900. * Create a `TimeRange` object which mimics an
  4901. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  4902. *
  4903. * @param {number|Array[]} start
  4904. * The start of a single range (a number) or an array of ranges (an
  4905. * array of arrays of two numbers each).
  4906. *
  4907. * @param {number} end
  4908. * The end of a single range. Cannot be used with the array form of
  4909. * the `start` argument.
  4910. */
  4911. function createTimeRanges(start, end) {
  4912. if (Array.isArray(start)) {
  4913. return createTimeRangesObj(start);
  4914. } else if (start === undefined || end === undefined) {
  4915. return createTimeRangesObj();
  4916. }
  4917. return createTimeRangesObj([[start, end]]);
  4918. }
  4919. /**
  4920. * @file buffer.js
  4921. * @module buffer
  4922. */
  4923. /**
  4924. * Compute the percentage of the media that has been buffered.
  4925. *
  4926. * @param {TimeRange} buffered
  4927. * The current `TimeRange` object representing buffered time ranges
  4928. *
  4929. * @param {number} duration
  4930. * Total duration of the media
  4931. *
  4932. * @return {number}
  4933. * Percent buffered of the total duration in decimal form.
  4934. */
  4935. function bufferedPercent(buffered, duration) {
  4936. var bufferedDuration = 0;
  4937. var start;
  4938. var end;
  4939. if (!duration) {
  4940. return 0;
  4941. }
  4942. if (!buffered || !buffered.length) {
  4943. buffered = createTimeRanges(0, 0);
  4944. }
  4945. for (var i = 0; i < buffered.length; i++) {
  4946. start = buffered.start(i);
  4947. end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction
  4948. if (end > duration) {
  4949. end = duration;
  4950. }
  4951. bufferedDuration += end - start;
  4952. }
  4953. return bufferedDuration / duration;
  4954. }
  4955. /**
  4956. * @file media-error.js
  4957. */
  4958. /**
  4959. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  4960. *
  4961. * @param {number|string|Object|MediaError} value
  4962. * This can be of multiple types:
  4963. * - number: should be a standard error code
  4964. * - string: an error message (the code will be 0)
  4965. * - Object: arbitrary properties
  4966. * - `MediaError` (native): used to populate a video.js `MediaError` object
  4967. * - `MediaError` (video.js): will return itself if it's already a
  4968. * video.js `MediaError` object.
  4969. *
  4970. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  4971. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  4972. *
  4973. * @class MediaError
  4974. */
  4975. function MediaError(value) {
  4976. // Allow redundant calls to this constructor to avoid having `instanceof`
  4977. // checks peppered around the code.
  4978. if (value instanceof MediaError) {
  4979. return value;
  4980. }
  4981. if (typeof value === 'number') {
  4982. this.code = value;
  4983. } else if (typeof value === 'string') {
  4984. // default code is zero, so this is a custom error
  4985. this.message = value;
  4986. } else if (isObject(value)) {
  4987. // We assign the `code` property manually because native `MediaError` objects
  4988. // do not expose it as an own/enumerable property of the object.
  4989. if (typeof value.code === 'number') {
  4990. this.code = value.code;
  4991. }
  4992. assign(this, value);
  4993. }
  4994. if (!this.message) {
  4995. this.message = MediaError.defaultMessages[this.code] || '';
  4996. }
  4997. }
  4998. /**
  4999. * The error code that refers two one of the defined `MediaError` types
  5000. *
  5001. * @type {Number}
  5002. */
  5003. MediaError.prototype.code = 0;
  5004. /**
  5005. * An optional message that to show with the error. Message is not part of the HTML5
  5006. * video spec but allows for more informative custom errors.
  5007. *
  5008. * @type {String}
  5009. */
  5010. MediaError.prototype.message = '';
  5011. /**
  5012. * An optional status code that can be set by plugins to allow even more detail about
  5013. * the error. For example a plugin might provide a specific HTTP status code and an
  5014. * error message for that code. Then when the plugin gets that error this class will
  5015. * know how to display an error message for it. This allows a custom message to show
  5016. * up on the `Player` error overlay.
  5017. *
  5018. * @type {Array}
  5019. */
  5020. MediaError.prototype.status = null;
  5021. /**
  5022. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5023. * specification listed under {@link MediaError} for more information.
  5024. *
  5025. * @enum {array}
  5026. * @readonly
  5027. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5028. * @property {string} 1 - MEDIA_ERR_ABORTED
  5029. * @property {string} 2 - MEDIA_ERR_NETWORK
  5030. * @property {string} 3 - MEDIA_ERR_DECODE
  5031. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5032. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5033. */
  5034. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5035. /**
  5036. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5037. *
  5038. * @type {Array}
  5039. * @constant
  5040. */
  5041. MediaError.defaultMessages = {
  5042. 1: 'You aborted the media playback',
  5043. 2: 'A network error caused the media download to fail part-way.',
  5044. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5045. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5046. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5047. }; // Add types as properties on MediaError
  5048. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5049. for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5050. MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance
  5051. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5052. } // jsdocs for instance/static members added above
  5053. /**
  5054. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5055. *
  5056. * @param {Object} value
  5057. * An object that may or may not be `Promise`-like.
  5058. *
  5059. * @return {boolean}
  5060. * Whether or not the object is `Promise`-like.
  5061. */
  5062. function isPromise(value) {
  5063. return value !== undefined && value !== null && typeof value.then === 'function';
  5064. }
  5065. /**
  5066. * Silence a Promise-like object.
  5067. *
  5068. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5069. * play promise" rejection error messages.
  5070. *
  5071. * @param {Object} value
  5072. * An object that may or may not be `Promise`-like.
  5073. */
  5074. function silencePromise(value) {
  5075. if (isPromise(value)) {
  5076. value.then(null, function (e) {});
  5077. }
  5078. }
  5079. /**
  5080. * @file text-track-list-converter.js Utilities for capturing text track state and
  5081. * re-creating tracks based on a capture.
  5082. *
  5083. * @module text-track-list-converter
  5084. */
  5085. /**
  5086. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5087. * represents the {@link TextTrack}'s state.
  5088. *
  5089. * @param {TextTrack} track
  5090. * The text track to query.
  5091. *
  5092. * @return {Object}
  5093. * A serializable javascript representation of the TextTrack.
  5094. * @private
  5095. */
  5096. var trackToJson_ = function trackToJson_(track) {
  5097. var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) {
  5098. if (track[prop]) {
  5099. acc[prop] = track[prop];
  5100. }
  5101. return acc;
  5102. }, {
  5103. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5104. return {
  5105. startTime: cue.startTime,
  5106. endTime: cue.endTime,
  5107. text: cue.text,
  5108. id: cue.id
  5109. };
  5110. })
  5111. });
  5112. return ret;
  5113. };
  5114. /**
  5115. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5116. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5117. * {@link text-track-list-converter:jsonToTextTracks}.
  5118. *
  5119. * @param {Tech} tech
  5120. * The tech object to query
  5121. *
  5122. * @return {Array}
  5123. * A serializable javascript representation of the {@link Tech}s
  5124. * {@link TextTrackList}.
  5125. */
  5126. var textTracksToJson = function textTracksToJson(tech) {
  5127. var trackEls = tech.$$('track');
  5128. var trackObjs = Array.prototype.map.call(trackEls, function (t) {
  5129. return t.track;
  5130. });
  5131. var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5132. var json = trackToJson_(trackEl.track);
  5133. if (trackEl.src) {
  5134. json.src = trackEl.src;
  5135. }
  5136. return json;
  5137. });
  5138. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5139. return trackObjs.indexOf(track) === -1;
  5140. }).map(trackToJson_));
  5141. };
  5142. /**
  5143. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5144. * object {@link TextTrack} representations.
  5145. *
  5146. * @param {Array} json
  5147. * An array of `TextTrack` representation objects, like those that would be
  5148. * produced by `textTracksToJson`.
  5149. *
  5150. * @param {Tech} tech
  5151. * The `Tech` to create the `TextTrack`s on.
  5152. */
  5153. var jsonToTextTracks = function jsonToTextTracks(json, tech) {
  5154. json.forEach(function (track) {
  5155. var addedTrack = tech.addRemoteTextTrack(track).track;
  5156. if (!track.src && track.cues) {
  5157. track.cues.forEach(function (cue) {
  5158. return addedTrack.addCue(cue);
  5159. });
  5160. }
  5161. });
  5162. return tech.textTracks();
  5163. };
  5164. var textTrackConverter = {
  5165. textTracksToJson: textTracksToJson,
  5166. jsonToTextTracks: jsonToTextTracks,
  5167. trackToJson_: trackToJson_
  5168. };
  5169. var MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5170. /**
  5171. * The `ModalDialog` displays over the video and its controls, which blocks
  5172. * interaction with the player until it is closed.
  5173. *
  5174. * Modal dialogs include a "Close" button and will close when that button
  5175. * is activated - or when ESC is pressed anywhere.
  5176. *
  5177. * @extends Component
  5178. */
  5179. var ModalDialog = /*#__PURE__*/function (_Component) {
  5180. _inheritsLoose__default['default'](ModalDialog, _Component);
  5181. /**
  5182. * Create an instance of this class.
  5183. *
  5184. * @param {Player} player
  5185. * The `Player` that this class should be attached to.
  5186. *
  5187. * @param {Object} [options]
  5188. * The key/value store of player options.
  5189. *
  5190. * @param {Mixed} [options.content=undefined]
  5191. * Provide customized content for this modal.
  5192. *
  5193. * @param {string} [options.description]
  5194. * A text description for the modal, primarily for accessibility.
  5195. *
  5196. * @param {boolean} [options.fillAlways=false]
  5197. * Normally, modals are automatically filled only the first time
  5198. * they open. This tells the modal to refresh its content
  5199. * every time it opens.
  5200. *
  5201. * @param {string} [options.label]
  5202. * A text label for the modal, primarily for accessibility.
  5203. *
  5204. * @param {boolean} [options.pauseOnOpen=true]
  5205. * If `true`, playback will will be paused if playing when
  5206. * the modal opens, and resumed when it closes.
  5207. *
  5208. * @param {boolean} [options.temporary=true]
  5209. * If `true`, the modal can only be opened once; it will be
  5210. * disposed as soon as it's closed.
  5211. *
  5212. * @param {boolean} [options.uncloseable=false]
  5213. * If `true`, the user will not be able to close the modal
  5214. * through the UI in the normal ways. Programmatic closing is
  5215. * still possible.
  5216. */
  5217. function ModalDialog(player, options) {
  5218. var _this;
  5219. _this = _Component.call(this, player, options) || this;
  5220. _this.handleKeyDown_ = function (e) {
  5221. return _this.handleKeyDown(e);
  5222. };
  5223. _this.close_ = function (e) {
  5224. return _this.close(e);
  5225. };
  5226. _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false;
  5227. _this.closeable(!_this.options_.uncloseable);
  5228. _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized
  5229. // because we only want the contents of the modal in the contentEl
  5230. // (not the UI elements like the close button).
  5231. _this.contentEl_ = createEl('div', {
  5232. className: MODAL_CLASS_NAME + "-content"
  5233. }, {
  5234. role: 'document'
  5235. });
  5236. _this.descEl_ = createEl('p', {
  5237. className: MODAL_CLASS_NAME + "-description vjs-control-text",
  5238. id: _this.el().getAttribute('aria-describedby')
  5239. });
  5240. textContent(_this.descEl_, _this.description());
  5241. _this.el_.appendChild(_this.descEl_);
  5242. _this.el_.appendChild(_this.contentEl_);
  5243. return _this;
  5244. }
  5245. /**
  5246. * Create the `ModalDialog`'s DOM element
  5247. *
  5248. * @return {Element}
  5249. * The DOM element that gets created.
  5250. */
  5251. var _proto = ModalDialog.prototype;
  5252. _proto.createEl = function createEl() {
  5253. return _Component.prototype.createEl.call(this, 'div', {
  5254. className: this.buildCSSClass(),
  5255. tabIndex: -1
  5256. }, {
  5257. 'aria-describedby': this.id() + "_description",
  5258. 'aria-hidden': 'true',
  5259. 'aria-label': this.label(),
  5260. 'role': 'dialog'
  5261. });
  5262. };
  5263. _proto.dispose = function dispose() {
  5264. this.contentEl_ = null;
  5265. this.descEl_ = null;
  5266. this.previouslyActiveEl_ = null;
  5267. _Component.prototype.dispose.call(this);
  5268. }
  5269. /**
  5270. * Builds the default DOM `className`.
  5271. *
  5272. * @return {string}
  5273. * The DOM `className` for this object.
  5274. */
  5275. ;
  5276. _proto.buildCSSClass = function buildCSSClass() {
  5277. return MODAL_CLASS_NAME + " vjs-hidden " + _Component.prototype.buildCSSClass.call(this);
  5278. }
  5279. /**
  5280. * Returns the label string for this modal. Primarily used for accessibility.
  5281. *
  5282. * @return {string}
  5283. * the localized or raw label of this modal.
  5284. */
  5285. ;
  5286. _proto.label = function label() {
  5287. return this.localize(this.options_.label || 'Modal Window');
  5288. }
  5289. /**
  5290. * Returns the description string for this modal. Primarily used for
  5291. * accessibility.
  5292. *
  5293. * @return {string}
  5294. * The localized or raw description of this modal.
  5295. */
  5296. ;
  5297. _proto.description = function description() {
  5298. var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable.
  5299. if (this.closeable()) {
  5300. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5301. }
  5302. return desc;
  5303. }
  5304. /**
  5305. * Opens the modal.
  5306. *
  5307. * @fires ModalDialog#beforemodalopen
  5308. * @fires ModalDialog#modalopen
  5309. */
  5310. ;
  5311. _proto.open = function open() {
  5312. if (!this.opened_) {
  5313. var player = this.player();
  5314. /**
  5315. * Fired just before a `ModalDialog` is opened.
  5316. *
  5317. * @event ModalDialog#beforemodalopen
  5318. * @type {EventTarget~Event}
  5319. */
  5320. this.trigger('beforemodalopen');
  5321. this.opened_ = true; // Fill content if the modal has never opened before and
  5322. // never been filled.
  5323. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5324. this.fill();
  5325. } // If the player was playing, pause it and take note of its previously
  5326. // playing state.
  5327. this.wasPlaying_ = !player.paused();
  5328. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5329. player.pause();
  5330. }
  5331. this.on('keydown', this.handleKeyDown_); // Hide controls and note if they were enabled.
  5332. this.hadControls_ = player.controls();
  5333. player.controls(false);
  5334. this.show();
  5335. this.conditionalFocus_();
  5336. this.el().setAttribute('aria-hidden', 'false');
  5337. /**
  5338. * Fired just after a `ModalDialog` is opened.
  5339. *
  5340. * @event ModalDialog#modalopen
  5341. * @type {EventTarget~Event}
  5342. */
  5343. this.trigger('modalopen');
  5344. this.hasBeenOpened_ = true;
  5345. }
  5346. }
  5347. /**
  5348. * If the `ModalDialog` is currently open or closed.
  5349. *
  5350. * @param {boolean} [value]
  5351. * If given, it will open (`true`) or close (`false`) the modal.
  5352. *
  5353. * @return {boolean}
  5354. * the current open state of the modaldialog
  5355. */
  5356. ;
  5357. _proto.opened = function opened(value) {
  5358. if (typeof value === 'boolean') {
  5359. this[value ? 'open' : 'close']();
  5360. }
  5361. return this.opened_;
  5362. }
  5363. /**
  5364. * Closes the modal, does nothing if the `ModalDialog` is
  5365. * not open.
  5366. *
  5367. * @fires ModalDialog#beforemodalclose
  5368. * @fires ModalDialog#modalclose
  5369. */
  5370. ;
  5371. _proto.close = function close() {
  5372. if (!this.opened_) {
  5373. return;
  5374. }
  5375. var player = this.player();
  5376. /**
  5377. * Fired just before a `ModalDialog` is closed.
  5378. *
  5379. * @event ModalDialog#beforemodalclose
  5380. * @type {EventTarget~Event}
  5381. */
  5382. this.trigger('beforemodalclose');
  5383. this.opened_ = false;
  5384. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5385. player.play();
  5386. }
  5387. this.off('keydown', this.handleKeyDown_);
  5388. if (this.hadControls_) {
  5389. player.controls(true);
  5390. }
  5391. this.hide();
  5392. this.el().setAttribute('aria-hidden', 'true');
  5393. /**
  5394. * Fired just after a `ModalDialog` is closed.
  5395. *
  5396. * @event ModalDialog#modalclose
  5397. * @type {EventTarget~Event}
  5398. */
  5399. this.trigger('modalclose');
  5400. this.conditionalBlur_();
  5401. if (this.options_.temporary) {
  5402. this.dispose();
  5403. }
  5404. }
  5405. /**
  5406. * Check to see if the `ModalDialog` is closeable via the UI.
  5407. *
  5408. * @param {boolean} [value]
  5409. * If given as a boolean, it will set the `closeable` option.
  5410. *
  5411. * @return {boolean}
  5412. * Returns the final value of the closable option.
  5413. */
  5414. ;
  5415. _proto.closeable = function closeable(value) {
  5416. if (typeof value === 'boolean') {
  5417. var closeable = this.closeable_ = !!value;
  5418. var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one.
  5419. if (closeable && !close) {
  5420. // The close button should be a child of the modal - not its
  5421. // content element, so temporarily change the content element.
  5422. var temp = this.contentEl_;
  5423. this.contentEl_ = this.el_;
  5424. close = this.addChild('closeButton', {
  5425. controlText: 'Close Modal Dialog'
  5426. });
  5427. this.contentEl_ = temp;
  5428. this.on(close, 'close', this.close_);
  5429. } // If this is being made uncloseable and has a close button, remove it.
  5430. if (!closeable && close) {
  5431. this.off(close, 'close', this.close_);
  5432. this.removeChild(close);
  5433. close.dispose();
  5434. }
  5435. }
  5436. return this.closeable_;
  5437. }
  5438. /**
  5439. * Fill the modal's content element with the modal's "content" option.
  5440. * The content element will be emptied before this change takes place.
  5441. */
  5442. ;
  5443. _proto.fill = function fill() {
  5444. this.fillWith(this.content());
  5445. }
  5446. /**
  5447. * Fill the modal's content element with arbitrary content.
  5448. * The content element will be emptied before this change takes place.
  5449. *
  5450. * @fires ModalDialog#beforemodalfill
  5451. * @fires ModalDialog#modalfill
  5452. *
  5453. * @param {Mixed} [content]
  5454. * The same rules apply to this as apply to the `content` option.
  5455. */
  5456. ;
  5457. _proto.fillWith = function fillWith(content) {
  5458. var contentEl = this.contentEl();
  5459. var parentEl = contentEl.parentNode;
  5460. var nextSiblingEl = contentEl.nextSibling;
  5461. /**
  5462. * Fired just before a `ModalDialog` is filled with content.
  5463. *
  5464. * @event ModalDialog#beforemodalfill
  5465. * @type {EventTarget~Event}
  5466. */
  5467. this.trigger('beforemodalfill');
  5468. this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing
  5469. // manipulation to avoid modifying the live DOM multiple times.
  5470. parentEl.removeChild(contentEl);
  5471. this.empty();
  5472. insertContent(contentEl, content);
  5473. /**
  5474. * Fired just after a `ModalDialog` is filled with content.
  5475. *
  5476. * @event ModalDialog#modalfill
  5477. * @type {EventTarget~Event}
  5478. */
  5479. this.trigger('modalfill'); // Re-inject the re-filled content element.
  5480. if (nextSiblingEl) {
  5481. parentEl.insertBefore(contentEl, nextSiblingEl);
  5482. } else {
  5483. parentEl.appendChild(contentEl);
  5484. } // make sure that the close button is last in the dialog DOM
  5485. var closeButton = this.getChild('closeButton');
  5486. if (closeButton) {
  5487. parentEl.appendChild(closeButton.el_);
  5488. }
  5489. }
  5490. /**
  5491. * Empties the content element. This happens anytime the modal is filled.
  5492. *
  5493. * @fires ModalDialog#beforemodalempty
  5494. * @fires ModalDialog#modalempty
  5495. */
  5496. ;
  5497. _proto.empty = function empty() {
  5498. /**
  5499. * Fired just before a `ModalDialog` is emptied.
  5500. *
  5501. * @event ModalDialog#beforemodalempty
  5502. * @type {EventTarget~Event}
  5503. */
  5504. this.trigger('beforemodalempty');
  5505. emptyEl(this.contentEl());
  5506. /**
  5507. * Fired just after a `ModalDialog` is emptied.
  5508. *
  5509. * @event ModalDialog#modalempty
  5510. * @type {EventTarget~Event}
  5511. */
  5512. this.trigger('modalempty');
  5513. }
  5514. /**
  5515. * Gets or sets the modal content, which gets normalized before being
  5516. * rendered into the DOM.
  5517. *
  5518. * This does not update the DOM or fill the modal, but it is called during
  5519. * that process.
  5520. *
  5521. * @param {Mixed} [value]
  5522. * If defined, sets the internal content value to be used on the
  5523. * next call(s) to `fill`. This value is normalized before being
  5524. * inserted. To "clear" the internal content value, pass `null`.
  5525. *
  5526. * @return {Mixed}
  5527. * The current content of the modal dialog
  5528. */
  5529. ;
  5530. _proto.content = function content(value) {
  5531. if (typeof value !== 'undefined') {
  5532. this.content_ = value;
  5533. }
  5534. return this.content_;
  5535. }
  5536. /**
  5537. * conditionally focus the modal dialog if focus was previously on the player.
  5538. *
  5539. * @private
  5540. */
  5541. ;
  5542. _proto.conditionalFocus_ = function conditionalFocus_() {
  5543. var activeEl = document__default['default'].activeElement;
  5544. var playerEl = this.player_.el_;
  5545. this.previouslyActiveEl_ = null;
  5546. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5547. this.previouslyActiveEl_ = activeEl;
  5548. this.focus();
  5549. }
  5550. }
  5551. /**
  5552. * conditionally blur the element and refocus the last focused element
  5553. *
  5554. * @private
  5555. */
  5556. ;
  5557. _proto.conditionalBlur_ = function conditionalBlur_() {
  5558. if (this.previouslyActiveEl_) {
  5559. this.previouslyActiveEl_.focus();
  5560. this.previouslyActiveEl_ = null;
  5561. }
  5562. }
  5563. /**
  5564. * Keydown handler. Attached when modal is focused.
  5565. *
  5566. * @listens keydown
  5567. */
  5568. ;
  5569. _proto.handleKeyDown = function handleKeyDown(event) {
  5570. // Do not allow keydowns to reach out of the modal dialog.
  5571. event.stopPropagation();
  5572. if (keycode__default['default'].isEventKey(event, 'Escape') && this.closeable()) {
  5573. event.preventDefault();
  5574. this.close();
  5575. return;
  5576. } // exit early if it isn't a tab key
  5577. if (!keycode__default['default'].isEventKey(event, 'Tab')) {
  5578. return;
  5579. }
  5580. var focusableEls = this.focusableEls_();
  5581. var activeEl = this.el_.querySelector(':focus');
  5582. var focusIndex;
  5583. for (var i = 0; i < focusableEls.length; i++) {
  5584. if (activeEl === focusableEls[i]) {
  5585. focusIndex = i;
  5586. break;
  5587. }
  5588. }
  5589. if (document__default['default'].activeElement === this.el_) {
  5590. focusIndex = 0;
  5591. }
  5592. if (event.shiftKey && focusIndex === 0) {
  5593. focusableEls[focusableEls.length - 1].focus();
  5594. event.preventDefault();
  5595. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5596. focusableEls[0].focus();
  5597. event.preventDefault();
  5598. }
  5599. }
  5600. /**
  5601. * get all focusable elements
  5602. *
  5603. * @private
  5604. */
  5605. ;
  5606. _proto.focusableEls_ = function focusableEls_() {
  5607. var allChildren = this.el_.querySelectorAll('*');
  5608. return Array.prototype.filter.call(allChildren, function (child) {
  5609. 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');
  5610. });
  5611. };
  5612. return ModalDialog;
  5613. }(Component$1);
  5614. /**
  5615. * Default options for `ModalDialog` default options.
  5616. *
  5617. * @type {Object}
  5618. * @private
  5619. */
  5620. ModalDialog.prototype.options_ = {
  5621. pauseOnOpen: true,
  5622. temporary: true
  5623. };
  5624. Component$1.registerComponent('ModalDialog', ModalDialog);
  5625. /**
  5626. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5627. * {@link VideoTrackList}
  5628. *
  5629. * @extends EventTarget
  5630. */
  5631. var TrackList = /*#__PURE__*/function (_EventTarget) {
  5632. _inheritsLoose__default['default'](TrackList, _EventTarget);
  5633. /**
  5634. * Create an instance of this class
  5635. *
  5636. * @param {Track[]} tracks
  5637. * A list of tracks to initialize the list with.
  5638. *
  5639. * @abstract
  5640. */
  5641. function TrackList(tracks) {
  5642. var _this;
  5643. if (tracks === void 0) {
  5644. tracks = [];
  5645. }
  5646. _this = _EventTarget.call(this) || this;
  5647. _this.tracks_ = [];
  5648. /**
  5649. * @memberof TrackList
  5650. * @member {number} length
  5651. * The current number of `Track`s in the this Trackist.
  5652. * @instance
  5653. */
  5654. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'length', {
  5655. get: function get() {
  5656. return this.tracks_.length;
  5657. }
  5658. });
  5659. for (var i = 0; i < tracks.length; i++) {
  5660. _this.addTrack(tracks[i]);
  5661. }
  5662. return _this;
  5663. }
  5664. /**
  5665. * Add a {@link Track} to the `TrackList`
  5666. *
  5667. * @param {Track} track
  5668. * The audio, video, or text track to add to the list.
  5669. *
  5670. * @fires TrackList#addtrack
  5671. */
  5672. var _proto = TrackList.prototype;
  5673. _proto.addTrack = function addTrack(track) {
  5674. var _this2 = this;
  5675. var index = this.tracks_.length;
  5676. if (!('' + index in this)) {
  5677. Object.defineProperty(this, index, {
  5678. get: function get() {
  5679. return this.tracks_[index];
  5680. }
  5681. });
  5682. } // Do not add duplicate tracks
  5683. if (this.tracks_.indexOf(track) === -1) {
  5684. this.tracks_.push(track);
  5685. /**
  5686. * Triggered when a track is added to a track list.
  5687. *
  5688. * @event TrackList#addtrack
  5689. * @type {EventTarget~Event}
  5690. * @property {Track} track
  5691. * A reference to track that was added.
  5692. */
  5693. this.trigger({
  5694. track: track,
  5695. type: 'addtrack',
  5696. target: this
  5697. });
  5698. }
  5699. /**
  5700. * Triggered when a track label is changed.
  5701. *
  5702. * @event TrackList#addtrack
  5703. * @type {EventTarget~Event}
  5704. * @property {Track} track
  5705. * A reference to track that was added.
  5706. */
  5707. track.labelchange_ = function () {
  5708. _this2.trigger({
  5709. track: track,
  5710. type: 'labelchange',
  5711. target: _this2
  5712. });
  5713. };
  5714. if (isEvented(track)) {
  5715. track.addEventListener('labelchange', track.labelchange_);
  5716. }
  5717. }
  5718. /**
  5719. * Remove a {@link Track} from the `TrackList`
  5720. *
  5721. * @param {Track} rtrack
  5722. * The audio, video, or text track to remove from the list.
  5723. *
  5724. * @fires TrackList#removetrack
  5725. */
  5726. ;
  5727. _proto.removeTrack = function removeTrack(rtrack) {
  5728. var track;
  5729. for (var i = 0, l = this.length; i < l; i++) {
  5730. if (this[i] === rtrack) {
  5731. track = this[i];
  5732. if (track.off) {
  5733. track.off();
  5734. }
  5735. this.tracks_.splice(i, 1);
  5736. break;
  5737. }
  5738. }
  5739. if (!track) {
  5740. return;
  5741. }
  5742. /**
  5743. * Triggered when a track is removed from track list.
  5744. *
  5745. * @event TrackList#removetrack
  5746. * @type {EventTarget~Event}
  5747. * @property {Track} track
  5748. * A reference to track that was removed.
  5749. */
  5750. this.trigger({
  5751. track: track,
  5752. type: 'removetrack',
  5753. target: this
  5754. });
  5755. }
  5756. /**
  5757. * Get a Track from the TrackList by a tracks id
  5758. *
  5759. * @param {string} id - the id of the track to get
  5760. * @method getTrackById
  5761. * @return {Track}
  5762. * @private
  5763. */
  5764. ;
  5765. _proto.getTrackById = function getTrackById(id) {
  5766. var result = null;
  5767. for (var i = 0, l = this.length; i < l; i++) {
  5768. var track = this[i];
  5769. if (track.id === id) {
  5770. result = track;
  5771. break;
  5772. }
  5773. }
  5774. return result;
  5775. };
  5776. return TrackList;
  5777. }(EventTarget$2);
  5778. /**
  5779. * Triggered when a different track is selected/enabled.
  5780. *
  5781. * @event TrackList#change
  5782. * @type {EventTarget~Event}
  5783. */
  5784. /**
  5785. * Events that can be called with on + eventName. See {@link EventHandler}.
  5786. *
  5787. * @property {Object} TrackList#allowedEvents_
  5788. * @private
  5789. */
  5790. TrackList.prototype.allowedEvents_ = {
  5791. change: 'change',
  5792. addtrack: 'addtrack',
  5793. removetrack: 'removetrack',
  5794. labelchange: 'labelchange'
  5795. }; // emulate attribute EventHandler support to allow for feature detection
  5796. for (var event in TrackList.prototype.allowedEvents_) {
  5797. TrackList.prototype['on' + event] = null;
  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 {AudioTrack} track
  5807. * The track to skip
  5808. *
  5809. * @private
  5810. */
  5811. var disableOthers$1 = function disableOthers(list, track) {
  5812. for (var i = 0; i < list.length; i++) {
  5813. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5814. continue;
  5815. } // another audio track is enabled, disable it
  5816. list[i].enabled = false;
  5817. }
  5818. };
  5819. /**
  5820. * The current list of {@link AudioTrack} for a media file.
  5821. *
  5822. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5823. * @extends TrackList
  5824. */
  5825. var AudioTrackList = /*#__PURE__*/function (_TrackList) {
  5826. _inheritsLoose__default['default'](AudioTrackList, _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. function AudioTrackList(tracks) {
  5834. var _this;
  5835. if (tracks === void 0) {
  5836. tracks = [];
  5837. }
  5838. // make sure only 1 track is enabled
  5839. // sorted from last index to first index
  5840. for (var i = tracks.length - 1; i >= 0; i--) {
  5841. if (tracks[i].enabled) {
  5842. disableOthers$1(tracks, tracks[i]);
  5843. break;
  5844. }
  5845. }
  5846. _this = _TrackList.call(this, tracks) || this;
  5847. _this.changing_ = false;
  5848. return _this;
  5849. }
  5850. /**
  5851. * Add an {@link AudioTrack} to the `AudioTrackList`.
  5852. *
  5853. * @param {AudioTrack} track
  5854. * The AudioTrack to add to the list
  5855. *
  5856. * @fires TrackList#addtrack
  5857. */
  5858. var _proto = AudioTrackList.prototype;
  5859. _proto.addTrack = function addTrack(track) {
  5860. var _this2 = this;
  5861. if (track.enabled) {
  5862. disableOthers$1(this, track);
  5863. }
  5864. _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this
  5865. if (!track.addEventListener) {
  5866. return;
  5867. }
  5868. track.enabledChange_ = function () {
  5869. // when we are disabling other tracks (since we don't support
  5870. // more than one track at a time) we will set changing_
  5871. // to true so that we don't trigger additional change events
  5872. if (_this2.changing_) {
  5873. return;
  5874. }
  5875. _this2.changing_ = true;
  5876. disableOthers$1(_this2, track);
  5877. _this2.changing_ = false;
  5878. _this2.trigger('change');
  5879. };
  5880. /**
  5881. * @listens AudioTrack#enabledchange
  5882. * @fires TrackList#change
  5883. */
  5884. track.addEventListener('enabledchange', track.enabledChange_);
  5885. };
  5886. _proto.removeTrack = function removeTrack(rtrack) {
  5887. _TrackList.prototype.removeTrack.call(this, rtrack);
  5888. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  5889. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  5890. rtrack.enabledChange_ = null;
  5891. }
  5892. };
  5893. return AudioTrackList;
  5894. }(TrackList);
  5895. /**
  5896. * Un-select all other {@link VideoTrack}s that are selected.
  5897. *
  5898. * @param {VideoTrackList} list
  5899. * list to work on
  5900. *
  5901. * @param {VideoTrack} track
  5902. * The track to skip
  5903. *
  5904. * @private
  5905. */
  5906. var disableOthers = function disableOthers(list, track) {
  5907. for (var i = 0; i < list.length; i++) {
  5908. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5909. continue;
  5910. } // another video track is enabled, disable it
  5911. list[i].selected = false;
  5912. }
  5913. };
  5914. /**
  5915. * The current list of {@link VideoTrack} for a video.
  5916. *
  5917. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  5918. * @extends TrackList
  5919. */
  5920. var VideoTrackList = /*#__PURE__*/function (_TrackList) {
  5921. _inheritsLoose__default['default'](VideoTrackList, _TrackList);
  5922. /**
  5923. * Create an instance of this class.
  5924. *
  5925. * @param {VideoTrack[]} [tracks=[]]
  5926. * A list of `VideoTrack` to instantiate the list with.
  5927. */
  5928. function VideoTrackList(tracks) {
  5929. var _this;
  5930. if (tracks === void 0) {
  5931. tracks = [];
  5932. }
  5933. // make sure only 1 track is enabled
  5934. // sorted from last index to first index
  5935. for (var i = tracks.length - 1; i >= 0; i--) {
  5936. if (tracks[i].selected) {
  5937. disableOthers(tracks, tracks[i]);
  5938. break;
  5939. }
  5940. }
  5941. _this = _TrackList.call(this, tracks) || this;
  5942. _this.changing_ = false;
  5943. /**
  5944. * @member {number} VideoTrackList#selectedIndex
  5945. * The current index of the selected {@link VideoTrack`}.
  5946. */
  5947. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'selectedIndex', {
  5948. get: function get() {
  5949. for (var _i = 0; _i < this.length; _i++) {
  5950. if (this[_i].selected) {
  5951. return _i;
  5952. }
  5953. }
  5954. return -1;
  5955. },
  5956. set: function set() {}
  5957. });
  5958. return _this;
  5959. }
  5960. /**
  5961. * Add a {@link VideoTrack} to the `VideoTrackList`.
  5962. *
  5963. * @param {VideoTrack} track
  5964. * The VideoTrack to add to the list
  5965. *
  5966. * @fires TrackList#addtrack
  5967. */
  5968. var _proto = VideoTrackList.prototype;
  5969. _proto.addTrack = function addTrack(track) {
  5970. var _this2 = this;
  5971. if (track.selected) {
  5972. disableOthers(this, track);
  5973. }
  5974. _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this
  5975. if (!track.addEventListener) {
  5976. return;
  5977. }
  5978. track.selectedChange_ = function () {
  5979. if (_this2.changing_) {
  5980. return;
  5981. }
  5982. _this2.changing_ = true;
  5983. disableOthers(_this2, track);
  5984. _this2.changing_ = false;
  5985. _this2.trigger('change');
  5986. };
  5987. /**
  5988. * @listens VideoTrack#selectedchange
  5989. * @fires TrackList#change
  5990. */
  5991. track.addEventListener('selectedchange', track.selectedChange_);
  5992. };
  5993. _proto.removeTrack = function removeTrack(rtrack) {
  5994. _TrackList.prototype.removeTrack.call(this, rtrack);
  5995. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  5996. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  5997. rtrack.selectedChange_ = null;
  5998. }
  5999. };
  6000. return VideoTrackList;
  6001. }(TrackList);
  6002. /**
  6003. * The current list of {@link TextTrack} for a media file.
  6004. *
  6005. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6006. * @extends TrackList
  6007. */
  6008. var TextTrackList = /*#__PURE__*/function (_TrackList) {
  6009. _inheritsLoose__default['default'](TextTrackList, _TrackList);
  6010. function TextTrackList() {
  6011. return _TrackList.apply(this, arguments) || this;
  6012. }
  6013. var _proto = TextTrackList.prototype;
  6014. /**
  6015. * Add a {@link TextTrack} to the `TextTrackList`
  6016. *
  6017. * @param {TextTrack} track
  6018. * The text track to add to the list.
  6019. *
  6020. * @fires TrackList#addtrack
  6021. */
  6022. _proto.addTrack = function addTrack(track) {
  6023. var _this = this;
  6024. _TrackList.prototype.addTrack.call(this, track);
  6025. if (!this.queueChange_) {
  6026. this.queueChange_ = function () {
  6027. return _this.queueTrigger('change');
  6028. };
  6029. }
  6030. if (!this.triggerSelectedlanguagechange) {
  6031. this.triggerSelectedlanguagechange_ = function () {
  6032. return _this.trigger('selectedlanguagechange');
  6033. };
  6034. }
  6035. /**
  6036. * @listens TextTrack#modechange
  6037. * @fires TrackList#change
  6038. */
  6039. track.addEventListener('modechange', this.queueChange_);
  6040. var nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6041. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6042. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6043. }
  6044. };
  6045. _proto.removeTrack = function removeTrack(rtrack) {
  6046. _TrackList.prototype.removeTrack.call(this, rtrack); // manually remove the event handlers we added
  6047. if (rtrack.removeEventListener) {
  6048. if (this.queueChange_) {
  6049. rtrack.removeEventListener('modechange', this.queueChange_);
  6050. }
  6051. if (this.selectedlanguagechange_) {
  6052. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6053. }
  6054. }
  6055. };
  6056. return TextTrackList;
  6057. }(TrackList);
  6058. /**
  6059. * @file html-track-element-list.js
  6060. */
  6061. /**
  6062. * The current list of {@link HtmlTrackElement}s.
  6063. */
  6064. var HtmlTrackElementList = /*#__PURE__*/function () {
  6065. /**
  6066. * Create an instance of this class.
  6067. *
  6068. * @param {HtmlTrackElement[]} [tracks=[]]
  6069. * A list of `HtmlTrackElement` to instantiate the list with.
  6070. */
  6071. function HtmlTrackElementList(trackElements) {
  6072. if (trackElements === void 0) {
  6073. trackElements = [];
  6074. }
  6075. this.trackElements_ = [];
  6076. /**
  6077. * @memberof HtmlTrackElementList
  6078. * @member {number} length
  6079. * The current number of `Track`s in the this Trackist.
  6080. * @instance
  6081. */
  6082. Object.defineProperty(this, 'length', {
  6083. get: function get() {
  6084. return this.trackElements_.length;
  6085. }
  6086. });
  6087. for (var i = 0, length = trackElements.length; i < length; i++) {
  6088. this.addTrackElement_(trackElements[i]);
  6089. }
  6090. }
  6091. /**
  6092. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6093. *
  6094. * @param {HtmlTrackElement} trackElement
  6095. * The track element to add to the list.
  6096. *
  6097. * @private
  6098. */
  6099. var _proto = HtmlTrackElementList.prototype;
  6100. _proto.addTrackElement_ = function addTrackElement_(trackElement) {
  6101. var index = this.trackElements_.length;
  6102. if (!('' + index in this)) {
  6103. Object.defineProperty(this, index, {
  6104. get: function get() {
  6105. return this.trackElements_[index];
  6106. }
  6107. });
  6108. } // Do not add duplicate elements
  6109. if (this.trackElements_.indexOf(trackElement) === -1) {
  6110. this.trackElements_.push(trackElement);
  6111. }
  6112. }
  6113. /**
  6114. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6115. * {@link TextTrack}.
  6116. *
  6117. * @param {TextTrack} track
  6118. * The track associated with a track element.
  6119. *
  6120. * @return {HtmlTrackElement|undefined}
  6121. * The track element that was found or undefined.
  6122. *
  6123. * @private
  6124. */
  6125. ;
  6126. _proto.getTrackElementByTrack_ = function getTrackElementByTrack_(track) {
  6127. var trackElement_;
  6128. for (var i = 0, length = this.trackElements_.length; i < length; i++) {
  6129. if (track === this.trackElements_[i].track) {
  6130. trackElement_ = this.trackElements_[i];
  6131. break;
  6132. }
  6133. }
  6134. return trackElement_;
  6135. }
  6136. /**
  6137. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6138. *
  6139. * @param {HtmlTrackElement} trackElement
  6140. * The track element to remove from the list.
  6141. *
  6142. * @private
  6143. */
  6144. ;
  6145. _proto.removeTrackElement_ = function removeTrackElement_(trackElement) {
  6146. for (var i = 0, length = this.trackElements_.length; i < length; i++) {
  6147. if (trackElement === this.trackElements_[i]) {
  6148. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6149. this.trackElements_[i].track.off();
  6150. }
  6151. if (typeof this.trackElements_[i].off === 'function') {
  6152. this.trackElements_[i].off();
  6153. }
  6154. this.trackElements_.splice(i, 1);
  6155. break;
  6156. }
  6157. }
  6158. };
  6159. return HtmlTrackElementList;
  6160. }();
  6161. /**
  6162. * @file text-track-cue-list.js
  6163. */
  6164. /**
  6165. * @typedef {Object} TextTrackCueList~TextTrackCue
  6166. *
  6167. * @property {string} id
  6168. * The unique id for this text track cue
  6169. *
  6170. * @property {number} startTime
  6171. * The start time for this text track cue
  6172. *
  6173. * @property {number} endTime
  6174. * The end time for this text track cue
  6175. *
  6176. * @property {boolean} pauseOnExit
  6177. * Pause when the end time is reached if true.
  6178. *
  6179. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6180. */
  6181. /**
  6182. * A List of TextTrackCues.
  6183. *
  6184. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6185. */
  6186. var TextTrackCueList = /*#__PURE__*/function () {
  6187. /**
  6188. * Create an instance of this class..
  6189. *
  6190. * @param {Array} cues
  6191. * A list of cues to be initialized with
  6192. */
  6193. function TextTrackCueList(cues) {
  6194. TextTrackCueList.prototype.setCues_.call(this, cues);
  6195. /**
  6196. * @memberof TextTrackCueList
  6197. * @member {number} length
  6198. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6199. * @instance
  6200. */
  6201. Object.defineProperty(this, 'length', {
  6202. get: function get() {
  6203. return this.length_;
  6204. }
  6205. });
  6206. }
  6207. /**
  6208. * A setter for cues in this list. Creates getters
  6209. * an an index for the cues.
  6210. *
  6211. * @param {Array} cues
  6212. * An array of cues to set
  6213. *
  6214. * @private
  6215. */
  6216. var _proto = TextTrackCueList.prototype;
  6217. _proto.setCues_ = function setCues_(cues) {
  6218. var oldLength = this.length || 0;
  6219. var i = 0;
  6220. var l = cues.length;
  6221. this.cues_ = cues;
  6222. this.length_ = cues.length;
  6223. var defineProp = function defineProp(index) {
  6224. if (!('' + index in this)) {
  6225. Object.defineProperty(this, '' + index, {
  6226. get: function get() {
  6227. return this.cues_[index];
  6228. }
  6229. });
  6230. }
  6231. };
  6232. if (oldLength < l) {
  6233. i = oldLength;
  6234. for (; i < l; i++) {
  6235. defineProp.call(this, i);
  6236. }
  6237. }
  6238. }
  6239. /**
  6240. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6241. *
  6242. * @param {string} id
  6243. * The id of the cue that should be searched for.
  6244. *
  6245. * @return {TextTrackCueList~TextTrackCue|null}
  6246. * A single cue or null if none was found.
  6247. */
  6248. ;
  6249. _proto.getCueById = function getCueById(id) {
  6250. var result = null;
  6251. for (var i = 0, l = this.length; i < l; i++) {
  6252. var cue = this[i];
  6253. if (cue.id === id) {
  6254. result = cue;
  6255. break;
  6256. }
  6257. }
  6258. return result;
  6259. };
  6260. return TextTrackCueList;
  6261. }();
  6262. /**
  6263. * @file track-kinds.js
  6264. */
  6265. /**
  6266. * All possible `VideoTrackKind`s
  6267. *
  6268. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6269. * @typedef VideoTrack~Kind
  6270. * @enum
  6271. */
  6272. var VideoTrackKind = {
  6273. alternative: 'alternative',
  6274. captions: 'captions',
  6275. main: 'main',
  6276. sign: 'sign',
  6277. subtitles: 'subtitles',
  6278. commentary: 'commentary'
  6279. };
  6280. /**
  6281. * All possible `AudioTrackKind`s
  6282. *
  6283. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6284. * @typedef AudioTrack~Kind
  6285. * @enum
  6286. */
  6287. var AudioTrackKind = {
  6288. 'alternative': 'alternative',
  6289. 'descriptions': 'descriptions',
  6290. 'main': 'main',
  6291. 'main-desc': 'main-desc',
  6292. 'translation': 'translation',
  6293. 'commentary': 'commentary'
  6294. };
  6295. /**
  6296. * All possible `TextTrackKind`s
  6297. *
  6298. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6299. * @typedef TextTrack~Kind
  6300. * @enum
  6301. */
  6302. var TextTrackKind = {
  6303. subtitles: 'subtitles',
  6304. captions: 'captions',
  6305. descriptions: 'descriptions',
  6306. chapters: 'chapters',
  6307. metadata: 'metadata'
  6308. };
  6309. /**
  6310. * All possible `TextTrackMode`s
  6311. *
  6312. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6313. * @typedef TextTrack~Mode
  6314. * @enum
  6315. */
  6316. var TextTrackMode = {
  6317. disabled: 'disabled',
  6318. hidden: 'hidden',
  6319. showing: 'showing'
  6320. };
  6321. /**
  6322. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6323. * {@link VideoTrack}, and {@link TextTrack}.
  6324. *
  6325. * > Note: This class should not be used directly
  6326. *
  6327. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6328. * @extends EventTarget
  6329. * @abstract
  6330. */
  6331. var Track = /*#__PURE__*/function (_EventTarget) {
  6332. _inheritsLoose__default['default'](Track, _EventTarget);
  6333. /**
  6334. * Create an instance of this class.
  6335. *
  6336. * @param {Object} [options={}]
  6337. * Object of option names and values
  6338. *
  6339. * @param {string} [options.kind='']
  6340. * A valid kind for the track type you are creating.
  6341. *
  6342. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6343. * A unique id for this AudioTrack.
  6344. *
  6345. * @param {string} [options.label='']
  6346. * The menu label for this track.
  6347. *
  6348. * @param {string} [options.language='']
  6349. * A valid two character language code.
  6350. *
  6351. * @abstract
  6352. */
  6353. function Track(options) {
  6354. var _this;
  6355. if (options === void 0) {
  6356. options = {};
  6357. }
  6358. _this = _EventTarget.call(this) || this;
  6359. var trackProps = {
  6360. id: options.id || 'vjs_track_' + newGUID(),
  6361. kind: options.kind || '',
  6362. language: options.language || ''
  6363. };
  6364. var label = options.label || '';
  6365. /**
  6366. * @memberof Track
  6367. * @member {string} id
  6368. * The id of this track. Cannot be changed after creation.
  6369. * @instance
  6370. *
  6371. * @readonly
  6372. */
  6373. /**
  6374. * @memberof Track
  6375. * @member {string} kind
  6376. * The kind of track that this is. Cannot be changed after creation.
  6377. * @instance
  6378. *
  6379. * @readonly
  6380. */
  6381. /**
  6382. * @memberof Track
  6383. * @member {string} language
  6384. * The two letter language code for this track. Cannot be changed after
  6385. * creation.
  6386. * @instance
  6387. *
  6388. * @readonly
  6389. */
  6390. var _loop = function _loop(key) {
  6391. Object.defineProperty(_assertThisInitialized__default['default'](_this), key, {
  6392. get: function get() {
  6393. return trackProps[key];
  6394. },
  6395. set: function set() {}
  6396. });
  6397. };
  6398. for (var key in trackProps) {
  6399. _loop(key);
  6400. }
  6401. /**
  6402. * @memberof Track
  6403. * @member {string} label
  6404. * The label of this track. Cannot be changed after creation.
  6405. * @instance
  6406. *
  6407. * @fires Track#labelchange
  6408. */
  6409. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'label', {
  6410. get: function get() {
  6411. return label;
  6412. },
  6413. set: function set(newLabel) {
  6414. if (newLabel !== label) {
  6415. label = newLabel;
  6416. /**
  6417. * An event that fires when label changes on this track.
  6418. *
  6419. * > Note: This is not part of the spec!
  6420. *
  6421. * @event Track#labelchange
  6422. * @type {EventTarget~Event}
  6423. */
  6424. this.trigger('labelchange');
  6425. }
  6426. }
  6427. });
  6428. return _this;
  6429. }
  6430. return Track;
  6431. }(EventTarget$2);
  6432. /**
  6433. * @file url.js
  6434. * @module url
  6435. */
  6436. /**
  6437. * @typedef {Object} url:URLObject
  6438. *
  6439. * @property {string} protocol
  6440. * The protocol of the url that was parsed.
  6441. *
  6442. * @property {string} hostname
  6443. * The hostname of the url that was parsed.
  6444. *
  6445. * @property {string} port
  6446. * The port of the url that was parsed.
  6447. *
  6448. * @property {string} pathname
  6449. * The pathname of the url that was parsed.
  6450. *
  6451. * @property {string} search
  6452. * The search query of the url that was parsed.
  6453. *
  6454. * @property {string} hash
  6455. * The hash of the url that was parsed.
  6456. *
  6457. * @property {string} host
  6458. * The host of the url that was parsed.
  6459. */
  6460. /**
  6461. * Resolve and parse the elements of a URL.
  6462. *
  6463. * @function
  6464. * @param {String} url
  6465. * The url to parse
  6466. *
  6467. * @return {url:URLObject}
  6468. * An object of url details
  6469. */
  6470. var parseUrl = function parseUrl(url) {
  6471. // This entire method can be replace with URL once we are able to drop IE11
  6472. var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL
  6473. var a = document__default['default'].createElement('a');
  6474. a.href = url; // Copy the specific URL properties to a new object
  6475. // This is also needed for IE because the anchor loses its
  6476. // properties when it's removed from the dom
  6477. var details = {};
  6478. for (var i = 0; i < props.length; i++) {
  6479. details[props[i]] = a[props[i]];
  6480. } // IE adds the port to the host property unlike everyone else. If
  6481. // a port identifier is added for standard ports, strip it.
  6482. if (details.protocol === 'http:') {
  6483. details.host = details.host.replace(/:80$/, '');
  6484. }
  6485. if (details.protocol === 'https:') {
  6486. details.host = details.host.replace(/:443$/, '');
  6487. }
  6488. if (!details.protocol) {
  6489. details.protocol = window__default['default'].location.protocol;
  6490. }
  6491. /* istanbul ignore if */
  6492. if (!details.host) {
  6493. details.host = window__default['default'].location.host;
  6494. }
  6495. return details;
  6496. };
  6497. /**
  6498. * Get absolute version of relative URL. Used to tell Flash the correct URL.
  6499. *
  6500. * @function
  6501. * @param {string} url
  6502. * URL to make absolute
  6503. *
  6504. * @return {string}
  6505. * Absolute URL
  6506. *
  6507. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6508. */
  6509. var getAbsoluteURL = function getAbsoluteURL(url) {
  6510. // Check if absolute URL
  6511. if (!url.match(/^https?:\/\//)) {
  6512. // Convert to absolute URL. Flash hosted off-site needs an absolute URL.
  6513. // add the url to an anchor and let the browser parse the URL
  6514. var a = document__default['default'].createElement('a');
  6515. a.href = url;
  6516. url = a.href;
  6517. }
  6518. return url;
  6519. };
  6520. /**
  6521. * Returns the extension of the passed file name. It will return an empty string
  6522. * if passed an invalid path.
  6523. *
  6524. * @function
  6525. * @param {string} path
  6526. * The fileName path like '/path/to/file.mp4'
  6527. *
  6528. * @return {string}
  6529. * The extension in lower case or an empty string if no
  6530. * extension could be found.
  6531. */
  6532. var getFileExtension = function getFileExtension(path) {
  6533. if (typeof path === 'string') {
  6534. var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6535. var pathParts = splitPathRe.exec(path);
  6536. if (pathParts) {
  6537. return pathParts.pop().toLowerCase();
  6538. }
  6539. }
  6540. return '';
  6541. };
  6542. /**
  6543. * Returns whether the url passed is a cross domain request or not.
  6544. *
  6545. * @function
  6546. * @param {string} url
  6547. * The url to check.
  6548. *
  6549. * @param {Object} [winLoc]
  6550. * the domain to check the url against, defaults to window.location
  6551. *
  6552. * @param {string} [winLoc.protocol]
  6553. * The window location protocol defaults to window.location.protocol
  6554. *
  6555. * @param {string} [winLoc.host]
  6556. * The window location host defaults to window.location.host
  6557. *
  6558. * @return {boolean}
  6559. * Whether it is a cross domain request or not.
  6560. */
  6561. var isCrossOrigin = function isCrossOrigin(url, winLoc) {
  6562. if (winLoc === void 0) {
  6563. winLoc = window__default['default'].location;
  6564. }
  6565. var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol
  6566. var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin
  6567. // IE8 doesn't know location.origin, so we won't rely on it here
  6568. var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6569. return crossOrigin;
  6570. };
  6571. var Url = /*#__PURE__*/Object.freeze({
  6572. __proto__: null,
  6573. parseUrl: parseUrl,
  6574. getAbsoluteURL: getAbsoluteURL,
  6575. getFileExtension: getFileExtension,
  6576. isCrossOrigin: isCrossOrigin
  6577. });
  6578. /**
  6579. * Takes a webvtt file contents and parses it into cues
  6580. *
  6581. * @param {string} srcContent
  6582. * webVTT file contents
  6583. *
  6584. * @param {TextTrack} track
  6585. * TextTrack to add cues to. Cues come from the srcContent.
  6586. *
  6587. * @private
  6588. */
  6589. var parseCues = function parseCues(srcContent, track) {
  6590. var parser = new window__default['default'].WebVTT.Parser(window__default['default'], window__default['default'].vttjs, window__default['default'].WebVTT.StringDecoder());
  6591. var errors = [];
  6592. parser.oncue = function (cue) {
  6593. track.addCue(cue);
  6594. };
  6595. parser.onparsingerror = function (error) {
  6596. errors.push(error);
  6597. };
  6598. parser.onflush = function () {
  6599. track.trigger({
  6600. type: 'loadeddata',
  6601. target: track
  6602. });
  6603. };
  6604. parser.parse(srcContent);
  6605. if (errors.length > 0) {
  6606. if (window__default['default'].console && window__default['default'].console.groupCollapsed) {
  6607. window__default['default'].console.groupCollapsed("Text Track parsing errors for " + track.src);
  6608. }
  6609. errors.forEach(function (error) {
  6610. return log$1.error(error);
  6611. });
  6612. if (window__default['default'].console && window__default['default'].console.groupEnd) {
  6613. window__default['default'].console.groupEnd();
  6614. }
  6615. }
  6616. parser.flush();
  6617. };
  6618. /**
  6619. * Load a `TextTrack` from a specified url.
  6620. *
  6621. * @param {string} src
  6622. * Url to load track from.
  6623. *
  6624. * @param {TextTrack} track
  6625. * Track to add cues to. Comes from the content at the end of `url`.
  6626. *
  6627. * @private
  6628. */
  6629. var loadTrack = function loadTrack(src, track) {
  6630. var opts = {
  6631. uri: src
  6632. };
  6633. var crossOrigin = isCrossOrigin(src);
  6634. if (crossOrigin) {
  6635. opts.cors = crossOrigin;
  6636. }
  6637. var withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  6638. if (withCredentials) {
  6639. opts.withCredentials = withCredentials;
  6640. }
  6641. XHR__default['default'](opts, bind(this, function (err, response, responseBody) {
  6642. if (err) {
  6643. return log$1.error(err, response);
  6644. }
  6645. track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  6646. // NOTE: this is only used for the alt/video.novtt.js build
  6647. if (typeof window__default['default'].WebVTT !== 'function') {
  6648. if (track.tech_) {
  6649. // to prevent use before define eslint error, we define loadHandler
  6650. // as a let here
  6651. track.tech_.any(['vttjsloaded', 'vttjserror'], function (event) {
  6652. if (event.type === 'vttjserror') {
  6653. log$1.error("vttjs failed to load, stopping trying to process " + track.src);
  6654. return;
  6655. }
  6656. return parseCues(responseBody, track);
  6657. });
  6658. }
  6659. } else {
  6660. parseCues(responseBody, track);
  6661. }
  6662. }));
  6663. };
  6664. /**
  6665. * A representation of a single `TextTrack`.
  6666. *
  6667. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  6668. * @extends Track
  6669. */
  6670. var TextTrack = /*#__PURE__*/function (_Track) {
  6671. _inheritsLoose__default['default'](TextTrack, _Track);
  6672. /**
  6673. * Create an instance of this class.
  6674. *
  6675. * @param {Object} options={}
  6676. * Object of option names and values
  6677. *
  6678. * @param {Tech} options.tech
  6679. * A reference to the tech that owns this TextTrack.
  6680. *
  6681. * @param {TextTrack~Kind} [options.kind='subtitles']
  6682. * A valid text track kind.
  6683. *
  6684. * @param {TextTrack~Mode} [options.mode='disabled']
  6685. * A valid text track mode.
  6686. *
  6687. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6688. * A unique id for this TextTrack.
  6689. *
  6690. * @param {string} [options.label='']
  6691. * The menu label for this track.
  6692. *
  6693. * @param {string} [options.language='']
  6694. * A valid two character language code.
  6695. *
  6696. * @param {string} [options.srclang='']
  6697. * A valid two character language code. An alternative, but deprioritized
  6698. * version of `options.language`
  6699. *
  6700. * @param {string} [options.src]
  6701. * A url to TextTrack cues.
  6702. *
  6703. * @param {boolean} [options.default]
  6704. * If this track should default to on or off.
  6705. */
  6706. function TextTrack(options) {
  6707. var _this;
  6708. if (options === void 0) {
  6709. options = {};
  6710. }
  6711. if (!options.tech) {
  6712. throw new Error('A tech was not provided.');
  6713. }
  6714. var settings = mergeOptions$3(options, {
  6715. kind: TextTrackKind[options.kind] || 'subtitles',
  6716. language: options.language || options.srclang || ''
  6717. });
  6718. var mode = TextTrackMode[settings.mode] || 'disabled';
  6719. var default_ = settings["default"];
  6720. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  6721. mode = 'hidden';
  6722. }
  6723. _this = _Track.call(this, settings) || this;
  6724. _this.tech_ = settings.tech;
  6725. _this.cues_ = [];
  6726. _this.activeCues_ = [];
  6727. _this.preload_ = _this.tech_.preloadTextTracks !== false;
  6728. var cues = new TextTrackCueList(_this.cues_);
  6729. var activeCues = new TextTrackCueList(_this.activeCues_);
  6730. var changed = false;
  6731. _this.timeupdateHandler = bind(_assertThisInitialized__default['default'](_this), function (event) {
  6732. if (event === void 0) {
  6733. event = {};
  6734. }
  6735. if (this.tech_.isDisposed()) {
  6736. return;
  6737. }
  6738. if (!this.tech_.isReady_) {
  6739. if (event.type !== 'timeupdate') {
  6740. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6741. }
  6742. return;
  6743. } // Accessing this.activeCues for the side-effects of updating itself
  6744. // due to its nature as a getter function. Do not remove or cues will
  6745. // stop updating!
  6746. // Use the setter to prevent deletion from uglify (pure_getters rule)
  6747. this.activeCues = this.activeCues;
  6748. if (changed) {
  6749. this.trigger('cuechange');
  6750. changed = false;
  6751. }
  6752. if (event.type !== 'timeupdate') {
  6753. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  6754. }
  6755. });
  6756. var disposeHandler = function disposeHandler() {
  6757. _this.stopTracking();
  6758. };
  6759. _this.tech_.one('dispose', disposeHandler);
  6760. if (mode !== 'disabled') {
  6761. _this.startTracking();
  6762. }
  6763. Object.defineProperties(_assertThisInitialized__default['default'](_this), {
  6764. /**
  6765. * @memberof TextTrack
  6766. * @member {boolean} default
  6767. * If this track was set to be on or off by default. Cannot be changed after
  6768. * creation.
  6769. * @instance
  6770. *
  6771. * @readonly
  6772. */
  6773. "default": {
  6774. get: function get() {
  6775. return default_;
  6776. },
  6777. set: function set() {}
  6778. },
  6779. /**
  6780. * @memberof TextTrack
  6781. * @member {string} mode
  6782. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  6783. * not be set if setting to an invalid mode.
  6784. * @instance
  6785. *
  6786. * @fires TextTrack#modechange
  6787. */
  6788. mode: {
  6789. get: function get() {
  6790. return mode;
  6791. },
  6792. set: function set(newMode) {
  6793. if (!TextTrackMode[newMode]) {
  6794. return;
  6795. }
  6796. if (mode === newMode) {
  6797. return;
  6798. }
  6799. mode = newMode;
  6800. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  6801. // On-demand load.
  6802. loadTrack(this.src, this);
  6803. }
  6804. this.stopTracking();
  6805. if (mode !== 'disabled') {
  6806. this.startTracking();
  6807. }
  6808. /**
  6809. * An event that fires when mode changes on this track. This allows
  6810. * the TextTrackList that holds this track to act accordingly.
  6811. *
  6812. * > Note: This is not part of the spec!
  6813. *
  6814. * @event TextTrack#modechange
  6815. * @type {EventTarget~Event}
  6816. */
  6817. this.trigger('modechange');
  6818. }
  6819. },
  6820. /**
  6821. * @memberof TextTrack
  6822. * @member {TextTrackCueList} cues
  6823. * The text track cue list for this TextTrack.
  6824. * @instance
  6825. */
  6826. cues: {
  6827. get: function get() {
  6828. if (!this.loaded_) {
  6829. return null;
  6830. }
  6831. return cues;
  6832. },
  6833. set: function set() {}
  6834. },
  6835. /**
  6836. * @memberof TextTrack
  6837. * @member {TextTrackCueList} activeCues
  6838. * The list text track cues that are currently active for this TextTrack.
  6839. * @instance
  6840. */
  6841. activeCues: {
  6842. get: function get() {
  6843. if (!this.loaded_) {
  6844. return null;
  6845. } // nothing to do
  6846. if (this.cues.length === 0) {
  6847. return activeCues;
  6848. }
  6849. var ct = this.tech_.currentTime();
  6850. var active = [];
  6851. for (var i = 0, l = this.cues.length; i < l; i++) {
  6852. var cue = this.cues[i];
  6853. if (cue.startTime <= ct && cue.endTime >= ct) {
  6854. active.push(cue);
  6855. } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) {
  6856. active.push(cue);
  6857. }
  6858. }
  6859. changed = false;
  6860. if (active.length !== this.activeCues_.length) {
  6861. changed = true;
  6862. } else {
  6863. for (var _i = 0; _i < active.length; _i++) {
  6864. if (this.activeCues_.indexOf(active[_i]) === -1) {
  6865. changed = true;
  6866. }
  6867. }
  6868. }
  6869. this.activeCues_ = active;
  6870. activeCues.setCues_(this.activeCues_);
  6871. return activeCues;
  6872. },
  6873. // /!\ Keep this setter empty (see the timeupdate handler above)
  6874. set: function set() {}
  6875. }
  6876. });
  6877. if (settings.src) {
  6878. _this.src = settings.src;
  6879. if (!_this.preload_) {
  6880. // Tracks will load on-demand.
  6881. // Act like we're loaded for other purposes.
  6882. _this.loaded_ = true;
  6883. }
  6884. if (_this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  6885. loadTrack(_this.src, _assertThisInitialized__default['default'](_this));
  6886. }
  6887. } else {
  6888. _this.loaded_ = true;
  6889. }
  6890. return _this;
  6891. }
  6892. var _proto = TextTrack.prototype;
  6893. _proto.startTracking = function startTracking() {
  6894. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  6895. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  6896. this.tech_.on('timeupdate', this.timeupdateHandler);
  6897. };
  6898. _proto.stopTracking = function stopTracking() {
  6899. if (this.rvf_) {
  6900. this.tech_.cancelVideoFrameCallback(this.rvf_);
  6901. this.rvf_ = undefined;
  6902. }
  6903. this.tech_.off('timeupdate', this.timeupdateHandler);
  6904. }
  6905. /**
  6906. * Add a cue to the internal list of cues.
  6907. *
  6908. * @param {TextTrack~Cue} cue
  6909. * The cue to add to our internal list
  6910. */
  6911. ;
  6912. _proto.addCue = function addCue(originalCue) {
  6913. var cue = originalCue;
  6914. if (window__default['default'].vttjs && !(originalCue instanceof window__default['default'].vttjs.VTTCue)) {
  6915. cue = new window__default['default'].vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  6916. for (var prop in originalCue) {
  6917. if (!(prop in cue)) {
  6918. cue[prop] = originalCue[prop];
  6919. }
  6920. } // make sure that `id` is copied over
  6921. cue.id = originalCue.id;
  6922. cue.originalCue_ = originalCue;
  6923. }
  6924. var tracks = this.tech_.textTracks();
  6925. for (var i = 0; i < tracks.length; i++) {
  6926. if (tracks[i] !== this) {
  6927. tracks[i].removeCue(cue);
  6928. }
  6929. }
  6930. this.cues_.push(cue);
  6931. this.cues.setCues_(this.cues_);
  6932. }
  6933. /**
  6934. * Remove a cue from our internal list
  6935. *
  6936. * @param {TextTrack~Cue} removeCue
  6937. * The cue to remove from our internal list
  6938. */
  6939. ;
  6940. _proto.removeCue = function removeCue(_removeCue) {
  6941. var i = this.cues_.length;
  6942. while (i--) {
  6943. var cue = this.cues_[i];
  6944. if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) {
  6945. this.cues_.splice(i, 1);
  6946. this.cues.setCues_(this.cues_);
  6947. break;
  6948. }
  6949. }
  6950. };
  6951. return TextTrack;
  6952. }(Track);
  6953. /**
  6954. * cuechange - One or more cues in the track have become active or stopped being active.
  6955. */
  6956. TextTrack.prototype.allowedEvents_ = {
  6957. cuechange: 'cuechange'
  6958. };
  6959. /**
  6960. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  6961. * only one `AudioTrack` in the list will be enabled at a time.
  6962. *
  6963. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  6964. * @extends Track
  6965. */
  6966. var AudioTrack = /*#__PURE__*/function (_Track) {
  6967. _inheritsLoose__default['default'](AudioTrack, _Track);
  6968. /**
  6969. * Create an instance of this class.
  6970. *
  6971. * @param {Object} [options={}]
  6972. * Object of option names and values
  6973. *
  6974. * @param {AudioTrack~Kind} [options.kind='']
  6975. * A valid audio track kind
  6976. *
  6977. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6978. * A unique id for this AudioTrack.
  6979. *
  6980. * @param {string} [options.label='']
  6981. * The menu label for this track.
  6982. *
  6983. * @param {string} [options.language='']
  6984. * A valid two character language code.
  6985. *
  6986. * @param {boolean} [options.enabled]
  6987. * If this track is the one that is currently playing. If this track is part of
  6988. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  6989. */
  6990. function AudioTrack(options) {
  6991. var _this;
  6992. if (options === void 0) {
  6993. options = {};
  6994. }
  6995. var settings = mergeOptions$3(options, {
  6996. kind: AudioTrackKind[options.kind] || ''
  6997. });
  6998. _this = _Track.call(this, settings) || this;
  6999. var enabled = false;
  7000. /**
  7001. * @memberof AudioTrack
  7002. * @member {boolean} enabled
  7003. * If this `AudioTrack` is enabled or not. When setting this will
  7004. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7005. * @instance
  7006. *
  7007. * @fires VideoTrack#selectedchange
  7008. */
  7009. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'enabled', {
  7010. get: function get() {
  7011. return enabled;
  7012. },
  7013. set: function set(newEnabled) {
  7014. // an invalid or unchanged value
  7015. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7016. return;
  7017. }
  7018. enabled = newEnabled;
  7019. /**
  7020. * An event that fires when enabled changes on this track. This allows
  7021. * the AudioTrackList that holds this track to act accordingly.
  7022. *
  7023. * > Note: This is not part of the spec! Native tracks will do
  7024. * this internally without an event.
  7025. *
  7026. * @event AudioTrack#enabledchange
  7027. * @type {EventTarget~Event}
  7028. */
  7029. this.trigger('enabledchange');
  7030. }
  7031. }); // if the user sets this track to selected then
  7032. // set selected to that true value otherwise
  7033. // we keep it false
  7034. if (settings.enabled) {
  7035. _this.enabled = settings.enabled;
  7036. }
  7037. _this.loaded_ = true;
  7038. return _this;
  7039. }
  7040. return AudioTrack;
  7041. }(Track);
  7042. /**
  7043. * A representation of a single `VideoTrack`.
  7044. *
  7045. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7046. * @extends Track
  7047. */
  7048. var VideoTrack = /*#__PURE__*/function (_Track) {
  7049. _inheritsLoose__default['default'](VideoTrack, _Track);
  7050. /**
  7051. * Create an instance of this class.
  7052. *
  7053. * @param {Object} [options={}]
  7054. * Object of option names and values
  7055. *
  7056. * @param {string} [options.kind='']
  7057. * A valid {@link VideoTrack~Kind}
  7058. *
  7059. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7060. * A unique id for this AudioTrack.
  7061. *
  7062. * @param {string} [options.label='']
  7063. * The menu label for this track.
  7064. *
  7065. * @param {string} [options.language='']
  7066. * A valid two character language code.
  7067. *
  7068. * @param {boolean} [options.selected]
  7069. * If this track is the one that is currently playing.
  7070. */
  7071. function VideoTrack(options) {
  7072. var _this;
  7073. if (options === void 0) {
  7074. options = {};
  7075. }
  7076. var settings = mergeOptions$3(options, {
  7077. kind: VideoTrackKind[options.kind] || ''
  7078. });
  7079. _this = _Track.call(this, settings) || this;
  7080. var selected = false;
  7081. /**
  7082. * @memberof VideoTrack
  7083. * @member {boolean} selected
  7084. * If this `VideoTrack` is selected or not. When setting this will
  7085. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7086. * @instance
  7087. *
  7088. * @fires VideoTrack#selectedchange
  7089. */
  7090. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'selected', {
  7091. get: function get() {
  7092. return selected;
  7093. },
  7094. set: function set(newSelected) {
  7095. // an invalid or unchanged value
  7096. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7097. return;
  7098. }
  7099. selected = newSelected;
  7100. /**
  7101. * An event that fires when selected changes on this track. This allows
  7102. * the VideoTrackList that holds this track to act accordingly.
  7103. *
  7104. * > Note: This is not part of the spec! Native tracks will do
  7105. * this internally without an event.
  7106. *
  7107. * @event VideoTrack#selectedchange
  7108. * @type {EventTarget~Event}
  7109. */
  7110. this.trigger('selectedchange');
  7111. }
  7112. }); // if the user sets this track to selected then
  7113. // set selected to that true value otherwise
  7114. // we keep it false
  7115. if (settings.selected) {
  7116. _this.selected = settings.selected;
  7117. }
  7118. return _this;
  7119. }
  7120. return VideoTrack;
  7121. }(Track);
  7122. /**
  7123. * @memberof HTMLTrackElement
  7124. * @typedef {HTMLTrackElement~ReadyState}
  7125. * @enum {number}
  7126. */
  7127. var NONE = 0;
  7128. var LOADING = 1;
  7129. var LOADED = 2;
  7130. var ERROR = 3;
  7131. /**
  7132. * A single track represented in the DOM.
  7133. *
  7134. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7135. * @extends EventTarget
  7136. */
  7137. var HTMLTrackElement = /*#__PURE__*/function (_EventTarget) {
  7138. _inheritsLoose__default['default'](HTMLTrackElement, _EventTarget);
  7139. /**
  7140. * Create an instance of this class.
  7141. *
  7142. * @param {Object} options={}
  7143. * Object of option names and values
  7144. *
  7145. * @param {Tech} options.tech
  7146. * A reference to the tech that owns this HTMLTrackElement.
  7147. *
  7148. * @param {TextTrack~Kind} [options.kind='subtitles']
  7149. * A valid text track kind.
  7150. *
  7151. * @param {TextTrack~Mode} [options.mode='disabled']
  7152. * A valid text track mode.
  7153. *
  7154. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7155. * A unique id for this TextTrack.
  7156. *
  7157. * @param {string} [options.label='']
  7158. * The menu label for this track.
  7159. *
  7160. * @param {string} [options.language='']
  7161. * A valid two character language code.
  7162. *
  7163. * @param {string} [options.srclang='']
  7164. * A valid two character language code. An alternative, but deprioritized
  7165. * version of `options.language`
  7166. *
  7167. * @param {string} [options.src]
  7168. * A url to TextTrack cues.
  7169. *
  7170. * @param {boolean} [options.default]
  7171. * If this track should default to on or off.
  7172. */
  7173. function HTMLTrackElement(options) {
  7174. var _this;
  7175. if (options === void 0) {
  7176. options = {};
  7177. }
  7178. _this = _EventTarget.call(this) || this;
  7179. var readyState;
  7180. var track = new TextTrack(options);
  7181. _this.kind = track.kind;
  7182. _this.src = track.src;
  7183. _this.srclang = track.language;
  7184. _this.label = track.label;
  7185. _this["default"] = track["default"];
  7186. Object.defineProperties(_assertThisInitialized__default['default'](_this), {
  7187. /**
  7188. * @memberof HTMLTrackElement
  7189. * @member {HTMLTrackElement~ReadyState} readyState
  7190. * The current ready state of the track element.
  7191. * @instance
  7192. */
  7193. readyState: {
  7194. get: function get() {
  7195. return readyState;
  7196. }
  7197. },
  7198. /**
  7199. * @memberof HTMLTrackElement
  7200. * @member {TextTrack} track
  7201. * The underlying TextTrack object.
  7202. * @instance
  7203. *
  7204. */
  7205. track: {
  7206. get: function get() {
  7207. return track;
  7208. }
  7209. }
  7210. });
  7211. readyState = NONE;
  7212. /**
  7213. * @listens TextTrack#loadeddata
  7214. * @fires HTMLTrackElement#load
  7215. */
  7216. track.addEventListener('loadeddata', function () {
  7217. readyState = LOADED;
  7218. _this.trigger({
  7219. type: 'load',
  7220. target: _assertThisInitialized__default['default'](_this)
  7221. });
  7222. });
  7223. return _this;
  7224. }
  7225. return HTMLTrackElement;
  7226. }(EventTarget$2);
  7227. HTMLTrackElement.prototype.allowedEvents_ = {
  7228. load: 'load'
  7229. };
  7230. HTMLTrackElement.NONE = NONE;
  7231. HTMLTrackElement.LOADING = LOADING;
  7232. HTMLTrackElement.LOADED = LOADED;
  7233. HTMLTrackElement.ERROR = ERROR;
  7234. /*
  7235. * This file contains all track properties that are used in
  7236. * player.js, tech.js, html5.js and possibly other techs in the future.
  7237. */
  7238. var NORMAL = {
  7239. audio: {
  7240. ListClass: AudioTrackList,
  7241. TrackClass: AudioTrack,
  7242. capitalName: 'Audio'
  7243. },
  7244. video: {
  7245. ListClass: VideoTrackList,
  7246. TrackClass: VideoTrack,
  7247. capitalName: 'Video'
  7248. },
  7249. text: {
  7250. ListClass: TextTrackList,
  7251. TrackClass: TextTrack,
  7252. capitalName: 'Text'
  7253. }
  7254. };
  7255. Object.keys(NORMAL).forEach(function (type) {
  7256. NORMAL[type].getterName = type + "Tracks";
  7257. NORMAL[type].privateName = type + "Tracks_";
  7258. });
  7259. var REMOTE = {
  7260. remoteText: {
  7261. ListClass: TextTrackList,
  7262. TrackClass: TextTrack,
  7263. capitalName: 'RemoteText',
  7264. getterName: 'remoteTextTracks',
  7265. privateName: 'remoteTextTracks_'
  7266. },
  7267. remoteTextEl: {
  7268. ListClass: HtmlTrackElementList,
  7269. TrackClass: HTMLTrackElement,
  7270. capitalName: 'RemoteTextTrackEls',
  7271. getterName: 'remoteTextTrackEls',
  7272. privateName: 'remoteTextTrackEls_'
  7273. }
  7274. };
  7275. var ALL = _extends__default['default']({}, NORMAL, REMOTE);
  7276. REMOTE.names = Object.keys(REMOTE);
  7277. NORMAL.names = Object.keys(NORMAL);
  7278. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7279. /**
  7280. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7281. * that just contains the src url alone.
  7282. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7283. * `var SourceString = 'http://example.com/some-video.mp4';`
  7284. *
  7285. * @typedef {Object|string} Tech~SourceObject
  7286. *
  7287. * @property {string} src
  7288. * The url to the source
  7289. *
  7290. * @property {string} type
  7291. * The mime type of the source
  7292. */
  7293. /**
  7294. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7295. *
  7296. * @private
  7297. *
  7298. * @param {Tech} self
  7299. * An instance of the Tech class.
  7300. *
  7301. * @param {string} kind
  7302. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7303. *
  7304. * @param {string} [label]
  7305. * Label to identify the text track
  7306. *
  7307. * @param {string} [language]
  7308. * Two letter language abbreviation
  7309. *
  7310. * @param {Object} [options={}]
  7311. * An object with additional text track options
  7312. *
  7313. * @return {TextTrack}
  7314. * The text track that was created.
  7315. */
  7316. function createTrackHelper(self, kind, label, language, options) {
  7317. if (options === void 0) {
  7318. options = {};
  7319. }
  7320. var tracks = self.textTracks();
  7321. options.kind = kind;
  7322. if (label) {
  7323. options.label = label;
  7324. }
  7325. if (language) {
  7326. options.language = language;
  7327. }
  7328. options.tech = self;
  7329. var track = new ALL.text.TrackClass(options);
  7330. tracks.addTrack(track);
  7331. return track;
  7332. }
  7333. /**
  7334. * This is the base class for media playback technology controllers, such as
  7335. * {@link HTML5}
  7336. *
  7337. * @extends Component
  7338. */
  7339. var Tech = /*#__PURE__*/function (_Component) {
  7340. _inheritsLoose__default['default'](Tech, _Component);
  7341. /**
  7342. * Create an instance of this Tech.
  7343. *
  7344. * @param {Object} [options]
  7345. * The key/value store of player options.
  7346. *
  7347. * @param {Component~ReadyCallback} ready
  7348. * Callback function to call when the `HTML5` Tech is ready.
  7349. */
  7350. function Tech(options, ready) {
  7351. var _this;
  7352. if (options === void 0) {
  7353. options = {};
  7354. }
  7355. if (ready === void 0) {
  7356. ready = function ready() {};
  7357. }
  7358. // we don't want the tech to report user activity automatically.
  7359. // This is done manually in addControlsListeners
  7360. options.reportTouchActivity = false;
  7361. _this = _Component.call(this, null, options, ready) || this;
  7362. _this.onDurationChange_ = function (e) {
  7363. return _this.onDurationChange(e);
  7364. };
  7365. _this.trackProgress_ = function (e) {
  7366. return _this.trackProgress(e);
  7367. };
  7368. _this.trackCurrentTime_ = function (e) {
  7369. return _this.trackCurrentTime(e);
  7370. };
  7371. _this.stopTrackingCurrentTime_ = function (e) {
  7372. return _this.stopTrackingCurrentTime(e);
  7373. };
  7374. _this.disposeSourceHandler_ = function (e) {
  7375. return _this.disposeSourceHandler(e);
  7376. };
  7377. _this.queuedHanders_ = new Set(); // keep track of whether the current source has played at all to
  7378. // implement a very limited played()
  7379. _this.hasStarted_ = false;
  7380. _this.on('playing', function () {
  7381. this.hasStarted_ = true;
  7382. });
  7383. _this.on('loadstart', function () {
  7384. this.hasStarted_ = false;
  7385. });
  7386. ALL.names.forEach(function (name) {
  7387. var props = ALL[name];
  7388. if (options && options[props.getterName]) {
  7389. _this[props.privateName] = options[props.getterName];
  7390. }
  7391. }); // Manually track progress in cases where the browser/tech doesn't report it.
  7392. if (!_this.featuresProgressEvents) {
  7393. _this.manualProgressOn();
  7394. } // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7395. if (!_this.featuresTimeupdateEvents) {
  7396. _this.manualTimeUpdatesOn();
  7397. }
  7398. ['Text', 'Audio', 'Video'].forEach(function (track) {
  7399. if (options["native" + track + "Tracks"] === false) {
  7400. _this["featuresNative" + track + "Tracks"] = false;
  7401. }
  7402. });
  7403. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7404. _this.featuresNativeTextTracks = false;
  7405. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7406. _this.featuresNativeTextTracks = true;
  7407. }
  7408. if (!_this.featuresNativeTextTracks) {
  7409. _this.emulateTextTracks();
  7410. }
  7411. _this.preloadTextTracks = options.preloadTextTracks !== false;
  7412. _this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7413. _this.initTrackListeners(); // Turn on component tap events only if not using native controls
  7414. if (!options.nativeControlsForTouch) {
  7415. _this.emitTapEvents();
  7416. }
  7417. if (_this.constructor) {
  7418. _this.name_ = _this.constructor.name || 'Unknown Tech';
  7419. }
  7420. return _this;
  7421. }
  7422. /**
  7423. * A special function to trigger source set in a way that will allow player
  7424. * to re-trigger if the player or tech are not ready yet.
  7425. *
  7426. * @fires Tech#sourceset
  7427. * @param {string} src The source string at the time of the source changing.
  7428. */
  7429. var _proto = Tech.prototype;
  7430. _proto.triggerSourceset = function triggerSourceset(src) {
  7431. var _this2 = this;
  7432. if (!this.isReady_) {
  7433. // on initial ready we have to trigger source set
  7434. // 1ms after ready so that player can watch for it.
  7435. this.one('ready', function () {
  7436. return _this2.setTimeout(function () {
  7437. return _this2.triggerSourceset(src);
  7438. }, 1);
  7439. });
  7440. }
  7441. /**
  7442. * Fired when the source is set on the tech causing the media element
  7443. * to reload.
  7444. *
  7445. * @see {@link Player#event:sourceset}
  7446. * @event Tech#sourceset
  7447. * @type {EventTarget~Event}
  7448. */
  7449. this.trigger({
  7450. src: src,
  7451. type: 'sourceset'
  7452. });
  7453. }
  7454. /* Fallbacks for unsupported event types
  7455. ================================================================================ */
  7456. /**
  7457. * Polyfill the `progress` event for browsers that don't support it natively.
  7458. *
  7459. * @see {@link Tech#trackProgress}
  7460. */
  7461. ;
  7462. _proto.manualProgressOn = function manualProgressOn() {
  7463. this.on('durationchange', this.onDurationChange_);
  7464. this.manualProgress = true; // Trigger progress watching when a source begins loading
  7465. this.one('ready', this.trackProgress_);
  7466. }
  7467. /**
  7468. * Turn off the polyfill for `progress` events that was created in
  7469. * {@link Tech#manualProgressOn}
  7470. */
  7471. ;
  7472. _proto.manualProgressOff = function manualProgressOff() {
  7473. this.manualProgress = false;
  7474. this.stopTrackingProgress();
  7475. this.off('durationchange', this.onDurationChange_);
  7476. }
  7477. /**
  7478. * This is used to trigger a `progress` event when the buffered percent changes. It
  7479. * sets an interval function that will be called every 500 milliseconds to check if the
  7480. * buffer end percent has changed.
  7481. *
  7482. * > This function is called by {@link Tech#manualProgressOn}
  7483. *
  7484. * @param {EventTarget~Event} event
  7485. * The `ready` event that caused this to run.
  7486. *
  7487. * @listens Tech#ready
  7488. * @fires Tech#progress
  7489. */
  7490. ;
  7491. _proto.trackProgress = function trackProgress(event) {
  7492. this.stopTrackingProgress();
  7493. this.progressInterval = this.setInterval(bind(this, function () {
  7494. // Don't trigger unless buffered amount is greater than last time
  7495. var numBufferedPercent = this.bufferedPercent();
  7496. if (this.bufferedPercent_ !== numBufferedPercent) {
  7497. /**
  7498. * See {@link Player#progress}
  7499. *
  7500. * @event Tech#progress
  7501. * @type {EventTarget~Event}
  7502. */
  7503. this.trigger('progress');
  7504. }
  7505. this.bufferedPercent_ = numBufferedPercent;
  7506. if (numBufferedPercent === 1) {
  7507. this.stopTrackingProgress();
  7508. }
  7509. }), 500);
  7510. }
  7511. /**
  7512. * Update our internal duration on a `durationchange` event by calling
  7513. * {@link Tech#duration}.
  7514. *
  7515. * @param {EventTarget~Event} event
  7516. * The `durationchange` event that caused this to run.
  7517. *
  7518. * @listens Tech#durationchange
  7519. */
  7520. ;
  7521. _proto.onDurationChange = function onDurationChange(event) {
  7522. this.duration_ = this.duration();
  7523. }
  7524. /**
  7525. * Get and create a `TimeRange` object for buffering.
  7526. *
  7527. * @return {TimeRange}
  7528. * The time range object that was created.
  7529. */
  7530. ;
  7531. _proto.buffered = function buffered() {
  7532. return createTimeRanges(0, 0);
  7533. }
  7534. /**
  7535. * Get the percentage of the current video that is currently buffered.
  7536. *
  7537. * @return {number}
  7538. * A number from 0 to 1 that represents the decimal percentage of the
  7539. * video that is buffered.
  7540. *
  7541. */
  7542. ;
  7543. _proto.bufferedPercent = function bufferedPercent$1() {
  7544. return bufferedPercent(this.buffered(), this.duration_);
  7545. }
  7546. /**
  7547. * Turn off the polyfill for `progress` events that was created in
  7548. * {@link Tech#manualProgressOn}
  7549. * Stop manually tracking progress events by clearing the interval that was set in
  7550. * {@link Tech#trackProgress}.
  7551. */
  7552. ;
  7553. _proto.stopTrackingProgress = function stopTrackingProgress() {
  7554. this.clearInterval(this.progressInterval);
  7555. }
  7556. /**
  7557. * Polyfill the `timeupdate` event for browsers that don't support it.
  7558. *
  7559. * @see {@link Tech#trackCurrentTime}
  7560. */
  7561. ;
  7562. _proto.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
  7563. this.manualTimeUpdates = true;
  7564. this.on('play', this.trackCurrentTime_);
  7565. this.on('pause', this.stopTrackingCurrentTime_);
  7566. }
  7567. /**
  7568. * Turn off the polyfill for `timeupdate` events that was created in
  7569. * {@link Tech#manualTimeUpdatesOn}
  7570. */
  7571. ;
  7572. _proto.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
  7573. this.manualTimeUpdates = false;
  7574. this.stopTrackingCurrentTime();
  7575. this.off('play', this.trackCurrentTime_);
  7576. this.off('pause', this.stopTrackingCurrentTime_);
  7577. }
  7578. /**
  7579. * Sets up an interval function to track current time and trigger `timeupdate` every
  7580. * 250 milliseconds.
  7581. *
  7582. * @listens Tech#play
  7583. * @triggers Tech#timeupdate
  7584. */
  7585. ;
  7586. _proto.trackCurrentTime = function trackCurrentTime() {
  7587. if (this.currentTimeInterval) {
  7588. this.stopTrackingCurrentTime();
  7589. }
  7590. this.currentTimeInterval = this.setInterval(function () {
  7591. /**
  7592. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  7593. *
  7594. * @event Tech#timeupdate
  7595. * @type {EventTarget~Event}
  7596. */
  7597. this.trigger({
  7598. type: 'timeupdate',
  7599. target: this,
  7600. manuallyTriggered: true
  7601. }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  7602. }, 250);
  7603. }
  7604. /**
  7605. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  7606. * `timeupdate` event is no longer triggered.
  7607. *
  7608. * @listens {Tech#pause}
  7609. */
  7610. ;
  7611. _proto.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
  7612. this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen,
  7613. // the progress bar won't make it all the way to the end
  7614. this.trigger({
  7615. type: 'timeupdate',
  7616. target: this,
  7617. manuallyTriggered: true
  7618. });
  7619. }
  7620. /**
  7621. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  7622. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  7623. *
  7624. * @fires Component#dispose
  7625. */
  7626. ;
  7627. _proto.dispose = function dispose() {
  7628. // clear out all tracks because we can't reuse them between techs
  7629. this.clearTracks(NORMAL.names); // Turn off any manual progress or timeupdate tracking
  7630. if (this.manualProgress) {
  7631. this.manualProgressOff();
  7632. }
  7633. if (this.manualTimeUpdates) {
  7634. this.manualTimeUpdatesOff();
  7635. }
  7636. _Component.prototype.dispose.call(this);
  7637. }
  7638. /**
  7639. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  7640. *
  7641. * > Note: Techs without source handlers should call this between sources for `video`
  7642. * & `audio` tracks. You don't want to use them between tracks!
  7643. *
  7644. * @param {string[]|string} types
  7645. * TrackList names to clear, valid names are `video`, `audio`, and
  7646. * `text`.
  7647. */
  7648. ;
  7649. _proto.clearTracks = function clearTracks(types) {
  7650. var _this3 = this;
  7651. types = [].concat(types); // clear out all tracks because we can't reuse them between techs
  7652. types.forEach(function (type) {
  7653. var list = _this3[type + "Tracks"]() || [];
  7654. var i = list.length;
  7655. while (i--) {
  7656. var track = list[i];
  7657. if (type === 'text') {
  7658. _this3.removeRemoteTextTrack(track);
  7659. }
  7660. list.removeTrack(track);
  7661. }
  7662. });
  7663. }
  7664. /**
  7665. * Remove any TextTracks added via addRemoteTextTrack that are
  7666. * flagged for automatic garbage collection
  7667. */
  7668. ;
  7669. _proto.cleanupAutoTextTracks = function cleanupAutoTextTracks() {
  7670. var list = this.autoRemoteTextTracks_ || [];
  7671. var i = list.length;
  7672. while (i--) {
  7673. var track = list[i];
  7674. this.removeRemoteTextTrack(track);
  7675. }
  7676. }
  7677. /**
  7678. * Reset the tech, which will removes all sources and reset the internal readyState.
  7679. *
  7680. * @abstract
  7681. */
  7682. ;
  7683. _proto.reset = function reset() {}
  7684. /**
  7685. * Get the value of `crossOrigin` from the tech.
  7686. *
  7687. * @abstract
  7688. *
  7689. * @see {Html5#crossOrigin}
  7690. */
  7691. ;
  7692. _proto.crossOrigin = function crossOrigin() {}
  7693. /**
  7694. * Set the value of `crossOrigin` on the tech.
  7695. *
  7696. * @abstract
  7697. *
  7698. * @param {string} crossOrigin the crossOrigin value
  7699. * @see {Html5#setCrossOrigin}
  7700. */
  7701. ;
  7702. _proto.setCrossOrigin = function setCrossOrigin() {}
  7703. /**
  7704. * Get or set an error on the Tech.
  7705. *
  7706. * @param {MediaError} [err]
  7707. * Error to set on the Tech
  7708. *
  7709. * @return {MediaError|null}
  7710. * The current error object on the tech, or null if there isn't one.
  7711. */
  7712. ;
  7713. _proto.error = function error(err) {
  7714. if (err !== undefined) {
  7715. this.error_ = new MediaError(err);
  7716. this.trigger('error');
  7717. }
  7718. return this.error_;
  7719. }
  7720. /**
  7721. * Returns the `TimeRange`s that have been played through for the current source.
  7722. *
  7723. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  7724. * It only checks whether the source has played at all or not.
  7725. *
  7726. * @return {TimeRange}
  7727. * - A single time range if this video has played
  7728. * - An empty set of ranges if not.
  7729. */
  7730. ;
  7731. _proto.played = function played() {
  7732. if (this.hasStarted_) {
  7733. return createTimeRanges(0, 0);
  7734. }
  7735. return createTimeRanges();
  7736. }
  7737. /**
  7738. * Start playback
  7739. *
  7740. * @abstract
  7741. *
  7742. * @see {Html5#play}
  7743. */
  7744. ;
  7745. _proto.play = function play() {}
  7746. /**
  7747. * Set whether we are scrubbing or not
  7748. *
  7749. * @abstract
  7750. *
  7751. * @see {Html5#setScrubbing}
  7752. */
  7753. ;
  7754. _proto.setScrubbing = function setScrubbing() {}
  7755. /**
  7756. * Get whether we are scrubbing or not
  7757. *
  7758. * @abstract
  7759. *
  7760. * @see {Html5#scrubbing}
  7761. */
  7762. ;
  7763. _proto.scrubbing = function scrubbing() {}
  7764. /**
  7765. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  7766. * previously called.
  7767. *
  7768. * @fires Tech#timeupdate
  7769. */
  7770. ;
  7771. _proto.setCurrentTime = function setCurrentTime() {
  7772. // improve the accuracy of manual timeupdates
  7773. if (this.manualTimeUpdates) {
  7774. /**
  7775. * A manual `timeupdate` event.
  7776. *
  7777. * @event Tech#timeupdate
  7778. * @type {EventTarget~Event}
  7779. */
  7780. this.trigger({
  7781. type: 'timeupdate',
  7782. target: this,
  7783. manuallyTriggered: true
  7784. });
  7785. }
  7786. }
  7787. /**
  7788. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  7789. * {@link TextTrackList} events.
  7790. *
  7791. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  7792. *
  7793. * @fires Tech#audiotrackchange
  7794. * @fires Tech#videotrackchange
  7795. * @fires Tech#texttrackchange
  7796. */
  7797. ;
  7798. _proto.initTrackListeners = function initTrackListeners() {
  7799. var _this4 = this;
  7800. /**
  7801. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  7802. *
  7803. * @event Tech#audiotrackchange
  7804. * @type {EventTarget~Event}
  7805. */
  7806. /**
  7807. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  7808. *
  7809. * @event Tech#videotrackchange
  7810. * @type {EventTarget~Event}
  7811. */
  7812. /**
  7813. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  7814. *
  7815. * @event Tech#texttrackchange
  7816. * @type {EventTarget~Event}
  7817. */
  7818. NORMAL.names.forEach(function (name) {
  7819. var props = NORMAL[name];
  7820. var trackListChanges = function trackListChanges() {
  7821. _this4.trigger(name + "trackchange");
  7822. };
  7823. var tracks = _this4[props.getterName]();
  7824. tracks.addEventListener('removetrack', trackListChanges);
  7825. tracks.addEventListener('addtrack', trackListChanges);
  7826. _this4.on('dispose', function () {
  7827. tracks.removeEventListener('removetrack', trackListChanges);
  7828. tracks.removeEventListener('addtrack', trackListChanges);
  7829. });
  7830. });
  7831. }
  7832. /**
  7833. * Emulate TextTracks using vtt.js if necessary
  7834. *
  7835. * @fires Tech#vttjsloaded
  7836. * @fires Tech#vttjserror
  7837. */
  7838. ;
  7839. _proto.addWebVttScript_ = function addWebVttScript_() {
  7840. var _this5 = this;
  7841. if (window__default['default'].WebVTT) {
  7842. return;
  7843. } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  7844. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  7845. // before inserting the WebVTT script
  7846. if (document__default['default'].body.contains(this.el())) {
  7847. // load via require if available and vtt.js script location was not passed in
  7848. // as an option. novtt builds will turn the above require call into an empty object
  7849. // which will cause this if check to always fail.
  7850. if (!this.options_['vtt.js'] && isPlain(vtt__default['default']) && Object.keys(vtt__default['default']).length > 0) {
  7851. this.trigger('vttjsloaded');
  7852. return;
  7853. } // load vtt.js via the script location option or the cdn of no location was
  7854. // passed in
  7855. var script = document__default['default'].createElement('script');
  7856. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  7857. script.onload = function () {
  7858. /**
  7859. * Fired when vtt.js is loaded.
  7860. *
  7861. * @event Tech#vttjsloaded
  7862. * @type {EventTarget~Event}
  7863. */
  7864. _this5.trigger('vttjsloaded');
  7865. };
  7866. script.onerror = function () {
  7867. /**
  7868. * Fired when vtt.js was not loaded due to an error
  7869. *
  7870. * @event Tech#vttjsloaded
  7871. * @type {EventTarget~Event}
  7872. */
  7873. _this5.trigger('vttjserror');
  7874. };
  7875. this.on('dispose', function () {
  7876. script.onload = null;
  7877. script.onerror = null;
  7878. }); // but have not loaded yet and we set it to true before the inject so that
  7879. // we don't overwrite the injected window.WebVTT if it loads right away
  7880. window__default['default'].WebVTT = true;
  7881. this.el().parentNode.appendChild(script);
  7882. } else {
  7883. this.ready(this.addWebVttScript_);
  7884. }
  7885. }
  7886. /**
  7887. * Emulate texttracks
  7888. *
  7889. */
  7890. ;
  7891. _proto.emulateTextTracks = function emulateTextTracks() {
  7892. var _this6 = this;
  7893. var tracks = this.textTracks();
  7894. var remoteTracks = this.remoteTextTracks();
  7895. var handleAddTrack = function handleAddTrack(e) {
  7896. return tracks.addTrack(e.track);
  7897. };
  7898. var handleRemoveTrack = function handleRemoveTrack(e) {
  7899. return tracks.removeTrack(e.track);
  7900. };
  7901. remoteTracks.on('addtrack', handleAddTrack);
  7902. remoteTracks.on('removetrack', handleRemoveTrack);
  7903. this.addWebVttScript_();
  7904. var updateDisplay = function updateDisplay() {
  7905. return _this6.trigger('texttrackchange');
  7906. };
  7907. var textTracksChanges = function textTracksChanges() {
  7908. updateDisplay();
  7909. for (var i = 0; i < tracks.length; i++) {
  7910. var track = tracks[i];
  7911. track.removeEventListener('cuechange', updateDisplay);
  7912. if (track.mode === 'showing') {
  7913. track.addEventListener('cuechange', updateDisplay);
  7914. }
  7915. }
  7916. };
  7917. textTracksChanges();
  7918. tracks.addEventListener('change', textTracksChanges);
  7919. tracks.addEventListener('addtrack', textTracksChanges);
  7920. tracks.addEventListener('removetrack', textTracksChanges);
  7921. this.on('dispose', function () {
  7922. remoteTracks.off('addtrack', handleAddTrack);
  7923. remoteTracks.off('removetrack', handleRemoveTrack);
  7924. tracks.removeEventListener('change', textTracksChanges);
  7925. tracks.removeEventListener('addtrack', textTracksChanges);
  7926. tracks.removeEventListener('removetrack', textTracksChanges);
  7927. for (var i = 0; i < tracks.length; i++) {
  7928. var track = tracks[i];
  7929. track.removeEventListener('cuechange', updateDisplay);
  7930. }
  7931. });
  7932. }
  7933. /**
  7934. * Create and returns a remote {@link TextTrack} object.
  7935. *
  7936. * @param {string} kind
  7937. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7938. *
  7939. * @param {string} [label]
  7940. * Label to identify the text track
  7941. *
  7942. * @param {string} [language]
  7943. * Two letter language abbreviation
  7944. *
  7945. * @return {TextTrack}
  7946. * The TextTrack that gets created.
  7947. */
  7948. ;
  7949. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  7950. if (!kind) {
  7951. throw new Error('TextTrack kind is required but was not provided');
  7952. }
  7953. return createTrackHelper(this, kind, label, language);
  7954. }
  7955. /**
  7956. * Create an emulated TextTrack for use by addRemoteTextTrack
  7957. *
  7958. * This is intended to be overridden by classes that inherit from
  7959. * Tech in order to create native or custom TextTracks.
  7960. *
  7961. * @param {Object} options
  7962. * The object should contain the options to initialize the TextTrack with.
  7963. *
  7964. * @param {string} [options.kind]
  7965. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  7966. *
  7967. * @param {string} [options.label].
  7968. * Label to identify the text track
  7969. *
  7970. * @param {string} [options.language]
  7971. * Two letter language abbreviation.
  7972. *
  7973. * @return {HTMLTrackElement}
  7974. * The track element that gets created.
  7975. */
  7976. ;
  7977. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  7978. var track = mergeOptions$3(options, {
  7979. tech: this
  7980. });
  7981. return new REMOTE.remoteTextEl.TrackClass(track);
  7982. }
  7983. /**
  7984. * Creates a remote text track object and returns an html track element.
  7985. *
  7986. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  7987. *
  7988. * @param {Object} options
  7989. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  7990. *
  7991. * @param {boolean} [manualCleanup=true]
  7992. * - When false: the TextTrack will be automatically removed from the video
  7993. * element whenever the source changes
  7994. * - When True: The TextTrack will have to be cleaned up manually
  7995. *
  7996. * @return {HTMLTrackElement}
  7997. * An Html Track Element.
  7998. *
  7999. * @deprecated The default functionality for this function will be equivalent
  8000. * to "manualCleanup=false" in the future. The manualCleanup parameter will
  8001. * also be removed.
  8002. */
  8003. ;
  8004. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  8005. var _this7 = this;
  8006. if (options === void 0) {
  8007. options = {};
  8008. }
  8009. var htmlTrackElement = this.createRemoteTextTrack(options);
  8010. if (manualCleanup !== true && manualCleanup !== false) {
  8011. // deprecation warning
  8012. log$1.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');
  8013. manualCleanup = true;
  8014. } // store HTMLTrackElement and TextTrack to remote list
  8015. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  8016. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  8017. if (manualCleanup !== true) {
  8018. // create the TextTrackList if it doesn't exist
  8019. this.ready(function () {
  8020. return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
  8021. });
  8022. }
  8023. return htmlTrackElement;
  8024. }
  8025. /**
  8026. * Remove a remote text track from the remote `TextTrackList`.
  8027. *
  8028. * @param {TextTrack} track
  8029. * `TextTrack` to remove from the `TextTrackList`
  8030. */
  8031. ;
  8032. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  8033. var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list
  8034. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  8035. this.remoteTextTracks().removeTrack(track);
  8036. this.autoRemoteTextTracks_.removeTrack(track);
  8037. }
  8038. /**
  8039. * Gets available media playback quality metrics as specified by the W3C's Media
  8040. * Playback Quality API.
  8041. *
  8042. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  8043. *
  8044. * @return {Object}
  8045. * An object with supported media playback quality metrics
  8046. *
  8047. * @abstract
  8048. */
  8049. ;
  8050. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  8051. return {};
  8052. }
  8053. /**
  8054. * Attempt to create a floating video window always on top of other windows
  8055. * so that users may continue consuming media while they interact with other
  8056. * content sites, or applications on their device.
  8057. *
  8058. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  8059. *
  8060. * @return {Promise|undefined}
  8061. * A promise with a Picture-in-Picture window if the browser supports
  8062. * Promises (or one was passed in as an option). It returns undefined
  8063. * otherwise.
  8064. *
  8065. * @abstract
  8066. */
  8067. ;
  8068. _proto.requestPictureInPicture = function requestPictureInPicture() {
  8069. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  8070. if (PromiseClass) {
  8071. return PromiseClass.reject();
  8072. }
  8073. }
  8074. /**
  8075. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  8076. * Defaults to true, as it should be considered disabled if the tech does not support pip
  8077. *
  8078. * @abstract
  8079. */
  8080. ;
  8081. _proto.disablePictureInPicture = function disablePictureInPicture() {
  8082. return true;
  8083. }
  8084. /**
  8085. * A method to set or unset the 'disablePictureInPicture' <video> property.
  8086. *
  8087. * @abstract
  8088. */
  8089. ;
  8090. _proto.setDisablePictureInPicture = function setDisablePictureInPicture() {}
  8091. /**
  8092. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  8093. *
  8094. * @param {function} cb
  8095. * @return {number} request id
  8096. */
  8097. ;
  8098. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  8099. var _this8 = this;
  8100. var id = newGUID();
  8101. if (!this.isReady_ || this.paused()) {
  8102. this.queuedHanders_.add(id);
  8103. this.one('playing', function () {
  8104. if (_this8.queuedHanders_.has(id)) {
  8105. _this8.queuedHanders_["delete"](id);
  8106. cb();
  8107. }
  8108. });
  8109. } else {
  8110. this.requestNamedAnimationFrame(id, cb);
  8111. }
  8112. return id;
  8113. }
  8114. /**
  8115. * A fallback implementation of cancelVideoFrameCallback
  8116. *
  8117. * @param {number} id id of callback to be cancelled
  8118. */
  8119. ;
  8120. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  8121. if (this.queuedHanders_.has(id)) {
  8122. this.queuedHanders_["delete"](id);
  8123. } else {
  8124. this.cancelNamedAnimationFrame(id);
  8125. }
  8126. }
  8127. /**
  8128. * A method to set a poster from a `Tech`.
  8129. *
  8130. * @abstract
  8131. */
  8132. ;
  8133. _proto.setPoster = function setPoster() {}
  8134. /**
  8135. * A method to check for the presence of the 'playsinline' <video> attribute.
  8136. *
  8137. * @abstract
  8138. */
  8139. ;
  8140. _proto.playsinline = function playsinline() {}
  8141. /**
  8142. * A method to set or unset the 'playsinline' <video> attribute.
  8143. *
  8144. * @abstract
  8145. */
  8146. ;
  8147. _proto.setPlaysinline = function setPlaysinline() {}
  8148. /**
  8149. * Attempt to force override of native audio tracks.
  8150. *
  8151. * @param {boolean} override - If set to true native audio will be overridden,
  8152. * otherwise native audio will potentially be used.
  8153. *
  8154. * @abstract
  8155. */
  8156. ;
  8157. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks() {}
  8158. /**
  8159. * Attempt to force override of native video tracks.
  8160. *
  8161. * @param {boolean} override - If set to true native video will be overridden,
  8162. * otherwise native video will potentially be used.
  8163. *
  8164. * @abstract
  8165. */
  8166. ;
  8167. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks() {}
  8168. /*
  8169. * Check if the tech can support the given mime-type.
  8170. *
  8171. * The base tech does not support any type, but source handlers might
  8172. * overwrite this.
  8173. *
  8174. * @param {string} type
  8175. * The mimetype to check for support
  8176. *
  8177. * @return {string}
  8178. * 'probably', 'maybe', or empty string
  8179. *
  8180. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8181. *
  8182. * @abstract
  8183. */
  8184. ;
  8185. _proto.canPlayType = function canPlayType() {
  8186. return '';
  8187. }
  8188. /**
  8189. * Check if the type is supported by this tech.
  8190. *
  8191. * The base tech does not support any type, but source handlers might
  8192. * overwrite this.
  8193. *
  8194. * @param {string} type
  8195. * The media type to check
  8196. * @return {string} Returns the native video element's response
  8197. */
  8198. ;
  8199. Tech.canPlayType = function canPlayType() {
  8200. return '';
  8201. }
  8202. /**
  8203. * Check if the tech can support the given source
  8204. *
  8205. * @param {Object} srcObj
  8206. * The source object
  8207. * @param {Object} options
  8208. * The options passed to the tech
  8209. * @return {string} 'probably', 'maybe', or '' (empty string)
  8210. */
  8211. ;
  8212. Tech.canPlaySource = function canPlaySource(srcObj, options) {
  8213. return Tech.canPlayType(srcObj.type);
  8214. }
  8215. /*
  8216. * Return whether the argument is a Tech or not.
  8217. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8218. *
  8219. * @param {Object} component
  8220. * The item to check
  8221. *
  8222. * @return {boolean}
  8223. * Whether it is a tech or not
  8224. * - True if it is a tech
  8225. * - False if it is not
  8226. */
  8227. ;
  8228. Tech.isTech = function isTech(component) {
  8229. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8230. }
  8231. /**
  8232. * Registers a `Tech` into a shared list for videojs.
  8233. *
  8234. * @param {string} name
  8235. * Name of the `Tech` to register.
  8236. *
  8237. * @param {Object} tech
  8238. * The `Tech` class to register.
  8239. */
  8240. ;
  8241. Tech.registerTech = function registerTech(name, tech) {
  8242. if (!Tech.techs_) {
  8243. Tech.techs_ = {};
  8244. }
  8245. if (!Tech.isTech(tech)) {
  8246. throw new Error("Tech " + name + " must be a Tech");
  8247. }
  8248. if (!Tech.canPlayType) {
  8249. throw new Error('Techs must have a static canPlayType method on them');
  8250. }
  8251. if (!Tech.canPlaySource) {
  8252. throw new Error('Techs must have a static canPlaySource method on them');
  8253. }
  8254. name = toTitleCase$1(name);
  8255. Tech.techs_[name] = tech;
  8256. Tech.techs_[toLowerCase(name)] = tech;
  8257. if (name !== 'Tech') {
  8258. // camel case the techName for use in techOrder
  8259. Tech.defaultTechOrder_.push(name);
  8260. }
  8261. return tech;
  8262. }
  8263. /**
  8264. * Get a `Tech` from the shared list by name.
  8265. *
  8266. * @param {string} name
  8267. * `camelCase` or `TitleCase` name of the Tech to get
  8268. *
  8269. * @return {Tech|undefined}
  8270. * The `Tech` or undefined if there was no tech with the name requested.
  8271. */
  8272. ;
  8273. Tech.getTech = function getTech(name) {
  8274. if (!name) {
  8275. return;
  8276. }
  8277. if (Tech.techs_ && Tech.techs_[name]) {
  8278. return Tech.techs_[name];
  8279. }
  8280. name = toTitleCase$1(name);
  8281. if (window__default['default'] && window__default['default'].videojs && window__default['default'].videojs[name]) {
  8282. log$1.warn("The " + name + " tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)");
  8283. return window__default['default'].videojs[name];
  8284. }
  8285. };
  8286. return Tech;
  8287. }(Component$1);
  8288. /**
  8289. * Get the {@link VideoTrackList}
  8290. *
  8291. * @returns {VideoTrackList}
  8292. * @method Tech.prototype.videoTracks
  8293. */
  8294. /**
  8295. * Get the {@link AudioTrackList}
  8296. *
  8297. * @returns {AudioTrackList}
  8298. * @method Tech.prototype.audioTracks
  8299. */
  8300. /**
  8301. * Get the {@link TextTrackList}
  8302. *
  8303. * @returns {TextTrackList}
  8304. * @method Tech.prototype.textTracks
  8305. */
  8306. /**
  8307. * Get the remote element {@link TextTrackList}
  8308. *
  8309. * @returns {TextTrackList}
  8310. * @method Tech.prototype.remoteTextTracks
  8311. */
  8312. /**
  8313. * Get the remote element {@link HtmlTrackElementList}
  8314. *
  8315. * @returns {HtmlTrackElementList}
  8316. * @method Tech.prototype.remoteTextTrackEls
  8317. */
  8318. ALL.names.forEach(function (name) {
  8319. var props = ALL[name];
  8320. Tech.prototype[props.getterName] = function () {
  8321. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8322. return this[props.privateName];
  8323. };
  8324. });
  8325. /**
  8326. * List of associated text tracks
  8327. *
  8328. * @type {TextTrackList}
  8329. * @private
  8330. * @property Tech#textTracks_
  8331. */
  8332. /**
  8333. * List of associated audio tracks.
  8334. *
  8335. * @type {AudioTrackList}
  8336. * @private
  8337. * @property Tech#audioTracks_
  8338. */
  8339. /**
  8340. * List of associated video tracks.
  8341. *
  8342. * @type {VideoTrackList}
  8343. * @private
  8344. * @property Tech#videoTracks_
  8345. */
  8346. /**
  8347. * Boolean indicating whether the `Tech` supports volume control.
  8348. *
  8349. * @type {boolean}
  8350. * @default
  8351. */
  8352. Tech.prototype.featuresVolumeControl = true;
  8353. /**
  8354. * Boolean indicating whether the `Tech` supports muting volume.
  8355. *
  8356. * @type {bolean}
  8357. * @default
  8358. */
  8359. Tech.prototype.featuresMuteControl = true;
  8360. /**
  8361. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8362. * Resizing plugins using request fullscreen reloads the plugin
  8363. *
  8364. * @type {boolean}
  8365. * @default
  8366. */
  8367. Tech.prototype.featuresFullscreenResize = false;
  8368. /**
  8369. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8370. * plays. Examples:
  8371. * - Set player to play 2x (twice) as fast
  8372. * - Set player to play 0.5x (half) as fast
  8373. *
  8374. * @type {boolean}
  8375. * @default
  8376. */
  8377. Tech.prototype.featuresPlaybackRate = false;
  8378. /**
  8379. * Boolean indicating whether the `Tech` supports the `progress` event. This is currently
  8380. * not triggered by video-js-swf. This will be used to determine if
  8381. * {@link Tech#manualProgressOn} should be called.
  8382. *
  8383. * @type {boolean}
  8384. * @default
  8385. */
  8386. Tech.prototype.featuresProgressEvents = false;
  8387. /**
  8388. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8389. *
  8390. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8391. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8392. * a new source.
  8393. *
  8394. * @type {boolean}
  8395. * @default
  8396. */
  8397. Tech.prototype.featuresSourceset = false;
  8398. /**
  8399. * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently
  8400. * not triggered by video-js-swf. This will be used to determine if
  8401. * {@link Tech#manualTimeUpdates} should be called.
  8402. *
  8403. * @type {boolean}
  8404. * @default
  8405. */
  8406. Tech.prototype.featuresTimeupdateEvents = false;
  8407. /**
  8408. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8409. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8410. *
  8411. * @type {boolean}
  8412. * @default
  8413. */
  8414. Tech.prototype.featuresNativeTextTracks = false;
  8415. /**
  8416. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8417. *
  8418. * @type {boolean}
  8419. * @default
  8420. */
  8421. Tech.prototype.featuresVideoFrameCallback = false;
  8422. /**
  8423. * A functional mixin for techs that want to use the Source Handler pattern.
  8424. * Source handlers are scripts for handling specific formats.
  8425. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8426. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8427. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8428. *
  8429. * @param {Tech} _Tech
  8430. * The tech to add source handler functions to.
  8431. *
  8432. * @mixes Tech~SourceHandlerAdditions
  8433. */
  8434. Tech.withSourceHandlers = function (_Tech) {
  8435. /**
  8436. * Register a source handler
  8437. *
  8438. * @param {Function} handler
  8439. * The source handler class
  8440. *
  8441. * @param {number} [index]
  8442. * Register it at the following index
  8443. */
  8444. _Tech.registerSourceHandler = function (handler, index) {
  8445. var handlers = _Tech.sourceHandlers;
  8446. if (!handlers) {
  8447. handlers = _Tech.sourceHandlers = [];
  8448. }
  8449. if (index === undefined) {
  8450. // add to the end of the list
  8451. index = handlers.length;
  8452. }
  8453. handlers.splice(index, 0, handler);
  8454. };
  8455. /**
  8456. * Check if the tech can support the given type. Also checks the
  8457. * Techs sourceHandlers.
  8458. *
  8459. * @param {string} type
  8460. * The mimetype to check.
  8461. *
  8462. * @return {string}
  8463. * 'probably', 'maybe', or '' (empty string)
  8464. */
  8465. _Tech.canPlayType = function (type) {
  8466. var handlers = _Tech.sourceHandlers || [];
  8467. var can;
  8468. for (var i = 0; i < handlers.length; i++) {
  8469. can = handlers[i].canPlayType(type);
  8470. if (can) {
  8471. return can;
  8472. }
  8473. }
  8474. return '';
  8475. };
  8476. /**
  8477. * Returns the first source handler that supports the source.
  8478. *
  8479. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8480. *
  8481. * @param {Tech~SourceObject} source
  8482. * The source object
  8483. *
  8484. * @param {Object} options
  8485. * The options passed to the tech
  8486. *
  8487. * @return {SourceHandler|null}
  8488. * The first source handler that supports the source or null if
  8489. * no SourceHandler supports the source
  8490. */
  8491. _Tech.selectSourceHandler = function (source, options) {
  8492. var handlers = _Tech.sourceHandlers || [];
  8493. var can;
  8494. for (var i = 0; i < handlers.length; i++) {
  8495. can = handlers[i].canHandleSource(source, options);
  8496. if (can) {
  8497. return handlers[i];
  8498. }
  8499. }
  8500. return null;
  8501. };
  8502. /**
  8503. * Check if the tech can support the given source.
  8504. *
  8505. * @param {Tech~SourceObject} srcObj
  8506. * The source object
  8507. *
  8508. * @param {Object} options
  8509. * The options passed to the tech
  8510. *
  8511. * @return {string}
  8512. * 'probably', 'maybe', or '' (empty string)
  8513. */
  8514. _Tech.canPlaySource = function (srcObj, options) {
  8515. var sh = _Tech.selectSourceHandler(srcObj, options);
  8516. if (sh) {
  8517. return sh.canHandleSource(srcObj, options);
  8518. }
  8519. return '';
  8520. };
  8521. /**
  8522. * When using a source handler, prefer its implementation of
  8523. * any function normally provided by the tech.
  8524. */
  8525. var deferrable = ['seekable', 'seeking', 'duration'];
  8526. /**
  8527. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  8528. * function if it exists, with a fallback to the Techs seekable function.
  8529. *
  8530. * @method _Tech.seekable
  8531. */
  8532. /**
  8533. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  8534. * function if it exists, otherwise it will fallback to the techs duration function.
  8535. *
  8536. * @method _Tech.duration
  8537. */
  8538. deferrable.forEach(function (fnName) {
  8539. var originalFn = this[fnName];
  8540. if (typeof originalFn !== 'function') {
  8541. return;
  8542. }
  8543. this[fnName] = function () {
  8544. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  8545. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  8546. }
  8547. return originalFn.apply(this, arguments);
  8548. };
  8549. }, _Tech.prototype);
  8550. /**
  8551. * Create a function for setting the source using a source object
  8552. * and source handlers.
  8553. * Should never be called unless a source handler was found.
  8554. *
  8555. * @param {Tech~SourceObject} source
  8556. * A source object with src and type keys
  8557. */
  8558. _Tech.prototype.setSource = function (source) {
  8559. var sh = _Tech.selectSourceHandler(source, this.options_);
  8560. if (!sh) {
  8561. // Fall back to a native source hander when unsupported sources are
  8562. // deliberately set
  8563. if (_Tech.nativeSourceHandler) {
  8564. sh = _Tech.nativeSourceHandler;
  8565. } else {
  8566. log$1.error('No source handler found for the current source.');
  8567. }
  8568. } // Dispose any existing source handler
  8569. this.disposeSourceHandler();
  8570. this.off('dispose', this.disposeSourceHandler_);
  8571. if (sh !== _Tech.nativeSourceHandler) {
  8572. this.currentSource_ = source;
  8573. }
  8574. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  8575. this.one('dispose', this.disposeSourceHandler_);
  8576. };
  8577. /**
  8578. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  8579. *
  8580. * @listens Tech#dispose
  8581. */
  8582. _Tech.prototype.disposeSourceHandler = function () {
  8583. // if we have a source and get another one
  8584. // then we are loading something new
  8585. // than clear all of our current tracks
  8586. if (this.currentSource_) {
  8587. this.clearTracks(['audio', 'video']);
  8588. this.currentSource_ = null;
  8589. } // always clean up auto-text tracks
  8590. this.cleanupAutoTextTracks();
  8591. if (this.sourceHandler_) {
  8592. if (this.sourceHandler_.dispose) {
  8593. this.sourceHandler_.dispose();
  8594. }
  8595. this.sourceHandler_ = null;
  8596. }
  8597. };
  8598. }; // The base Tech class needs to be registered as a Component. It is the only
  8599. // Tech that can be registered as a Component.
  8600. Component$1.registerComponent('Tech', Tech);
  8601. Tech.registerTech('Tech', Tech);
  8602. /**
  8603. * A list of techs that should be added to techOrder on Players
  8604. *
  8605. * @private
  8606. */
  8607. Tech.defaultTechOrder_ = [];
  8608. /**
  8609. * @file middleware.js
  8610. * @module middleware
  8611. */
  8612. var middlewares = {};
  8613. var middlewareInstances = {};
  8614. var TERMINATOR = {};
  8615. /**
  8616. * A middleware object is a plain JavaScript object that has methods that
  8617. * match the {@link Tech} methods found in the lists of allowed
  8618. * {@link module:middleware.allowedGetters|getters},
  8619. * {@link module:middleware.allowedSetters|setters}, and
  8620. * {@link module:middleware.allowedMediators|mediators}.
  8621. *
  8622. * @typedef {Object} MiddlewareObject
  8623. */
  8624. /**
  8625. * A middleware factory function that should return a
  8626. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  8627. *
  8628. * This factory will be called for each player when needed, with the player
  8629. * passed in as an argument.
  8630. *
  8631. * @callback MiddlewareFactory
  8632. * @param {Player} player
  8633. * A Video.js player.
  8634. */
  8635. /**
  8636. * Define a middleware that the player should use by way of a factory function
  8637. * that returns a middleware object.
  8638. *
  8639. * @param {string} type
  8640. * The MIME type to match or `"*"` for all MIME types.
  8641. *
  8642. * @param {MiddlewareFactory} middleware
  8643. * A middleware factory function that will be executed for
  8644. * matching types.
  8645. */
  8646. function use(type, middleware) {
  8647. middlewares[type] = middlewares[type] || [];
  8648. middlewares[type].push(middleware);
  8649. }
  8650. /**
  8651. * Asynchronously sets a source using middleware by recursing through any
  8652. * matching middlewares and calling `setSource` on each, passing along the
  8653. * previous returned value each time.
  8654. *
  8655. * @param {Player} player
  8656. * A {@link Player} instance.
  8657. *
  8658. * @param {Tech~SourceObject} src
  8659. * A source object.
  8660. *
  8661. * @param {Function}
  8662. * The next middleware to run.
  8663. */
  8664. function setSource(player, src, next) {
  8665. player.setTimeout(function () {
  8666. return setSourceHelper(src, middlewares[src.type], next, player);
  8667. }, 1);
  8668. }
  8669. /**
  8670. * When the tech is set, passes the tech to each middleware's `setTech` method.
  8671. *
  8672. * @param {Object[]} middleware
  8673. * An array of middleware instances.
  8674. *
  8675. * @param {Tech} tech
  8676. * A Video.js tech.
  8677. */
  8678. function setTech(middleware, tech) {
  8679. middleware.forEach(function (mw) {
  8680. return mw.setTech && mw.setTech(tech);
  8681. });
  8682. }
  8683. /**
  8684. * Calls a getter on the tech first, through each middleware
  8685. * from right to left to the player.
  8686. *
  8687. * @param {Object[]} middleware
  8688. * An array of middleware instances.
  8689. *
  8690. * @param {Tech} tech
  8691. * The current tech.
  8692. *
  8693. * @param {string} method
  8694. * A method name.
  8695. *
  8696. * @return {Mixed}
  8697. * The final value from the tech after middleware has intercepted it.
  8698. */
  8699. function get(middleware, tech, method) {
  8700. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  8701. }
  8702. /**
  8703. * Takes the argument given to the player and calls the setter method on each
  8704. * middleware from left to right to the tech.
  8705. *
  8706. * @param {Object[]} middleware
  8707. * An array of middleware instances.
  8708. *
  8709. * @param {Tech} tech
  8710. * The current tech.
  8711. *
  8712. * @param {string} method
  8713. * A method name.
  8714. *
  8715. * @param {Mixed} arg
  8716. * The value to set on the tech.
  8717. *
  8718. * @return {Mixed}
  8719. * The return value of the `method` of the `tech`.
  8720. */
  8721. function set(middleware, tech, method, arg) {
  8722. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  8723. }
  8724. /**
  8725. * Takes the argument given to the player and calls the `call` version of the
  8726. * method on each middleware from left to right.
  8727. *
  8728. * Then, call the passed in method on the tech and return the result unchanged
  8729. * back to the player, through middleware, this time from right to left.
  8730. *
  8731. * @param {Object[]} middleware
  8732. * An array of middleware instances.
  8733. *
  8734. * @param {Tech} tech
  8735. * The current tech.
  8736. *
  8737. * @param {string} method
  8738. * A method name.
  8739. *
  8740. * @param {Mixed} arg
  8741. * The value to set on the tech.
  8742. *
  8743. * @return {Mixed}
  8744. * The return value of the `method` of the `tech`, regardless of the
  8745. * return values of middlewares.
  8746. */
  8747. function mediate(middleware, tech, method, arg) {
  8748. if (arg === void 0) {
  8749. arg = null;
  8750. }
  8751. var callMethod = 'call' + toTitleCase$1(method);
  8752. var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  8753. var terminated = middlewareValue === TERMINATOR; // deprecated. The `null` return value should instead return TERMINATOR to
  8754. // prevent confusion if a techs method actually returns null.
  8755. var returnValue = terminated ? null : tech[method](middlewareValue);
  8756. executeRight(middleware, method, returnValue, terminated);
  8757. return returnValue;
  8758. }
  8759. /**
  8760. * Enumeration of allowed getters where the keys are method names.
  8761. *
  8762. * @type {Object}
  8763. */
  8764. var allowedGetters = {
  8765. buffered: 1,
  8766. currentTime: 1,
  8767. duration: 1,
  8768. muted: 1,
  8769. played: 1,
  8770. paused: 1,
  8771. seekable: 1,
  8772. volume: 1,
  8773. ended: 1
  8774. };
  8775. /**
  8776. * Enumeration of allowed setters where the keys are method names.
  8777. *
  8778. * @type {Object}
  8779. */
  8780. var allowedSetters = {
  8781. setCurrentTime: 1,
  8782. setMuted: 1,
  8783. setVolume: 1
  8784. };
  8785. /**
  8786. * Enumeration of allowed mediators where the keys are method names.
  8787. *
  8788. * @type {Object}
  8789. */
  8790. var allowedMediators = {
  8791. play: 1,
  8792. pause: 1
  8793. };
  8794. function middlewareIterator(method) {
  8795. return function (value, mw) {
  8796. // if the previous middleware terminated, pass along the termination
  8797. if (value === TERMINATOR) {
  8798. return TERMINATOR;
  8799. }
  8800. if (mw[method]) {
  8801. return mw[method](value);
  8802. }
  8803. return value;
  8804. };
  8805. }
  8806. function executeRight(mws, method, value, terminated) {
  8807. for (var i = mws.length - 1; i >= 0; i--) {
  8808. var mw = mws[i];
  8809. if (mw[method]) {
  8810. mw[method](terminated, value);
  8811. }
  8812. }
  8813. }
  8814. /**
  8815. * Clear the middleware cache for a player.
  8816. *
  8817. * @param {Player} player
  8818. * A {@link Player} instance.
  8819. */
  8820. function clearCacheForPlayer(player) {
  8821. middlewareInstances[player.id()] = null;
  8822. }
  8823. /**
  8824. * {
  8825. * [playerId]: [[mwFactory, mwInstance], ...]
  8826. * }
  8827. *
  8828. * @private
  8829. */
  8830. function getOrCreateFactory(player, mwFactory) {
  8831. var mws = middlewareInstances[player.id()];
  8832. var mw = null;
  8833. if (mws === undefined || mws === null) {
  8834. mw = mwFactory(player);
  8835. middlewareInstances[player.id()] = [[mwFactory, mw]];
  8836. return mw;
  8837. }
  8838. for (var i = 0; i < mws.length; i++) {
  8839. var _mws$i = mws[i],
  8840. mwf = _mws$i[0],
  8841. mwi = _mws$i[1];
  8842. if (mwf !== mwFactory) {
  8843. continue;
  8844. }
  8845. mw = mwi;
  8846. }
  8847. if (mw === null) {
  8848. mw = mwFactory(player);
  8849. mws.push([mwFactory, mw]);
  8850. }
  8851. return mw;
  8852. }
  8853. function setSourceHelper(src, middleware, next, player, acc, lastRun) {
  8854. if (src === void 0) {
  8855. src = {};
  8856. }
  8857. if (middleware === void 0) {
  8858. middleware = [];
  8859. }
  8860. if (acc === void 0) {
  8861. acc = [];
  8862. }
  8863. if (lastRun === void 0) {
  8864. lastRun = false;
  8865. }
  8866. var _middleware = middleware,
  8867. mwFactory = _middleware[0],
  8868. mwrest = _middleware.slice(1); // if mwFactory is a string, then we're at a fork in the road
  8869. if (typeof mwFactory === 'string') {
  8870. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun); // if we have an mwFactory, call it with the player to get the mw,
  8871. // then call the mw's setSource method
  8872. } else if (mwFactory) {
  8873. var mw = getOrCreateFactory(player, mwFactory); // if setSource isn't present, implicitly select this middleware
  8874. if (!mw.setSource) {
  8875. acc.push(mw);
  8876. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8877. }
  8878. mw.setSource(assign({}, src), function (err, _src) {
  8879. // something happened, try the next middleware on the current level
  8880. // make sure to use the old src
  8881. if (err) {
  8882. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8883. } // we've succeeded, now we need to go deeper
  8884. acc.push(mw); // if it's the same type, continue down the current chain
  8885. // otherwise, we want to go down the new chain
  8886. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  8887. });
  8888. } else if (mwrest.length) {
  8889. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  8890. } else if (lastRun) {
  8891. next(src, acc);
  8892. } else {
  8893. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  8894. }
  8895. }
  8896. /**
  8897. * Mimetypes
  8898. *
  8899. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  8900. * @typedef Mimetypes~Kind
  8901. * @enum
  8902. */
  8903. var MimetypesKind = {
  8904. opus: 'video/ogg',
  8905. ogv: 'video/ogg',
  8906. mp4: 'video/mp4',
  8907. mov: 'video/mp4',
  8908. m4v: 'video/mp4',
  8909. mkv: 'video/x-matroska',
  8910. m4a: 'audio/mp4',
  8911. mp3: 'audio/mpeg',
  8912. aac: 'audio/aac',
  8913. caf: 'audio/x-caf',
  8914. flac: 'audio/flac',
  8915. oga: 'audio/ogg',
  8916. wav: 'audio/wav',
  8917. m3u8: 'application/x-mpegURL',
  8918. mpd: 'application/dash+xml',
  8919. jpg: 'image/jpeg',
  8920. jpeg: 'image/jpeg',
  8921. gif: 'image/gif',
  8922. png: 'image/png',
  8923. svg: 'image/svg+xml',
  8924. webp: 'image/webp'
  8925. };
  8926. /**
  8927. * Get the mimetype of a given src url if possible
  8928. *
  8929. * @param {string} src
  8930. * The url to the src
  8931. *
  8932. * @return {string}
  8933. * return the mimetype if it was known or empty string otherwise
  8934. */
  8935. var getMimetype = function getMimetype(src) {
  8936. if (src === void 0) {
  8937. src = '';
  8938. }
  8939. var ext = getFileExtension(src);
  8940. var mimetype = MimetypesKind[ext.toLowerCase()];
  8941. return mimetype || '';
  8942. };
  8943. /**
  8944. * Find the mime type of a given source string if possible. Uses the player
  8945. * source cache.
  8946. *
  8947. * @param {Player} player
  8948. * The player object
  8949. *
  8950. * @param {string} src
  8951. * The source string
  8952. *
  8953. * @return {string}
  8954. * The type that was found
  8955. */
  8956. var findMimetype = function findMimetype(player, src) {
  8957. if (!src) {
  8958. return '';
  8959. } // 1. check for the type in the `source` cache
  8960. if (player.cache_.source.src === src && player.cache_.source.type) {
  8961. return player.cache_.source.type;
  8962. } // 2. see if we have this source in our `currentSources` cache
  8963. var matchingSources = player.cache_.sources.filter(function (s) {
  8964. return s.src === src;
  8965. });
  8966. if (matchingSources.length) {
  8967. return matchingSources[0].type;
  8968. } // 3. look for the src url in source elements and use the type there
  8969. var sources = player.$$('source');
  8970. for (var i = 0; i < sources.length; i++) {
  8971. var s = sources[i];
  8972. if (s.type && s.src && s.src === src) {
  8973. return s.type;
  8974. }
  8975. } // 4. finally fallback to our list of mime types based on src url extension
  8976. return getMimetype(src);
  8977. };
  8978. /**
  8979. * @module filter-source
  8980. */
  8981. /**
  8982. * Filter out single bad source objects or multiple source objects in an
  8983. * array. Also flattens nested source object arrays into a 1 dimensional
  8984. * array of source objects.
  8985. *
  8986. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  8987. * The src object to filter
  8988. *
  8989. * @return {Tech~SourceObject[]}
  8990. * An array of sourceobjects containing only valid sources
  8991. *
  8992. * @private
  8993. */
  8994. var filterSource = function filterSource(src) {
  8995. // traverse array
  8996. if (Array.isArray(src)) {
  8997. var newsrc = [];
  8998. src.forEach(function (srcobj) {
  8999. srcobj = filterSource(srcobj);
  9000. if (Array.isArray(srcobj)) {
  9001. newsrc = newsrc.concat(srcobj);
  9002. } else if (isObject(srcobj)) {
  9003. newsrc.push(srcobj);
  9004. }
  9005. });
  9006. src = newsrc;
  9007. } else if (typeof src === 'string' && src.trim()) {
  9008. // convert string into object
  9009. src = [fixSource({
  9010. src: src
  9011. })];
  9012. } else if (isObject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  9013. // src is already valid
  9014. src = [fixSource(src)];
  9015. } else {
  9016. // invalid source, turn it into an empty array
  9017. src = [];
  9018. }
  9019. return src;
  9020. };
  9021. /**
  9022. * Checks src mimetype, adding it when possible
  9023. *
  9024. * @param {Tech~SourceObject} src
  9025. * The src object to check
  9026. * @return {Tech~SourceObject}
  9027. * src Object with known type
  9028. */
  9029. function fixSource(src) {
  9030. if (!src.type) {
  9031. var mimetype = getMimetype(src.src);
  9032. if (mimetype) {
  9033. src.type = mimetype;
  9034. }
  9035. }
  9036. return src;
  9037. }
  9038. /**
  9039. * The `MediaLoader` is the `Component` that decides which playback technology to load
  9040. * when a player is initialized.
  9041. *
  9042. * @extends Component
  9043. */
  9044. var MediaLoader = /*#__PURE__*/function (_Component) {
  9045. _inheritsLoose__default['default'](MediaLoader, _Component);
  9046. /**
  9047. * Create an instance of this class.
  9048. *
  9049. * @param {Player} player
  9050. * The `Player` that this class should attach to.
  9051. *
  9052. * @param {Object} [options]
  9053. * The key/value store of player options.
  9054. *
  9055. * @param {Component~ReadyCallback} [ready]
  9056. * The function that is run when this component is ready.
  9057. */
  9058. function MediaLoader(player, options, ready) {
  9059. var _this;
  9060. // MediaLoader has no element
  9061. var options_ = mergeOptions$3({
  9062. createEl: false
  9063. }, options);
  9064. _this = _Component.call(this, player, options_, ready) || this; // If there are no sources when the player is initialized,
  9065. // load the first supported playback technology.
  9066. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  9067. for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  9068. var techName = toTitleCase$1(j[i]);
  9069. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  9070. // Remove once that deprecated behavior is removed.
  9071. if (!techName) {
  9072. tech = Component$1.getComponent(techName);
  9073. } // Check if the browser supports this technology
  9074. if (tech && tech.isSupported()) {
  9075. player.loadTech_(techName);
  9076. break;
  9077. }
  9078. }
  9079. } else {
  9080. // Loop through playback technologies (e.g. HTML5) and check for support.
  9081. // Then load the best source.
  9082. // A few assumptions here:
  9083. // All playback technologies respect preload false.
  9084. player.src(options.playerOptions.sources);
  9085. }
  9086. return _this;
  9087. }
  9088. return MediaLoader;
  9089. }(Component$1);
  9090. Component$1.registerComponent('MediaLoader', MediaLoader);
  9091. /**
  9092. * Component which is clickable or keyboard actionable, but is not a
  9093. * native HTML button.
  9094. *
  9095. * @extends Component
  9096. */
  9097. var ClickableComponent = /*#__PURE__*/function (_Component) {
  9098. _inheritsLoose__default['default'](ClickableComponent, _Component);
  9099. /**
  9100. * Creates an instance of this class.
  9101. *
  9102. * @param {Player} player
  9103. * The `Player` that this class should be attached to.
  9104. *
  9105. * @param {Object} [options]
  9106. * The key/value store of component options.
  9107. *
  9108. * @param {function} [options.clickHandler]
  9109. * The function to call when the button is clicked / activated
  9110. *
  9111. * @param {string} [options.controlText]
  9112. * The text to set on the button
  9113. *
  9114. * @param {string} [options.className]
  9115. * A class or space separated list of classes to add the component
  9116. *
  9117. */
  9118. function ClickableComponent(player, options) {
  9119. var _this;
  9120. _this = _Component.call(this, player, options) || this;
  9121. if (_this.options_.controlText) {
  9122. _this.controlText(_this.options_.controlText);
  9123. }
  9124. _this.handleMouseOver_ = function (e) {
  9125. return _this.handleMouseOver(e);
  9126. };
  9127. _this.handleMouseOut_ = function (e) {
  9128. return _this.handleMouseOut(e);
  9129. };
  9130. _this.handleClick_ = function (e) {
  9131. return _this.handleClick(e);
  9132. };
  9133. _this.handleKeyDown_ = function (e) {
  9134. return _this.handleKeyDown(e);
  9135. };
  9136. _this.emitTapEvents();
  9137. _this.enable();
  9138. return _this;
  9139. }
  9140. /**
  9141. * Create the `ClickableComponent`s DOM element.
  9142. *
  9143. * @param {string} [tag=div]
  9144. * The element's node type.
  9145. *
  9146. * @param {Object} [props={}]
  9147. * An object of properties that should be set on the element.
  9148. *
  9149. * @param {Object} [attributes={}]
  9150. * An object of attributes that should be set on the element.
  9151. *
  9152. * @return {Element}
  9153. * The element that gets created.
  9154. */
  9155. var _proto = ClickableComponent.prototype;
  9156. _proto.createEl = function createEl$1(tag, props, attributes) {
  9157. if (tag === void 0) {
  9158. tag = 'div';
  9159. }
  9160. if (props === void 0) {
  9161. props = {};
  9162. }
  9163. if (attributes === void 0) {
  9164. attributes = {};
  9165. }
  9166. props = assign({
  9167. className: this.buildCSSClass(),
  9168. tabIndex: 0
  9169. }, props);
  9170. if (tag === 'button') {
  9171. log$1.error("Creating a ClickableComponent with an HTML element of " + tag + " is not supported; use a Button instead.");
  9172. } // Add ARIA attributes for clickable element which is not a native HTML button
  9173. attributes = assign({
  9174. role: 'button'
  9175. }, attributes);
  9176. this.tabIndex_ = props.tabIndex;
  9177. var el = createEl(tag, props, attributes);
  9178. el.appendChild(createEl('span', {
  9179. className: 'vjs-icon-placeholder'
  9180. }, {
  9181. 'aria-hidden': true
  9182. }));
  9183. this.createControlTextEl(el);
  9184. return el;
  9185. };
  9186. _proto.dispose = function dispose() {
  9187. // remove controlTextEl_ on dispose
  9188. this.controlTextEl_ = null;
  9189. _Component.prototype.dispose.call(this);
  9190. }
  9191. /**
  9192. * Create a control text element on this `ClickableComponent`
  9193. *
  9194. * @param {Element} [el]
  9195. * Parent element for the control text.
  9196. *
  9197. * @return {Element}
  9198. * The control text element that gets created.
  9199. */
  9200. ;
  9201. _proto.createControlTextEl = function createControlTextEl(el) {
  9202. this.controlTextEl_ = createEl('span', {
  9203. className: 'vjs-control-text'
  9204. }, {
  9205. // let the screen reader user know that the text of the element may change
  9206. 'aria-live': 'polite'
  9207. });
  9208. if (el) {
  9209. el.appendChild(this.controlTextEl_);
  9210. }
  9211. this.controlText(this.controlText_, el);
  9212. return this.controlTextEl_;
  9213. }
  9214. /**
  9215. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9216. *
  9217. * @param {string} [text]
  9218. * Control text for element.
  9219. *
  9220. * @param {Element} [el=this.el()]
  9221. * Element to set the title on.
  9222. *
  9223. * @return {string}
  9224. * - The control text when getting
  9225. */
  9226. ;
  9227. _proto.controlText = function controlText(text, el) {
  9228. if (el === void 0) {
  9229. el = this.el();
  9230. }
  9231. if (text === undefined) {
  9232. return this.controlText_ || 'Need Text';
  9233. }
  9234. var localizedText = this.localize(text);
  9235. this.controlText_ = text;
  9236. textContent(this.controlTextEl_, localizedText);
  9237. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9238. // Set title attribute if only an icon is shown
  9239. el.setAttribute('title', localizedText);
  9240. }
  9241. }
  9242. /**
  9243. * Builds the default DOM `className`.
  9244. *
  9245. * @return {string}
  9246. * The DOM `className` for this object.
  9247. */
  9248. ;
  9249. _proto.buildCSSClass = function buildCSSClass() {
  9250. return "vjs-control vjs-button " + _Component.prototype.buildCSSClass.call(this);
  9251. }
  9252. /**
  9253. * Enable this `ClickableComponent`
  9254. */
  9255. ;
  9256. _proto.enable = function enable() {
  9257. if (!this.enabled_) {
  9258. this.enabled_ = true;
  9259. this.removeClass('vjs-disabled');
  9260. this.el_.setAttribute('aria-disabled', 'false');
  9261. if (typeof this.tabIndex_ !== 'undefined') {
  9262. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9263. }
  9264. this.on(['tap', 'click'], this.handleClick_);
  9265. this.on('keydown', this.handleKeyDown_);
  9266. }
  9267. }
  9268. /**
  9269. * Disable this `ClickableComponent`
  9270. */
  9271. ;
  9272. _proto.disable = function disable() {
  9273. this.enabled_ = false;
  9274. this.addClass('vjs-disabled');
  9275. this.el_.setAttribute('aria-disabled', 'true');
  9276. if (typeof this.tabIndex_ !== 'undefined') {
  9277. this.el_.removeAttribute('tabIndex');
  9278. }
  9279. this.off('mouseover', this.handleMouseOver_);
  9280. this.off('mouseout', this.handleMouseOut_);
  9281. this.off(['tap', 'click'], this.handleClick_);
  9282. this.off('keydown', this.handleKeyDown_);
  9283. }
  9284. /**
  9285. * Handles language change in ClickableComponent for the player in components
  9286. *
  9287. *
  9288. */
  9289. ;
  9290. _proto.handleLanguagechange = function handleLanguagechange() {
  9291. this.controlText(this.controlText_);
  9292. }
  9293. /**
  9294. * Event handler that is called when a `ClickableComponent` receives a
  9295. * `click` or `tap` event.
  9296. *
  9297. * @param {EventTarget~Event} event
  9298. * The `tap` or `click` event that caused this function to be called.
  9299. *
  9300. * @listens tap
  9301. * @listens click
  9302. * @abstract
  9303. */
  9304. ;
  9305. _proto.handleClick = function handleClick(event) {
  9306. if (this.options_.clickHandler) {
  9307. this.options_.clickHandler.call(this, arguments);
  9308. }
  9309. }
  9310. /**
  9311. * Event handler that is called when a `ClickableComponent` receives a
  9312. * `keydown` event.
  9313. *
  9314. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9315. *
  9316. * @param {EventTarget~Event} event
  9317. * The `keydown` event that caused this function to be called.
  9318. *
  9319. * @listens keydown
  9320. */
  9321. ;
  9322. _proto.handleKeyDown = function handleKeyDown(event) {
  9323. // Support Space or Enter key operation to fire a click event. Also,
  9324. // prevent the event from propagating through the DOM and triggering
  9325. // Player hotkeys.
  9326. if (keycode__default['default'].isEventKey(event, 'Space') || keycode__default['default'].isEventKey(event, 'Enter')) {
  9327. event.preventDefault();
  9328. event.stopPropagation();
  9329. this.trigger('click');
  9330. } else {
  9331. // Pass keypress handling up for unsupported keys
  9332. _Component.prototype.handleKeyDown.call(this, event);
  9333. }
  9334. };
  9335. return ClickableComponent;
  9336. }(Component$1);
  9337. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  9338. /**
  9339. * A `ClickableComponent` that handles showing the poster image for the player.
  9340. *
  9341. * @extends ClickableComponent
  9342. */
  9343. var PosterImage = /*#__PURE__*/function (_ClickableComponent) {
  9344. _inheritsLoose__default['default'](PosterImage, _ClickableComponent);
  9345. /**
  9346. * Create an instance of this class.
  9347. *
  9348. * @param {Player} player
  9349. * The `Player` that this class should attach to.
  9350. *
  9351. * @param {Object} [options]
  9352. * The key/value store of player options.
  9353. */
  9354. function PosterImage(player, options) {
  9355. var _this;
  9356. _this = _ClickableComponent.call(this, player, options) || this;
  9357. _this.update();
  9358. _this.update_ = function (e) {
  9359. return _this.update(e);
  9360. };
  9361. player.on('posterchange', _this.update_);
  9362. return _this;
  9363. }
  9364. /**
  9365. * Clean up and dispose of the `PosterImage`.
  9366. */
  9367. var _proto = PosterImage.prototype;
  9368. _proto.dispose = function dispose() {
  9369. this.player().off('posterchange', this.update_);
  9370. _ClickableComponent.prototype.dispose.call(this);
  9371. }
  9372. /**
  9373. * Create the `PosterImage`s DOM element.
  9374. *
  9375. * @return {Element}
  9376. * The element that gets created.
  9377. */
  9378. ;
  9379. _proto.createEl = function createEl$1() {
  9380. var el = createEl('div', {
  9381. className: 'vjs-poster',
  9382. // Don't want poster to be tabbable.
  9383. tabIndex: -1
  9384. });
  9385. return el;
  9386. }
  9387. /**
  9388. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9389. *
  9390. * @listens Player#posterchange
  9391. *
  9392. * @param {EventTarget~Event} [event]
  9393. * The `Player#posterchange` event that triggered this function.
  9394. */
  9395. ;
  9396. _proto.update = function update(event) {
  9397. var url = this.player().poster();
  9398. this.setSrc(url); // If there's no poster source we should display:none on this component
  9399. // so it's not still clickable or right-clickable
  9400. if (url) {
  9401. this.show();
  9402. } else {
  9403. this.hide();
  9404. }
  9405. }
  9406. /**
  9407. * Set the source of the `PosterImage` depending on the display method.
  9408. *
  9409. * @param {string} url
  9410. * The URL to the source for the `PosterImage`.
  9411. */
  9412. ;
  9413. _proto.setSrc = function setSrc(url) {
  9414. var backgroundImage = ''; // Any falsy value should stay as an empty string, otherwise
  9415. // this will throw an extra error
  9416. if (url) {
  9417. backgroundImage = "url(\"" + url + "\")";
  9418. }
  9419. this.el_.style.backgroundImage = backgroundImage;
  9420. }
  9421. /**
  9422. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9423. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9424. *
  9425. * @listens tap
  9426. * @listens click
  9427. * @listens keydown
  9428. *
  9429. * @param {EventTarget~Event} event
  9430. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9431. */
  9432. ;
  9433. _proto.handleClick = function handleClick(event) {
  9434. // We don't want a click to trigger playback when controls are disabled
  9435. if (!this.player_.controls()) {
  9436. return;
  9437. }
  9438. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  9439. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  9440. // calling .focus() on the video element causes the video to go black,
  9441. // so we avoid it in that specific case
  9442. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  9443. this.player_.tech(true).focus();
  9444. }
  9445. if (this.player_.paused()) {
  9446. silencePromise(this.player_.play());
  9447. } else {
  9448. this.player_.pause();
  9449. }
  9450. };
  9451. return PosterImage;
  9452. }(ClickableComponent);
  9453. Component$1.registerComponent('PosterImage', PosterImage);
  9454. var darkGray = '#222';
  9455. var lightGray = '#ccc';
  9456. var fontMap = {
  9457. monospace: 'monospace',
  9458. sansSerif: 'sans-serif',
  9459. serif: 'serif',
  9460. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9461. monospaceSerif: '"Courier New", monospace',
  9462. proportionalSansSerif: 'sans-serif',
  9463. proportionalSerif: 'serif',
  9464. casual: '"Comic Sans MS", Impact, fantasy',
  9465. script: '"Monotype Corsiva", cursive',
  9466. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9467. };
  9468. /**
  9469. * Construct an rgba color from a given hex color code.
  9470. *
  9471. * @param {number} color
  9472. * Hex number for color, like #f0e or #f604e2.
  9473. *
  9474. * @param {number} opacity
  9475. * Value for opacity, 0.0 - 1.0.
  9476. *
  9477. * @return {string}
  9478. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9479. */
  9480. function constructColor(color, opacity) {
  9481. var hex;
  9482. if (color.length === 4) {
  9483. // color looks like "#f0e"
  9484. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9485. } else if (color.length === 7) {
  9486. // color looks like "#f604e2"
  9487. hex = color.slice(1);
  9488. } else {
  9489. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9490. }
  9491. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9492. }
  9493. /**
  9494. * Try to update the style of a DOM element. Some style changes will throw an error,
  9495. * particularly in IE8. Those should be noops.
  9496. *
  9497. * @param {Element} el
  9498. * The DOM element to be styled.
  9499. *
  9500. * @param {string} style
  9501. * The CSS property on the element that should be styled.
  9502. *
  9503. * @param {string} rule
  9504. * The style rule that should be applied to the property.
  9505. *
  9506. * @private
  9507. */
  9508. function tryUpdateStyle(el, style, rule) {
  9509. try {
  9510. el.style[style] = rule;
  9511. } catch (e) {
  9512. // Satisfies linter.
  9513. return;
  9514. }
  9515. }
  9516. /**
  9517. * The component for displaying text track cues.
  9518. *
  9519. * @extends Component
  9520. */
  9521. var TextTrackDisplay = /*#__PURE__*/function (_Component) {
  9522. _inheritsLoose__default['default'](TextTrackDisplay, _Component);
  9523. /**
  9524. * Creates an instance of this class.
  9525. *
  9526. * @param {Player} player
  9527. * The `Player` that this class should be attached to.
  9528. *
  9529. * @param {Object} [options]
  9530. * The key/value store of player options.
  9531. *
  9532. * @param {Component~ReadyCallback} [ready]
  9533. * The function to call when `TextTrackDisplay` is ready.
  9534. */
  9535. function TextTrackDisplay(player, options, ready) {
  9536. var _this;
  9537. _this = _Component.call(this, player, options, ready) || this;
  9538. var updateDisplayHandler = function updateDisplayHandler(e) {
  9539. return _this.updateDisplay(e);
  9540. };
  9541. player.on('loadstart', function (e) {
  9542. return _this.toggleDisplay(e);
  9543. });
  9544. player.on('texttrackchange', updateDisplayHandler);
  9545. player.on('loadedmetadata', function (e) {
  9546. return _this.preselectTrack(e);
  9547. }); // This used to be called during player init, but was causing an error
  9548. // if a track should show by default and the display hadn't loaded yet.
  9549. // Should probably be moved to an external track loader when we support
  9550. // tracks that don't need a display.
  9551. player.ready(bind(_assertThisInitialized__default['default'](_this), function () {
  9552. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  9553. this.hide();
  9554. return;
  9555. }
  9556. player.on('fullscreenchange', updateDisplayHandler);
  9557. player.on('playerresize', updateDisplayHandler);
  9558. window__default['default'].addEventListener('orientationchange', updateDisplayHandler);
  9559. player.on('dispose', function () {
  9560. return window__default['default'].removeEventListener('orientationchange', updateDisplayHandler);
  9561. });
  9562. var tracks = this.options_.playerOptions.tracks || [];
  9563. for (var i = 0; i < tracks.length; i++) {
  9564. this.player_.addRemoteTextTrack(tracks[i], true);
  9565. }
  9566. this.preselectTrack();
  9567. }));
  9568. return _this;
  9569. }
  9570. /**
  9571. * Preselect a track following this precedence:
  9572. * - matches the previously selected {@link TextTrack}'s language and kind
  9573. * - matches the previously selected {@link TextTrack}'s language only
  9574. * - is the first default captions track
  9575. * - is the first default descriptions track
  9576. *
  9577. * @listens Player#loadstart
  9578. */
  9579. var _proto = TextTrackDisplay.prototype;
  9580. _proto.preselectTrack = function preselectTrack() {
  9581. var modes = {
  9582. captions: 1,
  9583. subtitles: 1
  9584. };
  9585. var trackList = this.player_.textTracks();
  9586. var userPref = this.player_.cache_.selectedLanguage;
  9587. var firstDesc;
  9588. var firstCaptions;
  9589. var preferredTrack;
  9590. for (var i = 0; i < trackList.length; i++) {
  9591. var track = trackList[i];
  9592. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  9593. // Always choose the track that matches both language and kind
  9594. if (track.kind === userPref.kind) {
  9595. preferredTrack = track; // or choose the first track that matches language
  9596. } else if (!preferredTrack) {
  9597. preferredTrack = track;
  9598. } // clear everything if offTextTrackMenuItem was clicked
  9599. } else if (userPref && !userPref.enabled) {
  9600. preferredTrack = null;
  9601. firstDesc = null;
  9602. firstCaptions = null;
  9603. } else if (track["default"]) {
  9604. if (track.kind === 'descriptions' && !firstDesc) {
  9605. firstDesc = track;
  9606. } else if (track.kind in modes && !firstCaptions) {
  9607. firstCaptions = track;
  9608. }
  9609. }
  9610. } // The preferredTrack matches the user preference and takes
  9611. // precedence over all the other tracks.
  9612. // So, display the preferredTrack before the first default track
  9613. // and the subtitles/captions track before the descriptions track
  9614. if (preferredTrack) {
  9615. preferredTrack.mode = 'showing';
  9616. } else if (firstCaptions) {
  9617. firstCaptions.mode = 'showing';
  9618. } else if (firstDesc) {
  9619. firstDesc.mode = 'showing';
  9620. }
  9621. }
  9622. /**
  9623. * Turn display of {@link TextTrack}'s from the current state into the other state.
  9624. * There are only two states:
  9625. * - 'shown'
  9626. * - 'hidden'
  9627. *
  9628. * @listens Player#loadstart
  9629. */
  9630. ;
  9631. _proto.toggleDisplay = function toggleDisplay() {
  9632. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  9633. this.hide();
  9634. } else {
  9635. this.show();
  9636. }
  9637. }
  9638. /**
  9639. * Create the {@link Component}'s DOM element.
  9640. *
  9641. * @return {Element}
  9642. * The element that was created.
  9643. */
  9644. ;
  9645. _proto.createEl = function createEl() {
  9646. return _Component.prototype.createEl.call(this, 'div', {
  9647. className: 'vjs-text-track-display'
  9648. }, {
  9649. 'translate': 'yes',
  9650. 'aria-live': 'off',
  9651. 'aria-atomic': 'true'
  9652. });
  9653. }
  9654. /**
  9655. * Clear all displayed {@link TextTrack}s.
  9656. */
  9657. ;
  9658. _proto.clearDisplay = function clearDisplay() {
  9659. if (typeof window__default['default'].WebVTT === 'function') {
  9660. window__default['default'].WebVTT.processCues(window__default['default'], [], this.el_);
  9661. }
  9662. }
  9663. /**
  9664. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  9665. * a {@link Player#fullscreenchange} is fired.
  9666. *
  9667. * @listens Player#texttrackchange
  9668. * @listens Player#fullscreenchange
  9669. */
  9670. ;
  9671. _proto.updateDisplay = function updateDisplay() {
  9672. var tracks = this.player_.textTracks();
  9673. var allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  9674. this.clearDisplay();
  9675. if (allowMultipleShowingTracks) {
  9676. var showingTracks = [];
  9677. for (var _i = 0; _i < tracks.length; ++_i) {
  9678. var track = tracks[_i];
  9679. if (track.mode !== 'showing') {
  9680. continue;
  9681. }
  9682. showingTracks.push(track);
  9683. }
  9684. this.updateForTrack(showingTracks);
  9685. return;
  9686. } // Track display prioritization model: if multiple tracks are 'showing',
  9687. // display the first 'subtitles' or 'captions' track which is 'showing',
  9688. // otherwise display the first 'descriptions' track which is 'showing'
  9689. var descriptionsTrack = null;
  9690. var captionsSubtitlesTrack = null;
  9691. var i = tracks.length;
  9692. while (i--) {
  9693. var _track = tracks[i];
  9694. if (_track.mode === 'showing') {
  9695. if (_track.kind === 'descriptions') {
  9696. descriptionsTrack = _track;
  9697. } else {
  9698. captionsSubtitlesTrack = _track;
  9699. }
  9700. }
  9701. }
  9702. if (captionsSubtitlesTrack) {
  9703. if (this.getAttribute('aria-live') !== 'off') {
  9704. this.setAttribute('aria-live', 'off');
  9705. }
  9706. this.updateForTrack(captionsSubtitlesTrack);
  9707. } else if (descriptionsTrack) {
  9708. if (this.getAttribute('aria-live') !== 'assertive') {
  9709. this.setAttribute('aria-live', 'assertive');
  9710. }
  9711. this.updateForTrack(descriptionsTrack);
  9712. }
  9713. }
  9714. /**
  9715. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  9716. *
  9717. * @param {TextTrack} track
  9718. * Text track object containing active cues to style.
  9719. */
  9720. ;
  9721. _proto.updateDisplayState = function updateDisplayState(track) {
  9722. var overrides = this.player_.textTrackSettings.getValues();
  9723. var cues = track.activeCues;
  9724. var i = cues.length;
  9725. while (i--) {
  9726. var cue = cues[i];
  9727. if (!cue) {
  9728. continue;
  9729. }
  9730. var cueDiv = cue.displayState;
  9731. if (overrides.color) {
  9732. cueDiv.firstChild.style.color = overrides.color;
  9733. }
  9734. if (overrides.textOpacity) {
  9735. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  9736. }
  9737. if (overrides.backgroundColor) {
  9738. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  9739. }
  9740. if (overrides.backgroundOpacity) {
  9741. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  9742. }
  9743. if (overrides.windowColor) {
  9744. if (overrides.windowOpacity) {
  9745. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  9746. } else {
  9747. cueDiv.style.backgroundColor = overrides.windowColor;
  9748. }
  9749. }
  9750. if (overrides.edgeStyle) {
  9751. if (overrides.edgeStyle === 'dropshadow') {
  9752. cueDiv.firstChild.style.textShadow = "2px 2px 3px " + darkGray + ", 2px 2px 4px " + darkGray + ", 2px 2px 5px " + darkGray;
  9753. } else if (overrides.edgeStyle === 'raised') {
  9754. cueDiv.firstChild.style.textShadow = "1px 1px " + darkGray + ", 2px 2px " + darkGray + ", 3px 3px " + darkGray;
  9755. } else if (overrides.edgeStyle === 'depressed') {
  9756. cueDiv.firstChild.style.textShadow = "1px 1px " + lightGray + ", 0 1px " + lightGray + ", -1px -1px " + darkGray + ", 0 -1px " + darkGray;
  9757. } else if (overrides.edgeStyle === 'uniform') {
  9758. cueDiv.firstChild.style.textShadow = "0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray;
  9759. }
  9760. }
  9761. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  9762. var fontSize = window__default['default'].parseFloat(cueDiv.style.fontSize);
  9763. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  9764. cueDiv.style.height = 'auto';
  9765. cueDiv.style.top = 'auto';
  9766. }
  9767. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  9768. if (overrides.fontFamily === 'small-caps') {
  9769. cueDiv.firstChild.style.fontVariant = 'small-caps';
  9770. } else {
  9771. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  9772. }
  9773. }
  9774. }
  9775. }
  9776. /**
  9777. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  9778. *
  9779. * @param {TextTrack|TextTrack[]} tracks
  9780. * Text track object or text track array to be added to the list.
  9781. */
  9782. ;
  9783. _proto.updateForTrack = function updateForTrack(tracks) {
  9784. if (!Array.isArray(tracks)) {
  9785. tracks = [tracks];
  9786. }
  9787. if (typeof window__default['default'].WebVTT !== 'function' || tracks.every(function (track) {
  9788. return !track.activeCues;
  9789. })) {
  9790. return;
  9791. }
  9792. var cues = []; // push all active track cues
  9793. for (var i = 0; i < tracks.length; ++i) {
  9794. var track = tracks[i];
  9795. for (var j = 0; j < track.activeCues.length; ++j) {
  9796. cues.push(track.activeCues[j]);
  9797. }
  9798. } // removes all cues before it processes new ones
  9799. window__default['default'].WebVTT.processCues(window__default['default'], cues, this.el_); // add unique class to each language text track & add settings styling if necessary
  9800. for (var _i2 = 0; _i2 < tracks.length; ++_i2) {
  9801. var _track2 = tracks[_i2];
  9802. for (var _j = 0; _j < _track2.activeCues.length; ++_j) {
  9803. var cueEl = _track2.activeCues[_j].displayState;
  9804. addClass(cueEl, 'vjs-text-track-cue');
  9805. addClass(cueEl, 'vjs-text-track-cue-' + (_track2.language ? _track2.language : _i2));
  9806. if (_track2.language) {
  9807. setAttribute(cueEl, 'lang', _track2.language);
  9808. }
  9809. }
  9810. if (this.player_.textTrackSettings) {
  9811. this.updateDisplayState(_track2);
  9812. }
  9813. }
  9814. };
  9815. return TextTrackDisplay;
  9816. }(Component$1);
  9817. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  9818. /**
  9819. * A loading spinner for use during waiting/loading events.
  9820. *
  9821. * @extends Component
  9822. */
  9823. var LoadingSpinner = /*#__PURE__*/function (_Component) {
  9824. _inheritsLoose__default['default'](LoadingSpinner, _Component);
  9825. function LoadingSpinner() {
  9826. return _Component.apply(this, arguments) || this;
  9827. }
  9828. var _proto = LoadingSpinner.prototype;
  9829. /**
  9830. * Create the `LoadingSpinner`s DOM element.
  9831. *
  9832. * @return {Element}
  9833. * The dom element that gets created.
  9834. */
  9835. _proto.createEl = function createEl$1() {
  9836. var isAudio = this.player_.isAudio();
  9837. var playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  9838. var controlText = createEl('span', {
  9839. className: 'vjs-control-text',
  9840. textContent: this.localize('{1} is loading.', [playerType])
  9841. });
  9842. var el = _Component.prototype.createEl.call(this, 'div', {
  9843. className: 'vjs-loading-spinner',
  9844. dir: 'ltr'
  9845. });
  9846. el.appendChild(controlText);
  9847. return el;
  9848. };
  9849. return LoadingSpinner;
  9850. }(Component$1);
  9851. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  9852. /**
  9853. * Base class for all buttons.
  9854. *
  9855. * @extends ClickableComponent
  9856. */
  9857. var Button = /*#__PURE__*/function (_ClickableComponent) {
  9858. _inheritsLoose__default['default'](Button, _ClickableComponent);
  9859. function Button() {
  9860. return _ClickableComponent.apply(this, arguments) || this;
  9861. }
  9862. var _proto = Button.prototype;
  9863. /**
  9864. * Create the `Button`s DOM element.
  9865. *
  9866. * @param {string} [tag="button"]
  9867. * The element's node type. This argument is IGNORED: no matter what
  9868. * is passed, it will always create a `button` element.
  9869. *
  9870. * @param {Object} [props={}]
  9871. * An object of properties that should be set on the element.
  9872. *
  9873. * @param {Object} [attributes={}]
  9874. * An object of attributes that should be set on the element.
  9875. *
  9876. * @return {Element}
  9877. * The element that gets created.
  9878. */
  9879. _proto.createEl = function createEl$1(tag, props, attributes) {
  9880. if (props === void 0) {
  9881. props = {};
  9882. }
  9883. if (attributes === void 0) {
  9884. attributes = {};
  9885. }
  9886. tag = 'button';
  9887. props = assign({
  9888. className: this.buildCSSClass()
  9889. }, props); // Add attributes for button element
  9890. attributes = assign({
  9891. // Necessary since the default button type is "submit"
  9892. type: 'button'
  9893. }, attributes);
  9894. var el = createEl(tag, props, attributes);
  9895. el.appendChild(createEl('span', {
  9896. className: 'vjs-icon-placeholder'
  9897. }, {
  9898. 'aria-hidden': true
  9899. }));
  9900. this.createControlTextEl(el);
  9901. return el;
  9902. }
  9903. /**
  9904. * Add a child `Component` inside of this `Button`.
  9905. *
  9906. * @param {string|Component} child
  9907. * The name or instance of a child to add.
  9908. *
  9909. * @param {Object} [options={}]
  9910. * The key/value store of options that will get passed to children of
  9911. * the child.
  9912. *
  9913. * @return {Component}
  9914. * The `Component` that gets added as a child. When using a string the
  9915. * `Component` will get created by this process.
  9916. *
  9917. * @deprecated since version 5
  9918. */
  9919. ;
  9920. _proto.addChild = function addChild(child, options) {
  9921. if (options === void 0) {
  9922. options = {};
  9923. }
  9924. var className = this.constructor.name;
  9925. log$1.warn("Adding an actionable (user controllable) child to a Button (" + className + ") is not supported; use a ClickableComponent instead."); // Avoid the error message generated by ClickableComponent's addChild method
  9926. return Component$1.prototype.addChild.call(this, child, options);
  9927. }
  9928. /**
  9929. * Enable the `Button` element so that it can be activated or clicked. Use this with
  9930. * {@link Button#disable}.
  9931. */
  9932. ;
  9933. _proto.enable = function enable() {
  9934. _ClickableComponent.prototype.enable.call(this);
  9935. this.el_.removeAttribute('disabled');
  9936. }
  9937. /**
  9938. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  9939. * {@link Button#enable}.
  9940. */
  9941. ;
  9942. _proto.disable = function disable() {
  9943. _ClickableComponent.prototype.disable.call(this);
  9944. this.el_.setAttribute('disabled', 'disabled');
  9945. }
  9946. /**
  9947. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  9948. * press.
  9949. *
  9950. * @param {EventTarget~Event} event
  9951. * The event that caused this function to get called.
  9952. *
  9953. * @listens keydown
  9954. */
  9955. ;
  9956. _proto.handleKeyDown = function handleKeyDown(event) {
  9957. // Ignore Space or Enter key operation, which is handled by the browser for
  9958. // a button - though not for its super class, ClickableComponent. Also,
  9959. // prevent the event from propagating through the DOM and triggering Player
  9960. // hotkeys. We do not preventDefault here because we _want_ the browser to
  9961. // handle it.
  9962. if (keycode__default['default'].isEventKey(event, 'Space') || keycode__default['default'].isEventKey(event, 'Enter')) {
  9963. event.stopPropagation();
  9964. return;
  9965. } // Pass keypress handling up for unsupported keys
  9966. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  9967. };
  9968. return Button;
  9969. }(ClickableComponent);
  9970. Component$1.registerComponent('Button', Button);
  9971. /**
  9972. * The initial play button that shows before the video has played. The hiding of the
  9973. * `BigPlayButton` get done via CSS and `Player` states.
  9974. *
  9975. * @extends Button
  9976. */
  9977. var BigPlayButton = /*#__PURE__*/function (_Button) {
  9978. _inheritsLoose__default['default'](BigPlayButton, _Button);
  9979. function BigPlayButton(player, options) {
  9980. var _this;
  9981. _this = _Button.call(this, player, options) || this;
  9982. _this.mouseused_ = false;
  9983. _this.on('mousedown', function (e) {
  9984. return _this.handleMouseDown(e);
  9985. });
  9986. return _this;
  9987. }
  9988. /**
  9989. * Builds the default DOM `className`.
  9990. *
  9991. * @return {string}
  9992. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  9993. */
  9994. var _proto = BigPlayButton.prototype;
  9995. _proto.buildCSSClass = function buildCSSClass() {
  9996. return 'vjs-big-play-button';
  9997. }
  9998. /**
  9999. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  10000. * for more detailed information on what a click can be.
  10001. *
  10002. * @param {EventTarget~Event} event
  10003. * The `keydown`, `tap`, or `click` event that caused this function to be
  10004. * called.
  10005. *
  10006. * @listens tap
  10007. * @listens click
  10008. */
  10009. ;
  10010. _proto.handleClick = function handleClick(event) {
  10011. var playPromise = this.player_.play(); // exit early if clicked via the mouse
  10012. if (this.mouseused_ && event.clientX && event.clientY) {
  10013. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  10014. silencePromise(playPromise);
  10015. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  10016. // calling .focus() on the video element causes the video to go black,
  10017. // so we avoid it in that specific case
  10018. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  10019. this.player_.tech(true).focus();
  10020. }
  10021. return;
  10022. }
  10023. var cb = this.player_.getChild('controlBar');
  10024. var playToggle = cb && cb.getChild('playToggle');
  10025. if (!playToggle) {
  10026. this.player_.tech(true).focus();
  10027. return;
  10028. }
  10029. var playFocus = function playFocus() {
  10030. return playToggle.focus();
  10031. };
  10032. if (isPromise(playPromise)) {
  10033. playPromise.then(playFocus, function () {});
  10034. } else {
  10035. this.setTimeout(playFocus, 1);
  10036. }
  10037. };
  10038. _proto.handleKeyDown = function handleKeyDown(event) {
  10039. this.mouseused_ = false;
  10040. _Button.prototype.handleKeyDown.call(this, event);
  10041. };
  10042. _proto.handleMouseDown = function handleMouseDown(event) {
  10043. this.mouseused_ = true;
  10044. };
  10045. return BigPlayButton;
  10046. }(Button);
  10047. /**
  10048. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  10049. *
  10050. * @type {string}
  10051. * @private
  10052. */
  10053. BigPlayButton.prototype.controlText_ = 'Play Video';
  10054. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  10055. /**
  10056. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  10057. * it gets clicked.
  10058. *
  10059. * @extends Button
  10060. */
  10061. var CloseButton = /*#__PURE__*/function (_Button) {
  10062. _inheritsLoose__default['default'](CloseButton, _Button);
  10063. /**
  10064. * Creates an instance of the this class.
  10065. *
  10066. * @param {Player} player
  10067. * The `Player` that this class should be attached to.
  10068. *
  10069. * @param {Object} [options]
  10070. * The key/value store of player options.
  10071. */
  10072. function CloseButton(player, options) {
  10073. var _this;
  10074. _this = _Button.call(this, player, options) || this;
  10075. _this.controlText(options && options.controlText || _this.localize('Close'));
  10076. return _this;
  10077. }
  10078. /**
  10079. * Builds the default DOM `className`.
  10080. *
  10081. * @return {string}
  10082. * The DOM `className` for this object.
  10083. */
  10084. var _proto = CloseButton.prototype;
  10085. _proto.buildCSSClass = function buildCSSClass() {
  10086. return "vjs-close-button " + _Button.prototype.buildCSSClass.call(this);
  10087. }
  10088. /**
  10089. * This gets called when a `CloseButton` gets clicked. See
  10090. * {@link ClickableComponent#handleClick} for more information on when
  10091. * this will be triggered
  10092. *
  10093. * @param {EventTarget~Event} event
  10094. * The `keydown`, `tap`, or `click` event that caused this function to be
  10095. * called.
  10096. *
  10097. * @listens tap
  10098. * @listens click
  10099. * @fires CloseButton#close
  10100. */
  10101. ;
  10102. _proto.handleClick = function handleClick(event) {
  10103. /**
  10104. * Triggered when the a `CloseButton` is clicked.
  10105. *
  10106. * @event CloseButton#close
  10107. * @type {EventTarget~Event}
  10108. *
  10109. * @property {boolean} [bubbles=false]
  10110. * set to false so that the close event does not
  10111. * bubble up to parents if there is no listener
  10112. */
  10113. this.trigger({
  10114. type: 'close',
  10115. bubbles: false
  10116. });
  10117. }
  10118. /**
  10119. * Event handler that is called when a `CloseButton` receives a
  10120. * `keydown` event.
  10121. *
  10122. * By default, if the key is Esc, it will trigger a `click` event.
  10123. *
  10124. * @param {EventTarget~Event} event
  10125. * The `keydown` event that caused this function to be called.
  10126. *
  10127. * @listens keydown
  10128. */
  10129. ;
  10130. _proto.handleKeyDown = function handleKeyDown(event) {
  10131. // Esc button will trigger `click` event
  10132. if (keycode__default['default'].isEventKey(event, 'Esc')) {
  10133. event.preventDefault();
  10134. event.stopPropagation();
  10135. this.trigger('click');
  10136. } else {
  10137. // Pass keypress handling up for unsupported keys
  10138. _Button.prototype.handleKeyDown.call(this, event);
  10139. }
  10140. };
  10141. return CloseButton;
  10142. }(Button);
  10143. Component$1.registerComponent('CloseButton', CloseButton);
  10144. /**
  10145. * Button to toggle between play and pause.
  10146. *
  10147. * @extends Button
  10148. */
  10149. var PlayToggle = /*#__PURE__*/function (_Button) {
  10150. _inheritsLoose__default['default'](PlayToggle, _Button);
  10151. /**
  10152. * Creates an instance of this class.
  10153. *
  10154. * @param {Player} player
  10155. * The `Player` that this class should be attached to.
  10156. *
  10157. * @param {Object} [options={}]
  10158. * The key/value store of player options.
  10159. */
  10160. function PlayToggle(player, options) {
  10161. var _this;
  10162. if (options === void 0) {
  10163. options = {};
  10164. }
  10165. _this = _Button.call(this, player, options) || this; // show or hide replay icon
  10166. options.replay = options.replay === undefined || options.replay;
  10167. _this.on(player, 'play', function (e) {
  10168. return _this.handlePlay(e);
  10169. });
  10170. _this.on(player, 'pause', function (e) {
  10171. return _this.handlePause(e);
  10172. });
  10173. if (options.replay) {
  10174. _this.on(player, 'ended', function (e) {
  10175. return _this.handleEnded(e);
  10176. });
  10177. }
  10178. return _this;
  10179. }
  10180. /**
  10181. * Builds the default DOM `className`.
  10182. *
  10183. * @return {string}
  10184. * The DOM `className` for this object.
  10185. */
  10186. var _proto = PlayToggle.prototype;
  10187. _proto.buildCSSClass = function buildCSSClass() {
  10188. return "vjs-play-control " + _Button.prototype.buildCSSClass.call(this);
  10189. }
  10190. /**
  10191. * This gets called when an `PlayToggle` is "clicked". See
  10192. * {@link ClickableComponent} for more detailed information on what a click can be.
  10193. *
  10194. * @param {EventTarget~Event} [event]
  10195. * The `keydown`, `tap`, or `click` event that caused this function to be
  10196. * called.
  10197. *
  10198. * @listens tap
  10199. * @listens click
  10200. */
  10201. ;
  10202. _proto.handleClick = function handleClick(event) {
  10203. if (this.player_.paused()) {
  10204. silencePromise(this.player_.play());
  10205. } else {
  10206. this.player_.pause();
  10207. }
  10208. }
  10209. /**
  10210. * This gets called once after the video has ended and the user seeks so that
  10211. * we can change the replay button back to a play button.
  10212. *
  10213. * @param {EventTarget~Event} [event]
  10214. * The event that caused this function to run.
  10215. *
  10216. * @listens Player#seeked
  10217. */
  10218. ;
  10219. _proto.handleSeeked = function handleSeeked(event) {
  10220. this.removeClass('vjs-ended');
  10221. if (this.player_.paused()) {
  10222. this.handlePause(event);
  10223. } else {
  10224. this.handlePlay(event);
  10225. }
  10226. }
  10227. /**
  10228. * Add the vjs-playing class to the element so it can change appearance.
  10229. *
  10230. * @param {EventTarget~Event} [event]
  10231. * The event that caused this function to run.
  10232. *
  10233. * @listens Player#play
  10234. */
  10235. ;
  10236. _proto.handlePlay = function handlePlay(event) {
  10237. this.removeClass('vjs-ended');
  10238. this.removeClass('vjs-paused');
  10239. this.addClass('vjs-playing'); // change the button text to "Pause"
  10240. this.controlText('Pause');
  10241. }
  10242. /**
  10243. * Add the vjs-paused class to the element so it can change appearance.
  10244. *
  10245. * @param {EventTarget~Event} [event]
  10246. * The event that caused this function to run.
  10247. *
  10248. * @listens Player#pause
  10249. */
  10250. ;
  10251. _proto.handlePause = function handlePause(event) {
  10252. this.removeClass('vjs-playing');
  10253. this.addClass('vjs-paused'); // change the button text to "Play"
  10254. this.controlText('Play');
  10255. }
  10256. /**
  10257. * Add the vjs-ended class to the element so it can change appearance
  10258. *
  10259. * @param {EventTarget~Event} [event]
  10260. * The event that caused this function to run.
  10261. *
  10262. * @listens Player#ended
  10263. */
  10264. ;
  10265. _proto.handleEnded = function handleEnded(event) {
  10266. var _this2 = this;
  10267. this.removeClass('vjs-playing');
  10268. this.addClass('vjs-ended'); // change the button text to "Replay"
  10269. this.controlText('Replay'); // on the next seek remove the replay button
  10270. this.one(this.player_, 'seeked', function (e) {
  10271. return _this2.handleSeeked(e);
  10272. });
  10273. };
  10274. return PlayToggle;
  10275. }(Button);
  10276. /**
  10277. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10278. *
  10279. * @type {string}
  10280. * @private
  10281. */
  10282. PlayToggle.prototype.controlText_ = 'Play';
  10283. Component$1.registerComponent('PlayToggle', PlayToggle);
  10284. /**
  10285. * @file format-time.js
  10286. * @module format-time
  10287. */
  10288. /**
  10289. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  10290. * seconds) will force a number of leading zeros to cover the length of the
  10291. * guide.
  10292. *
  10293. * @private
  10294. * @param {number} seconds
  10295. * Number of seconds to be turned into a string
  10296. *
  10297. * @param {number} guide
  10298. * Number (in seconds) to model the string after
  10299. *
  10300. * @return {string}
  10301. * Time formatted as H:MM:SS or M:SS
  10302. */
  10303. var defaultImplementation = function defaultImplementation(seconds, guide) {
  10304. seconds = seconds < 0 ? 0 : seconds;
  10305. var s = Math.floor(seconds % 60);
  10306. var m = Math.floor(seconds / 60 % 60);
  10307. var h = Math.floor(seconds / 3600);
  10308. var gm = Math.floor(guide / 60 % 60);
  10309. var gh = Math.floor(guide / 3600); // handle invalid times
  10310. if (isNaN(seconds) || seconds === Infinity) {
  10311. // '-' is false for all relational operators (e.g. <, >=) so this setting
  10312. // will add the minimum number of fields specified by the guide
  10313. h = m = s = '-';
  10314. } // Check if we need to show hours
  10315. h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero.
  10316. // Always show at least one digit of minutes.
  10317. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds
  10318. s = s < 10 ? '0' + s : s;
  10319. return h + m + s;
  10320. }; // Internal pointer to the current implementation.
  10321. var implementation = defaultImplementation;
  10322. /**
  10323. * Replaces the default formatTime implementation with a custom implementation.
  10324. *
  10325. * @param {Function} customImplementation
  10326. * A function which will be used in place of the default formatTime
  10327. * implementation. Will receive the current time in seconds and the
  10328. * guide (in seconds) as arguments.
  10329. */
  10330. function setFormatTime(customImplementation) {
  10331. implementation = customImplementation;
  10332. }
  10333. /**
  10334. * Resets formatTime to the default implementation.
  10335. */
  10336. function resetFormatTime() {
  10337. implementation = defaultImplementation;
  10338. }
  10339. /**
  10340. * Delegates to either the default time formatting function or a custom
  10341. * function supplied via `setFormatTime`.
  10342. *
  10343. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  10344. * guide (in seconds) will force a number of leading zeros to cover the
  10345. * length of the guide.
  10346. *
  10347. * @static
  10348. * @example formatTime(125, 600) === "02:05"
  10349. * @param {number} seconds
  10350. * Number of seconds to be turned into a string
  10351. *
  10352. * @param {number} guide
  10353. * Number (in seconds) to model the string after
  10354. *
  10355. * @return {string}
  10356. * Time formatted as H:MM:SS or M:SS
  10357. */
  10358. function formatTime(seconds, guide) {
  10359. if (guide === void 0) {
  10360. guide = seconds;
  10361. }
  10362. return implementation(seconds, guide);
  10363. }
  10364. /**
  10365. * Displays time information about the video
  10366. *
  10367. * @extends Component
  10368. */
  10369. var TimeDisplay = /*#__PURE__*/function (_Component) {
  10370. _inheritsLoose__default['default'](TimeDisplay, _Component);
  10371. /**
  10372. * Creates an instance of this class.
  10373. *
  10374. * @param {Player} player
  10375. * The `Player` that this class should be attached to.
  10376. *
  10377. * @param {Object} [options]
  10378. * The key/value store of player options.
  10379. */
  10380. function TimeDisplay(player, options) {
  10381. var _this;
  10382. _this = _Component.call(this, player, options) || this;
  10383. _this.on(player, ['timeupdate', 'ended'], function (e) {
  10384. return _this.updateContent(e);
  10385. });
  10386. _this.updateTextNode_();
  10387. return _this;
  10388. }
  10389. /**
  10390. * Create the `Component`'s DOM element
  10391. *
  10392. * @return {Element}
  10393. * The element that was created.
  10394. */
  10395. var _proto = TimeDisplay.prototype;
  10396. _proto.createEl = function createEl$1() {
  10397. var className = this.buildCSSClass();
  10398. var el = _Component.prototype.createEl.call(this, 'div', {
  10399. className: className + " vjs-time-control vjs-control"
  10400. });
  10401. var span = createEl('span', {
  10402. className: 'vjs-control-text',
  10403. textContent: this.localize(this.labelText_) + "\xA0"
  10404. }, {
  10405. role: 'presentation'
  10406. });
  10407. el.appendChild(span);
  10408. this.contentEl_ = createEl('span', {
  10409. className: className + "-display"
  10410. }, {
  10411. // tell screen readers not to automatically read the time as it changes
  10412. 'aria-live': 'off',
  10413. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10414. // treat them as a break between items in the DOM when using arrow keys
  10415. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10416. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10417. 'role': 'presentation'
  10418. });
  10419. el.appendChild(this.contentEl_);
  10420. return el;
  10421. };
  10422. _proto.dispose = function dispose() {
  10423. this.contentEl_ = null;
  10424. this.textNode_ = null;
  10425. _Component.prototype.dispose.call(this);
  10426. }
  10427. /**
  10428. * Updates the time display text node with a new time
  10429. *
  10430. * @param {number} [time=0] the time to update to
  10431. *
  10432. * @private
  10433. */
  10434. ;
  10435. _proto.updateTextNode_ = function updateTextNode_(time) {
  10436. var _this2 = this;
  10437. if (time === void 0) {
  10438. time = 0;
  10439. }
  10440. time = formatTime(time);
  10441. if (this.formattedTime_ === time) {
  10442. return;
  10443. }
  10444. this.formattedTime_ = time;
  10445. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', function () {
  10446. if (!_this2.contentEl_) {
  10447. return;
  10448. }
  10449. var oldNode = _this2.textNode_;
  10450. if (oldNode && _this2.contentEl_.firstChild !== oldNode) {
  10451. oldNode = null;
  10452. 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.');
  10453. }
  10454. _this2.textNode_ = document__default['default'].createTextNode(_this2.formattedTime_);
  10455. if (!_this2.textNode_) {
  10456. return;
  10457. }
  10458. if (oldNode) {
  10459. _this2.contentEl_.replaceChild(_this2.textNode_, oldNode);
  10460. } else {
  10461. _this2.contentEl_.appendChild(_this2.textNode_);
  10462. }
  10463. });
  10464. }
  10465. /**
  10466. * To be filled out in the child class, should update the displayed time
  10467. * in accordance with the fact that the current time has changed.
  10468. *
  10469. * @param {EventTarget~Event} [event]
  10470. * The `timeupdate` event that caused this to run.
  10471. *
  10472. * @listens Player#timeupdate
  10473. */
  10474. ;
  10475. _proto.updateContent = function updateContent(event) {};
  10476. return TimeDisplay;
  10477. }(Component$1);
  10478. /**
  10479. * The text that is added to the `TimeDisplay` for screen reader users.
  10480. *
  10481. * @type {string}
  10482. * @private
  10483. */
  10484. TimeDisplay.prototype.labelText_ = 'Time';
  10485. /**
  10486. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10487. *
  10488. * @type {string}
  10489. * @private
  10490. *
  10491. * @deprecated in v7; controlText_ is not used in non-active display Components
  10492. */
  10493. TimeDisplay.prototype.controlText_ = 'Time';
  10494. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  10495. /**
  10496. * Displays the current time
  10497. *
  10498. * @extends Component
  10499. */
  10500. var CurrentTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  10501. _inheritsLoose__default['default'](CurrentTimeDisplay, _TimeDisplay);
  10502. function CurrentTimeDisplay() {
  10503. return _TimeDisplay.apply(this, arguments) || this;
  10504. }
  10505. var _proto = CurrentTimeDisplay.prototype;
  10506. /**
  10507. * Builds the default DOM `className`.
  10508. *
  10509. * @return {string}
  10510. * The DOM `className` for this object.
  10511. */
  10512. _proto.buildCSSClass = function buildCSSClass() {
  10513. return 'vjs-current-time';
  10514. }
  10515. /**
  10516. * Update current time display
  10517. *
  10518. * @param {EventTarget~Event} [event]
  10519. * The `timeupdate` event that caused this function to run.
  10520. *
  10521. * @listens Player#timeupdate
  10522. */
  10523. ;
  10524. _proto.updateContent = function updateContent(event) {
  10525. // Allows for smooth scrubbing, when player can't keep up.
  10526. var time;
  10527. if (this.player_.ended()) {
  10528. time = this.player_.duration();
  10529. } else {
  10530. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  10531. }
  10532. this.updateTextNode_(time);
  10533. };
  10534. return CurrentTimeDisplay;
  10535. }(TimeDisplay);
  10536. /**
  10537. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  10538. *
  10539. * @type {string}
  10540. * @private
  10541. */
  10542. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  10543. /**
  10544. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  10545. *
  10546. * @type {string}
  10547. * @private
  10548. *
  10549. * @deprecated in v7; controlText_ is not used in non-active display Components
  10550. */
  10551. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  10552. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  10553. /**
  10554. * Displays the duration
  10555. *
  10556. * @extends Component
  10557. */
  10558. var DurationDisplay = /*#__PURE__*/function (_TimeDisplay) {
  10559. _inheritsLoose__default['default'](DurationDisplay, _TimeDisplay);
  10560. /**
  10561. * Creates an instance of this class.
  10562. *
  10563. * @param {Player} player
  10564. * The `Player` that this class should be attached to.
  10565. *
  10566. * @param {Object} [options]
  10567. * The key/value store of player options.
  10568. */
  10569. function DurationDisplay(player, options) {
  10570. var _this;
  10571. _this = _TimeDisplay.call(this, player, options) || this;
  10572. var updateContent = function updateContent(e) {
  10573. return _this.updateContent(e);
  10574. }; // we do not want to/need to throttle duration changes,
  10575. // as they should always display the changed duration as
  10576. // it has changed
  10577. _this.on(player, 'durationchange', updateContent); // Listen to loadstart because the player duration is reset when a new media element is loaded,
  10578. // but the durationchange on the user agent will not fire.
  10579. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  10580. _this.on(player, 'loadstart', updateContent); // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  10581. // listeners could have broken dependent applications/libraries. These
  10582. // can likely be removed for 7.0.
  10583. _this.on(player, 'loadedmetadata', updateContent);
  10584. return _this;
  10585. }
  10586. /**
  10587. * Builds the default DOM `className`.
  10588. *
  10589. * @return {string}
  10590. * The DOM `className` for this object.
  10591. */
  10592. var _proto = DurationDisplay.prototype;
  10593. _proto.buildCSSClass = function buildCSSClass() {
  10594. return 'vjs-duration';
  10595. }
  10596. /**
  10597. * Update duration time display.
  10598. *
  10599. * @param {EventTarget~Event} [event]
  10600. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  10601. * this function to be called.
  10602. *
  10603. * @listens Player#durationchange
  10604. * @listens Player#timeupdate
  10605. * @listens Player#loadedmetadata
  10606. */
  10607. ;
  10608. _proto.updateContent = function updateContent(event) {
  10609. var duration = this.player_.duration();
  10610. this.updateTextNode_(duration);
  10611. };
  10612. return DurationDisplay;
  10613. }(TimeDisplay);
  10614. /**
  10615. * The text that is added to the `DurationDisplay` for screen reader users.
  10616. *
  10617. * @type {string}
  10618. * @private
  10619. */
  10620. DurationDisplay.prototype.labelText_ = 'Duration';
  10621. /**
  10622. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  10623. *
  10624. * @type {string}
  10625. * @private
  10626. *
  10627. * @deprecated in v7; controlText_ is not used in non-active display Components
  10628. */
  10629. DurationDisplay.prototype.controlText_ = 'Duration';
  10630. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  10631. /**
  10632. * The separator between the current time and duration.
  10633. * Can be hidden if it's not needed in the design.
  10634. *
  10635. * @extends Component
  10636. */
  10637. var TimeDivider = /*#__PURE__*/function (_Component) {
  10638. _inheritsLoose__default['default'](TimeDivider, _Component);
  10639. function TimeDivider() {
  10640. return _Component.apply(this, arguments) || this;
  10641. }
  10642. var _proto = TimeDivider.prototype;
  10643. /**
  10644. * Create the component's DOM element
  10645. *
  10646. * @return {Element}
  10647. * The element that was created.
  10648. */
  10649. _proto.createEl = function createEl() {
  10650. var el = _Component.prototype.createEl.call(this, 'div', {
  10651. className: 'vjs-time-control vjs-time-divider'
  10652. }, {
  10653. // this element and its contents can be hidden from assistive techs since
  10654. // it is made extraneous by the announcement of the control text
  10655. // for the current time and duration displays
  10656. 'aria-hidden': true
  10657. });
  10658. var div = _Component.prototype.createEl.call(this, 'div');
  10659. var span = _Component.prototype.createEl.call(this, 'span', {
  10660. textContent: '/'
  10661. });
  10662. div.appendChild(span);
  10663. el.appendChild(div);
  10664. return el;
  10665. };
  10666. return TimeDivider;
  10667. }(Component$1);
  10668. Component$1.registerComponent('TimeDivider', TimeDivider);
  10669. /**
  10670. * Displays the time left in the video
  10671. *
  10672. * @extends Component
  10673. */
  10674. var RemainingTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  10675. _inheritsLoose__default['default'](RemainingTimeDisplay, _TimeDisplay);
  10676. /**
  10677. * Creates an instance of this class.
  10678. *
  10679. * @param {Player} player
  10680. * The `Player` that this class should be attached to.
  10681. *
  10682. * @param {Object} [options]
  10683. * The key/value store of player options.
  10684. */
  10685. function RemainingTimeDisplay(player, options) {
  10686. var _this;
  10687. _this = _TimeDisplay.call(this, player, options) || this;
  10688. _this.on(player, 'durationchange', function (e) {
  10689. return _this.updateContent(e);
  10690. });
  10691. return _this;
  10692. }
  10693. /**
  10694. * Builds the default DOM `className`.
  10695. *
  10696. * @return {string}
  10697. * The DOM `className` for this object.
  10698. */
  10699. var _proto = RemainingTimeDisplay.prototype;
  10700. _proto.buildCSSClass = function buildCSSClass() {
  10701. return 'vjs-remaining-time';
  10702. }
  10703. /**
  10704. * Create the `Component`'s DOM element with the "minus" characted prepend to the time
  10705. *
  10706. * @return {Element}
  10707. * The element that was created.
  10708. */
  10709. ;
  10710. _proto.createEl = function createEl$1() {
  10711. var el = _TimeDisplay.prototype.createEl.call(this);
  10712. if (this.options_.displayNegative !== false) {
  10713. el.insertBefore(createEl('span', {}, {
  10714. 'aria-hidden': true
  10715. }, '-'), this.contentEl_);
  10716. }
  10717. return el;
  10718. }
  10719. /**
  10720. * Update remaining time display.
  10721. *
  10722. * @param {EventTarget~Event} [event]
  10723. * The `timeupdate` or `durationchange` event that caused this to run.
  10724. *
  10725. * @listens Player#timeupdate
  10726. * @listens Player#durationchange
  10727. */
  10728. ;
  10729. _proto.updateContent = function updateContent(event) {
  10730. if (typeof this.player_.duration() !== 'number') {
  10731. return;
  10732. }
  10733. var time; // @deprecated We should only use remainingTimeDisplay
  10734. // as of video.js 7
  10735. if (this.player_.ended()) {
  10736. time = 0;
  10737. } else if (this.player_.remainingTimeDisplay) {
  10738. time = this.player_.remainingTimeDisplay();
  10739. } else {
  10740. time = this.player_.remainingTime();
  10741. }
  10742. this.updateTextNode_(time);
  10743. };
  10744. return RemainingTimeDisplay;
  10745. }(TimeDisplay);
  10746. /**
  10747. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  10748. *
  10749. * @type {string}
  10750. * @private
  10751. */
  10752. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  10753. /**
  10754. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  10755. *
  10756. * @type {string}
  10757. * @private
  10758. *
  10759. * @deprecated in v7; controlText_ is not used in non-active display Components
  10760. */
  10761. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  10762. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  10763. /**
  10764. * Displays the live indicator when duration is Infinity.
  10765. *
  10766. * @extends Component
  10767. */
  10768. var LiveDisplay = /*#__PURE__*/function (_Component) {
  10769. _inheritsLoose__default['default'](LiveDisplay, _Component);
  10770. /**
  10771. * Creates an instance of this class.
  10772. *
  10773. * @param {Player} player
  10774. * The `Player` that this class should be attached to.
  10775. *
  10776. * @param {Object} [options]
  10777. * The key/value store of player options.
  10778. */
  10779. function LiveDisplay(player, options) {
  10780. var _this;
  10781. _this = _Component.call(this, player, options) || this;
  10782. _this.updateShowing();
  10783. _this.on(_this.player(), 'durationchange', function (e) {
  10784. return _this.updateShowing(e);
  10785. });
  10786. return _this;
  10787. }
  10788. /**
  10789. * Create the `Component`'s DOM element
  10790. *
  10791. * @return {Element}
  10792. * The element that was created.
  10793. */
  10794. var _proto = LiveDisplay.prototype;
  10795. _proto.createEl = function createEl$1() {
  10796. var el = _Component.prototype.createEl.call(this, 'div', {
  10797. className: 'vjs-live-control vjs-control'
  10798. });
  10799. this.contentEl_ = createEl('div', {
  10800. className: 'vjs-live-display'
  10801. }, {
  10802. 'aria-live': 'off'
  10803. });
  10804. this.contentEl_.appendChild(createEl('span', {
  10805. className: 'vjs-control-text',
  10806. textContent: this.localize('Stream Type') + "\xA0"
  10807. }));
  10808. this.contentEl_.appendChild(document__default['default'].createTextNode(this.localize('LIVE')));
  10809. el.appendChild(this.contentEl_);
  10810. return el;
  10811. };
  10812. _proto.dispose = function dispose() {
  10813. this.contentEl_ = null;
  10814. _Component.prototype.dispose.call(this);
  10815. }
  10816. /**
  10817. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  10818. * it accordingly
  10819. *
  10820. * @param {EventTarget~Event} [event]
  10821. * The {@link Player#durationchange} event that caused this function to run.
  10822. *
  10823. * @listens Player#durationchange
  10824. */
  10825. ;
  10826. _proto.updateShowing = function updateShowing(event) {
  10827. if (this.player().duration() === Infinity) {
  10828. this.show();
  10829. } else {
  10830. this.hide();
  10831. }
  10832. };
  10833. return LiveDisplay;
  10834. }(Component$1);
  10835. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  10836. /**
  10837. * Displays the live indicator when duration is Infinity.
  10838. *
  10839. * @extends Component
  10840. */
  10841. var SeekToLive = /*#__PURE__*/function (_Button) {
  10842. _inheritsLoose__default['default'](SeekToLive, _Button);
  10843. /**
  10844. * Creates an instance of this class.
  10845. *
  10846. * @param {Player} player
  10847. * The `Player` that this class should be attached to.
  10848. *
  10849. * @param {Object} [options]
  10850. * The key/value store of player options.
  10851. */
  10852. function SeekToLive(player, options) {
  10853. var _this;
  10854. _this = _Button.call(this, player, options) || this;
  10855. _this.updateLiveEdgeStatus();
  10856. if (_this.player_.liveTracker) {
  10857. _this.updateLiveEdgeStatusHandler_ = function (e) {
  10858. return _this.updateLiveEdgeStatus(e);
  10859. };
  10860. _this.on(_this.player_.liveTracker, 'liveedgechange', _this.updateLiveEdgeStatusHandler_);
  10861. }
  10862. return _this;
  10863. }
  10864. /**
  10865. * Create the `Component`'s DOM element
  10866. *
  10867. * @return {Element}
  10868. * The element that was created.
  10869. */
  10870. var _proto = SeekToLive.prototype;
  10871. _proto.createEl = function createEl$1() {
  10872. var el = _Button.prototype.createEl.call(this, 'button', {
  10873. className: 'vjs-seek-to-live-control vjs-control'
  10874. });
  10875. this.textEl_ = createEl('span', {
  10876. className: 'vjs-seek-to-live-text',
  10877. textContent: this.localize('LIVE')
  10878. }, {
  10879. 'aria-hidden': 'true'
  10880. });
  10881. el.appendChild(this.textEl_);
  10882. return el;
  10883. }
  10884. /**
  10885. * Update the state of this button if we are at the live edge
  10886. * or not
  10887. */
  10888. ;
  10889. _proto.updateLiveEdgeStatus = function updateLiveEdgeStatus() {
  10890. // default to live edge
  10891. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  10892. this.setAttribute('aria-disabled', true);
  10893. this.addClass('vjs-at-live-edge');
  10894. this.controlText('Seek to live, currently playing live');
  10895. } else {
  10896. this.setAttribute('aria-disabled', false);
  10897. this.removeClass('vjs-at-live-edge');
  10898. this.controlText('Seek to live, currently behind live');
  10899. }
  10900. }
  10901. /**
  10902. * On click bring us as near to the live point as possible.
  10903. * This requires that we wait for the next `live-seekable-change`
  10904. * event which will happen every segment length seconds.
  10905. */
  10906. ;
  10907. _proto.handleClick = function handleClick() {
  10908. this.player_.liveTracker.seekToLiveEdge();
  10909. }
  10910. /**
  10911. * Dispose of the element and stop tracking
  10912. */
  10913. ;
  10914. _proto.dispose = function dispose() {
  10915. if (this.player_.liveTracker) {
  10916. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  10917. }
  10918. this.textEl_ = null;
  10919. _Button.prototype.dispose.call(this);
  10920. };
  10921. return SeekToLive;
  10922. }(Button);
  10923. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  10924. Component$1.registerComponent('SeekToLive', SeekToLive);
  10925. /**
  10926. * Keep a number between a min and a max value
  10927. *
  10928. * @param {number} number
  10929. * The number to clamp
  10930. *
  10931. * @param {number} min
  10932. * The minimum value
  10933. * @param {number} max
  10934. * The maximum value
  10935. *
  10936. * @return {number}
  10937. * the clamped number
  10938. */
  10939. var clamp = function clamp(number, min, max) {
  10940. number = Number(number);
  10941. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  10942. };
  10943. /**
  10944. * The base functionality for a slider. Can be vertical or horizontal.
  10945. * For instance the volume bar or the seek bar on a video is a slider.
  10946. *
  10947. * @extends Component
  10948. */
  10949. var Slider = /*#__PURE__*/function (_Component) {
  10950. _inheritsLoose__default['default'](Slider, _Component);
  10951. /**
  10952. * Create an instance of this class
  10953. *
  10954. * @param {Player} player
  10955. * The `Player` that this class should be attached to.
  10956. *
  10957. * @param {Object} [options]
  10958. * The key/value store of player options.
  10959. */
  10960. function Slider(player, options) {
  10961. var _this;
  10962. _this = _Component.call(this, player, options) || this;
  10963. _this.handleMouseDown_ = function (e) {
  10964. return _this.handleMouseDown(e);
  10965. };
  10966. _this.handleMouseUp_ = function (e) {
  10967. return _this.handleMouseUp(e);
  10968. };
  10969. _this.handleKeyDown_ = function (e) {
  10970. return _this.handleKeyDown(e);
  10971. };
  10972. _this.handleClick_ = function (e) {
  10973. return _this.handleClick(e);
  10974. };
  10975. _this.handleMouseMove_ = function (e) {
  10976. return _this.handleMouseMove(e);
  10977. };
  10978. _this.update_ = function (e) {
  10979. return _this.update(e);
  10980. }; // Set property names to bar to match with the child Slider class is looking for
  10981. _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type
  10982. _this.vertical(!!_this.options_.vertical);
  10983. _this.enable();
  10984. return _this;
  10985. }
  10986. /**
  10987. * Are controls are currently enabled for this slider or not.
  10988. *
  10989. * @return {boolean}
  10990. * true if controls are enabled, false otherwise
  10991. */
  10992. var _proto = Slider.prototype;
  10993. _proto.enabled = function enabled() {
  10994. return this.enabled_;
  10995. }
  10996. /**
  10997. * Enable controls for this slider if they are disabled
  10998. */
  10999. ;
  11000. _proto.enable = function enable() {
  11001. if (this.enabled()) {
  11002. return;
  11003. }
  11004. this.on('mousedown', this.handleMouseDown_);
  11005. this.on('touchstart', this.handleMouseDown_);
  11006. this.on('keydown', this.handleKeyDown_);
  11007. this.on('click', this.handleClick_); // TODO: deprecated, controlsvisible does not seem to be fired
  11008. this.on(this.player_, 'controlsvisible', this.update);
  11009. if (this.playerEvent) {
  11010. this.on(this.player_, this.playerEvent, this.update);
  11011. }
  11012. this.removeClass('disabled');
  11013. this.setAttribute('tabindex', 0);
  11014. this.enabled_ = true;
  11015. }
  11016. /**
  11017. * Disable controls for this slider if they are enabled
  11018. */
  11019. ;
  11020. _proto.disable = function disable() {
  11021. if (!this.enabled()) {
  11022. return;
  11023. }
  11024. var doc = this.bar.el_.ownerDocument;
  11025. this.off('mousedown', this.handleMouseDown_);
  11026. this.off('touchstart', this.handleMouseDown_);
  11027. this.off('keydown', this.handleKeyDown_);
  11028. this.off('click', this.handleClick_);
  11029. this.off(this.player_, 'controlsvisible', this.update_);
  11030. this.off(doc, 'mousemove', this.handleMouseMove_);
  11031. this.off(doc, 'mouseup', this.handleMouseUp_);
  11032. this.off(doc, 'touchmove', this.handleMouseMove_);
  11033. this.off(doc, 'touchend', this.handleMouseUp_);
  11034. this.removeAttribute('tabindex');
  11035. this.addClass('disabled');
  11036. if (this.playerEvent) {
  11037. this.off(this.player_, this.playerEvent, this.update);
  11038. }
  11039. this.enabled_ = false;
  11040. }
  11041. /**
  11042. * Create the `Slider`s DOM element.
  11043. *
  11044. * @param {string} type
  11045. * Type of element to create.
  11046. *
  11047. * @param {Object} [props={}]
  11048. * List of properties in Object form.
  11049. *
  11050. * @param {Object} [attributes={}]
  11051. * list of attributes in Object form.
  11052. *
  11053. * @return {Element}
  11054. * The element that gets created.
  11055. */
  11056. ;
  11057. _proto.createEl = function createEl(type, props, attributes) {
  11058. if (props === void 0) {
  11059. props = {};
  11060. }
  11061. if (attributes === void 0) {
  11062. attributes = {};
  11063. }
  11064. // Add the slider element class to all sub classes
  11065. props.className = props.className + ' vjs-slider';
  11066. props = assign({
  11067. tabIndex: 0
  11068. }, props);
  11069. attributes = assign({
  11070. 'role': 'slider',
  11071. 'aria-valuenow': 0,
  11072. 'aria-valuemin': 0,
  11073. 'aria-valuemax': 100,
  11074. 'tabIndex': 0
  11075. }, attributes);
  11076. return _Component.prototype.createEl.call(this, type, props, attributes);
  11077. }
  11078. /**
  11079. * Handle `mousedown` or `touchstart` events on the `Slider`.
  11080. *
  11081. * @param {EventTarget~Event} event
  11082. * `mousedown` or `touchstart` event that triggered this function
  11083. *
  11084. * @listens mousedown
  11085. * @listens touchstart
  11086. * @fires Slider#slideractive
  11087. */
  11088. ;
  11089. _proto.handleMouseDown = function handleMouseDown(event) {
  11090. var doc = this.bar.el_.ownerDocument;
  11091. if (event.type === 'mousedown') {
  11092. event.preventDefault();
  11093. } // Do not call preventDefault() on touchstart in Chrome
  11094. // to avoid console warnings. Use a 'touch-action: none' style
  11095. // instead to prevent unintented scrolling.
  11096. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  11097. if (event.type === 'touchstart' && !IS_CHROME) {
  11098. event.preventDefault();
  11099. }
  11100. blockTextSelection();
  11101. this.addClass('vjs-sliding');
  11102. /**
  11103. * Triggered when the slider is in an active state
  11104. *
  11105. * @event Slider#slideractive
  11106. * @type {EventTarget~Event}
  11107. */
  11108. this.trigger('slideractive');
  11109. this.on(doc, 'mousemove', this.handleMouseMove_);
  11110. this.on(doc, 'mouseup', this.handleMouseUp_);
  11111. this.on(doc, 'touchmove', this.handleMouseMove_);
  11112. this.on(doc, 'touchend', this.handleMouseUp_);
  11113. this.handleMouseMove(event, true);
  11114. }
  11115. /**
  11116. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  11117. * The `mousemove` and `touchmove` events will only only trigger this function during
  11118. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  11119. * {@link Slider#handleMouseUp}.
  11120. *
  11121. * @param {EventTarget~Event} event
  11122. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  11123. * this function
  11124. * @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.
  11125. *
  11126. * @listens mousemove
  11127. * @listens touchmove
  11128. */
  11129. ;
  11130. _proto.handleMouseMove = function handleMouseMove(event) {}
  11131. /**
  11132. * Handle `mouseup` or `touchend` events on the `Slider`.
  11133. *
  11134. * @param {EventTarget~Event} event
  11135. * `mouseup` or `touchend` event that triggered this function.
  11136. *
  11137. * @listens touchend
  11138. * @listens mouseup
  11139. * @fires Slider#sliderinactive
  11140. */
  11141. ;
  11142. _proto.handleMouseUp = function handleMouseUp() {
  11143. var doc = this.bar.el_.ownerDocument;
  11144. unblockTextSelection();
  11145. this.removeClass('vjs-sliding');
  11146. /**
  11147. * Triggered when the slider is no longer in an active state.
  11148. *
  11149. * @event Slider#sliderinactive
  11150. * @type {EventTarget~Event}
  11151. */
  11152. this.trigger('sliderinactive');
  11153. this.off(doc, 'mousemove', this.handleMouseMove_);
  11154. this.off(doc, 'mouseup', this.handleMouseUp_);
  11155. this.off(doc, 'touchmove', this.handleMouseMove_);
  11156. this.off(doc, 'touchend', this.handleMouseUp_);
  11157. this.update();
  11158. }
  11159. /**
  11160. * Update the progress bar of the `Slider`.
  11161. *
  11162. * @return {number}
  11163. * The percentage of progress the progress bar represents as a
  11164. * number from 0 to 1.
  11165. */
  11166. ;
  11167. _proto.update = function update() {
  11168. var _this2 = this;
  11169. // In VolumeBar init we have a setTimeout for update that pops and update
  11170. // to the end of the execution stack. The player is destroyed before then
  11171. // update will cause an error
  11172. // If there's no bar...
  11173. if (!this.el_ || !this.bar) {
  11174. return;
  11175. } // clamp progress between 0 and 1
  11176. // and only round to four decimal places, as we round to two below
  11177. var progress = this.getProgress();
  11178. if (progress === this.progress_) {
  11179. return progress;
  11180. }
  11181. this.progress_ = progress;
  11182. this.requestNamedAnimationFrame('Slider#update', function () {
  11183. // Set the new bar width or height
  11184. var sizeKey = _this2.vertical() ? 'height' : 'width'; // Convert to a percentage for css value
  11185. _this2.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  11186. });
  11187. return progress;
  11188. }
  11189. /**
  11190. * Get the percentage of the bar that should be filled
  11191. * but clamped and rounded.
  11192. *
  11193. * @return {number}
  11194. * percentage filled that the slider is
  11195. */
  11196. ;
  11197. _proto.getProgress = function getProgress() {
  11198. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  11199. }
  11200. /**
  11201. * Calculate distance for slider
  11202. *
  11203. * @param {EventTarget~Event} event
  11204. * The event that caused this function to run.
  11205. *
  11206. * @return {number}
  11207. * The current position of the Slider.
  11208. * - position.x for vertical `Slider`s
  11209. * - position.y for horizontal `Slider`s
  11210. */
  11211. ;
  11212. _proto.calculateDistance = function calculateDistance(event) {
  11213. var position = getPointerPosition(this.el_, event);
  11214. if (this.vertical()) {
  11215. return position.y;
  11216. }
  11217. return position.x;
  11218. }
  11219. /**
  11220. * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down
  11221. * arrow keys. This function will only be called when the slider has focus. See
  11222. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  11223. *
  11224. * @param {EventTarget~Event} event
  11225. * the `keydown` event that caused this function to run.
  11226. *
  11227. * @listens keydown
  11228. */
  11229. ;
  11230. _proto.handleKeyDown = function handleKeyDown(event) {
  11231. // Left and Down Arrows
  11232. if (keycode__default['default'].isEventKey(event, 'Left') || keycode__default['default'].isEventKey(event, 'Down')) {
  11233. event.preventDefault();
  11234. event.stopPropagation();
  11235. this.stepBack(); // Up and Right Arrows
  11236. } else if (keycode__default['default'].isEventKey(event, 'Right') || keycode__default['default'].isEventKey(event, 'Up')) {
  11237. event.preventDefault();
  11238. event.stopPropagation();
  11239. this.stepForward();
  11240. } else {
  11241. // Pass keydown handling up for unsupported keys
  11242. _Component.prototype.handleKeyDown.call(this, event);
  11243. }
  11244. }
  11245. /**
  11246. * Listener for click events on slider, used to prevent clicks
  11247. * from bubbling up to parent elements like button menus.
  11248. *
  11249. * @param {Object} event
  11250. * Event that caused this object to run
  11251. */
  11252. ;
  11253. _proto.handleClick = function handleClick(event) {
  11254. event.stopPropagation();
  11255. event.preventDefault();
  11256. }
  11257. /**
  11258. * Get/set if slider is horizontal for vertical
  11259. *
  11260. * @param {boolean} [bool]
  11261. * - true if slider is vertical,
  11262. * - false is horizontal
  11263. *
  11264. * @return {boolean}
  11265. * - true if slider is vertical, and getting
  11266. * - false if the slider is horizontal, and getting
  11267. */
  11268. ;
  11269. _proto.vertical = function vertical(bool) {
  11270. if (bool === undefined) {
  11271. return this.vertical_ || false;
  11272. }
  11273. this.vertical_ = !!bool;
  11274. if (this.vertical_) {
  11275. this.addClass('vjs-slider-vertical');
  11276. } else {
  11277. this.addClass('vjs-slider-horizontal');
  11278. }
  11279. };
  11280. return Slider;
  11281. }(Component$1);
  11282. Component$1.registerComponent('Slider', Slider);
  11283. var percentify = function percentify(time, end) {
  11284. return clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  11285. };
  11286. /**
  11287. * Shows loading progress
  11288. *
  11289. * @extends Component
  11290. */
  11291. var LoadProgressBar = /*#__PURE__*/function (_Component) {
  11292. _inheritsLoose__default['default'](LoadProgressBar, _Component);
  11293. /**
  11294. * Creates an instance of this class.
  11295. *
  11296. * @param {Player} player
  11297. * The `Player` that this class should be attached to.
  11298. *
  11299. * @param {Object} [options]
  11300. * The key/value store of player options.
  11301. */
  11302. function LoadProgressBar(player, options) {
  11303. var _this;
  11304. _this = _Component.call(this, player, options) || this;
  11305. _this.partEls_ = [];
  11306. _this.on(player, 'progress', function (e) {
  11307. return _this.update(e);
  11308. });
  11309. return _this;
  11310. }
  11311. /**
  11312. * Create the `Component`'s DOM element
  11313. *
  11314. * @return {Element}
  11315. * The element that was created.
  11316. */
  11317. var _proto = LoadProgressBar.prototype;
  11318. _proto.createEl = function createEl$1() {
  11319. var el = _Component.prototype.createEl.call(this, 'div', {
  11320. className: 'vjs-load-progress'
  11321. });
  11322. var wrapper = createEl('span', {
  11323. className: 'vjs-control-text'
  11324. });
  11325. var loadedText = createEl('span', {
  11326. textContent: this.localize('Loaded')
  11327. });
  11328. var separator = document__default['default'].createTextNode(': ');
  11329. this.percentageEl_ = createEl('span', {
  11330. className: 'vjs-control-text-loaded-percentage',
  11331. textContent: '0%'
  11332. });
  11333. el.appendChild(wrapper);
  11334. wrapper.appendChild(loadedText);
  11335. wrapper.appendChild(separator);
  11336. wrapper.appendChild(this.percentageEl_);
  11337. return el;
  11338. };
  11339. _proto.dispose = function dispose() {
  11340. this.partEls_ = null;
  11341. this.percentageEl_ = null;
  11342. _Component.prototype.dispose.call(this);
  11343. }
  11344. /**
  11345. * Update progress bar
  11346. *
  11347. * @param {EventTarget~Event} [event]
  11348. * The `progress` event that caused this function to run.
  11349. *
  11350. * @listens Player#progress
  11351. */
  11352. ;
  11353. _proto.update = function update(event) {
  11354. var _this2 = this;
  11355. this.requestNamedAnimationFrame('LoadProgressBar#update', function () {
  11356. var liveTracker = _this2.player_.liveTracker;
  11357. var buffered = _this2.player_.buffered();
  11358. var duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : _this2.player_.duration();
  11359. var bufferedEnd = _this2.player_.bufferedEnd();
  11360. var children = _this2.partEls_;
  11361. var percent = percentify(bufferedEnd, duration);
  11362. if (_this2.percent_ !== percent) {
  11363. // update the width of the progress bar
  11364. _this2.el_.style.width = percent; // update the control-text
  11365. textContent(_this2.percentageEl_, percent);
  11366. _this2.percent_ = percent;
  11367. } // add child elements to represent the individual buffered time ranges
  11368. for (var i = 0; i < buffered.length; i++) {
  11369. var start = buffered.start(i);
  11370. var end = buffered.end(i);
  11371. var part = children[i];
  11372. if (!part) {
  11373. part = _this2.el_.appendChild(createEl());
  11374. children[i] = part;
  11375. } // only update if changed
  11376. if (part.dataset.start === start && part.dataset.end === end) {
  11377. continue;
  11378. }
  11379. part.dataset.start = start;
  11380. part.dataset.end = end; // set the percent based on the width of the progress bar (bufferedEnd)
  11381. part.style.left = percentify(start, bufferedEnd);
  11382. part.style.width = percentify(end - start, bufferedEnd);
  11383. } // remove unused buffered range elements
  11384. for (var _i = children.length; _i > buffered.length; _i--) {
  11385. _this2.el_.removeChild(children[_i - 1]);
  11386. }
  11387. children.length = buffered.length;
  11388. });
  11389. };
  11390. return LoadProgressBar;
  11391. }(Component$1);
  11392. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  11393. /**
  11394. * Time tooltips display a time above the progress bar.
  11395. *
  11396. * @extends Component
  11397. */
  11398. var TimeTooltip = /*#__PURE__*/function (_Component) {
  11399. _inheritsLoose__default['default'](TimeTooltip, _Component);
  11400. /**
  11401. * Creates an instance of this class.
  11402. *
  11403. * @param {Player} player
  11404. * The {@link Player} that this class should be attached to.
  11405. *
  11406. * @param {Object} [options]
  11407. * The key/value store of player options.
  11408. */
  11409. function TimeTooltip(player, options) {
  11410. var _this;
  11411. _this = _Component.call(this, player, options) || this;
  11412. _this.update = throttle(bind(_assertThisInitialized__default['default'](_this), _this.update), UPDATE_REFRESH_INTERVAL);
  11413. return _this;
  11414. }
  11415. /**
  11416. * Create the time tooltip DOM element
  11417. *
  11418. * @return {Element}
  11419. * The element that was created.
  11420. */
  11421. var _proto = TimeTooltip.prototype;
  11422. _proto.createEl = function createEl() {
  11423. return _Component.prototype.createEl.call(this, 'div', {
  11424. className: 'vjs-time-tooltip'
  11425. }, {
  11426. 'aria-hidden': 'true'
  11427. });
  11428. }
  11429. /**
  11430. * Updates the position of the time tooltip relative to the `SeekBar`.
  11431. *
  11432. * @param {Object} seekBarRect
  11433. * The `ClientRect` for the {@link SeekBar} element.
  11434. *
  11435. * @param {number} seekBarPoint
  11436. * A number from 0 to 1, representing a horizontal reference point
  11437. * from the left edge of the {@link SeekBar}
  11438. */
  11439. ;
  11440. _proto.update = function update(seekBarRect, seekBarPoint, content) {
  11441. var tooltipRect = findPosition(this.el_);
  11442. var playerRect = getBoundingClientRect(this.player_.el());
  11443. var seekBarPointPx = seekBarRect.width * seekBarPoint; // do nothing if either rect isn't available
  11444. // for example, if the player isn't in the DOM for testing
  11445. if (!playerRect || !tooltipRect) {
  11446. return;
  11447. } // This is the space left of the `seekBarPoint` available within the bounds
  11448. // of the player. We calculate any gap between the left edge of the player
  11449. // and the left edge of the `SeekBar` and add the number of pixels in the
  11450. // `SeekBar` before hitting the `seekBarPoint`
  11451. var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx; // This is the space right of the `seekBarPoint` available within the bounds
  11452. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11453. // to the right edge of the `SeekBar` and add to that any gap between the
  11454. // right edge of the `SeekBar` and the player.
  11455. var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right); // This is the number of pixels by which the tooltip will need to be pulled
  11456. // further to the right to center it over the `seekBarPoint`.
  11457. var pullTooltipBy = tooltipRect.width / 2; // Adjust the `pullTooltipBy` distance to the left or right depending on
  11458. // the results of the space calculations above.
  11459. if (spaceLeftOfPoint < pullTooltipBy) {
  11460. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11461. } else if (spaceRightOfPoint < pullTooltipBy) {
  11462. pullTooltipBy = spaceRightOfPoint;
  11463. } // Due to the imprecision of decimal/ratio based calculations and varying
  11464. // rounding behaviors, there are cases where the spacing adjustment is off
  11465. // by a pixel or two. This adds insurance to these calculations.
  11466. if (pullTooltipBy < 0) {
  11467. pullTooltipBy = 0;
  11468. } else if (pullTooltipBy > tooltipRect.width) {
  11469. pullTooltipBy = tooltipRect.width;
  11470. } // prevent small width fluctuations within 0.4px from
  11471. // changing the value below.
  11472. // This really helps for live to prevent the play
  11473. // progress time tooltip from jittering
  11474. pullTooltipBy = Math.round(pullTooltipBy);
  11475. this.el_.style.right = "-" + pullTooltipBy + "px";
  11476. this.write(content);
  11477. }
  11478. /**
  11479. * Write the time to the tooltip DOM element.
  11480. *
  11481. * @param {string} content
  11482. * The formatted time for the tooltip.
  11483. */
  11484. ;
  11485. _proto.write = function write(content) {
  11486. textContent(this.el_, content);
  11487. }
  11488. /**
  11489. * Updates the position of the time tooltip relative to the `SeekBar`.
  11490. *
  11491. * @param {Object} seekBarRect
  11492. * The `ClientRect` for the {@link SeekBar} element.
  11493. *
  11494. * @param {number} seekBarPoint
  11495. * A number from 0 to 1, representing a horizontal reference point
  11496. * from the left edge of the {@link SeekBar}
  11497. *
  11498. * @param {number} time
  11499. * The time to update the tooltip to, not used during live playback
  11500. *
  11501. * @param {Function} cb
  11502. * A function that will be called during the request animation frame
  11503. * for tooltips that need to do additional animations from the default
  11504. */
  11505. ;
  11506. _proto.updateTime = function updateTime(seekBarRect, seekBarPoint, time, cb) {
  11507. var _this2 = this;
  11508. this.requestNamedAnimationFrame('TimeTooltip#updateTime', function () {
  11509. var content;
  11510. var duration = _this2.player_.duration();
  11511. if (_this2.player_.liveTracker && _this2.player_.liveTracker.isLive()) {
  11512. var liveWindow = _this2.player_.liveTracker.liveWindow();
  11513. var secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11514. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11515. } else {
  11516. content = formatTime(time, duration);
  11517. }
  11518. _this2.update(seekBarRect, seekBarPoint, content);
  11519. if (cb) {
  11520. cb();
  11521. }
  11522. });
  11523. };
  11524. return TimeTooltip;
  11525. }(Component$1);
  11526. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  11527. /**
  11528. * Used by {@link SeekBar} to display media playback progress as part of the
  11529. * {@link ProgressControl}.
  11530. *
  11531. * @extends Component
  11532. */
  11533. var PlayProgressBar = /*#__PURE__*/function (_Component) {
  11534. _inheritsLoose__default['default'](PlayProgressBar, _Component);
  11535. /**
  11536. * Creates an instance of this class.
  11537. *
  11538. * @param {Player} player
  11539. * The {@link Player} that this class should be attached to.
  11540. *
  11541. * @param {Object} [options]
  11542. * The key/value store of player options.
  11543. */
  11544. function PlayProgressBar(player, options) {
  11545. var _this;
  11546. _this = _Component.call(this, player, options) || this;
  11547. _this.update = throttle(bind(_assertThisInitialized__default['default'](_this), _this.update), UPDATE_REFRESH_INTERVAL);
  11548. return _this;
  11549. }
  11550. /**
  11551. * Create the the DOM element for this class.
  11552. *
  11553. * @return {Element}
  11554. * The element that was created.
  11555. */
  11556. var _proto = PlayProgressBar.prototype;
  11557. _proto.createEl = function createEl() {
  11558. return _Component.prototype.createEl.call(this, 'div', {
  11559. className: 'vjs-play-progress vjs-slider-bar'
  11560. }, {
  11561. 'aria-hidden': 'true'
  11562. });
  11563. }
  11564. /**
  11565. * Enqueues updates to its own DOM as well as the DOM of its
  11566. * {@link TimeTooltip} child.
  11567. *
  11568. * @param {Object} seekBarRect
  11569. * The `ClientRect` for the {@link SeekBar} element.
  11570. *
  11571. * @param {number} seekBarPoint
  11572. * A number from 0 to 1, representing a horizontal reference point
  11573. * from the left edge of the {@link SeekBar}
  11574. */
  11575. ;
  11576. _proto.update = function update(seekBarRect, seekBarPoint) {
  11577. var timeTooltip = this.getChild('timeTooltip');
  11578. if (!timeTooltip) {
  11579. return;
  11580. }
  11581. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11582. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  11583. };
  11584. return PlayProgressBar;
  11585. }(Component$1);
  11586. /**
  11587. * Default options for {@link PlayProgressBar}.
  11588. *
  11589. * @type {Object}
  11590. * @private
  11591. */
  11592. PlayProgressBar.prototype.options_ = {
  11593. children: []
  11594. }; // Time tooltips should not be added to a player on mobile devices
  11595. if (!IS_IOS && !IS_ANDROID) {
  11596. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  11597. }
  11598. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  11599. /**
  11600. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  11601. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  11602. * indicating the time which is represented by a given point in the
  11603. * {@link ProgressControl}.
  11604. *
  11605. * @extends Component
  11606. */
  11607. var MouseTimeDisplay = /*#__PURE__*/function (_Component) {
  11608. _inheritsLoose__default['default'](MouseTimeDisplay, _Component);
  11609. /**
  11610. * Creates an instance of this class.
  11611. *
  11612. * @param {Player} player
  11613. * The {@link Player} that this class should be attached to.
  11614. *
  11615. * @param {Object} [options]
  11616. * The key/value store of player options.
  11617. */
  11618. function MouseTimeDisplay(player, options) {
  11619. var _this;
  11620. _this = _Component.call(this, player, options) || this;
  11621. _this.update = throttle(bind(_assertThisInitialized__default['default'](_this), _this.update), UPDATE_REFRESH_INTERVAL);
  11622. return _this;
  11623. }
  11624. /**
  11625. * Create the DOM element for this class.
  11626. *
  11627. * @return {Element}
  11628. * The element that was created.
  11629. */
  11630. var _proto = MouseTimeDisplay.prototype;
  11631. _proto.createEl = function createEl() {
  11632. return _Component.prototype.createEl.call(this, 'div', {
  11633. className: 'vjs-mouse-display'
  11634. });
  11635. }
  11636. /**
  11637. * Enqueues updates to its own DOM as well as the DOM of its
  11638. * {@link TimeTooltip} child.
  11639. *
  11640. * @param {Object} seekBarRect
  11641. * The `ClientRect` for the {@link SeekBar} element.
  11642. *
  11643. * @param {number} seekBarPoint
  11644. * A number from 0 to 1, representing a horizontal reference point
  11645. * from the left edge of the {@link SeekBar}
  11646. */
  11647. ;
  11648. _proto.update = function update(seekBarRect, seekBarPoint) {
  11649. var _this2 = this;
  11650. var time = seekBarPoint * this.player_.duration();
  11651. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, function () {
  11652. _this2.el_.style.left = seekBarRect.width * seekBarPoint + "px";
  11653. });
  11654. };
  11655. return MouseTimeDisplay;
  11656. }(Component$1);
  11657. /**
  11658. * Default options for `MouseTimeDisplay`
  11659. *
  11660. * @type {Object}
  11661. * @private
  11662. */
  11663. MouseTimeDisplay.prototype.options_ = {
  11664. children: ['timeTooltip']
  11665. };
  11666. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  11667. var STEP_SECONDS = 5; // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  11668. var PAGE_KEY_MULTIPLIER = 12;
  11669. /**
  11670. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  11671. * as its `bar`.
  11672. *
  11673. * @extends Slider
  11674. */
  11675. var SeekBar = /*#__PURE__*/function (_Slider) {
  11676. _inheritsLoose__default['default'](SeekBar, _Slider);
  11677. /**
  11678. * Creates an instance of this class.
  11679. *
  11680. * @param {Player} player
  11681. * The `Player` that this class should be attached to.
  11682. *
  11683. * @param {Object} [options]
  11684. * The key/value store of player options.
  11685. */
  11686. function SeekBar(player, options) {
  11687. var _this;
  11688. _this = _Slider.call(this, player, options) || this;
  11689. _this.setEventHandlers_();
  11690. return _this;
  11691. }
  11692. /**
  11693. * Sets the event handlers
  11694. *
  11695. * @private
  11696. */
  11697. var _proto = SeekBar.prototype;
  11698. _proto.setEventHandlers_ = function setEventHandlers_() {
  11699. var _this2 = this;
  11700. this.update_ = bind(this, this.update);
  11701. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  11702. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  11703. if (this.player_.liveTracker) {
  11704. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  11705. } // when playing, let's ensure we smoothly update the play progress bar
  11706. // via an interval
  11707. this.updateInterval = null;
  11708. this.enableIntervalHandler_ = function (e) {
  11709. return _this2.enableInterval_(e);
  11710. };
  11711. this.disableIntervalHandler_ = function (e) {
  11712. return _this2.disableInterval_(e);
  11713. };
  11714. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  11715. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  11716. // also, this causes the CPU to spike and eventually crash the page on IE11.
  11717. if ('hidden' in document__default['default'] && 'visibilityState' in document__default['default']) {
  11718. this.on(document__default['default'], 'visibilitychange', this.toggleVisibility_);
  11719. }
  11720. };
  11721. _proto.toggleVisibility_ = function toggleVisibility_(e) {
  11722. if (document__default['default'].visibilityState === 'hidden') {
  11723. this.cancelNamedAnimationFrame('SeekBar#update');
  11724. this.cancelNamedAnimationFrame('Slider#update');
  11725. this.disableInterval_(e);
  11726. } else {
  11727. if (!this.player_.ended() && !this.player_.paused()) {
  11728. this.enableInterval_();
  11729. } // we just switched back to the page and someone may be looking, so, update ASAP
  11730. this.update();
  11731. }
  11732. };
  11733. _proto.enableInterval_ = function enableInterval_() {
  11734. if (this.updateInterval) {
  11735. return;
  11736. }
  11737. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  11738. };
  11739. _proto.disableInterval_ = function disableInterval_(e) {
  11740. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  11741. return;
  11742. }
  11743. if (!this.updateInterval) {
  11744. return;
  11745. }
  11746. this.clearInterval(this.updateInterval);
  11747. this.updateInterval = null;
  11748. }
  11749. /**
  11750. * Create the `Component`'s DOM element
  11751. *
  11752. * @return {Element}
  11753. * The element that was created.
  11754. */
  11755. ;
  11756. _proto.createEl = function createEl() {
  11757. return _Slider.prototype.createEl.call(this, 'div', {
  11758. className: 'vjs-progress-holder'
  11759. }, {
  11760. 'aria-label': this.localize('Progress Bar')
  11761. });
  11762. }
  11763. /**
  11764. * This function updates the play progress bar and accessibility
  11765. * attributes to whatever is passed in.
  11766. *
  11767. * @param {EventTarget~Event} [event]
  11768. * The `timeupdate` or `ended` event that caused this to run.
  11769. *
  11770. * @listens Player#timeupdate
  11771. *
  11772. * @return {number}
  11773. * The current percent at a number from 0-1
  11774. */
  11775. ;
  11776. _proto.update = function update(event) {
  11777. var _this3 = this;
  11778. // ignore updates while the tab is hidden
  11779. if (document__default['default'].visibilityState === 'hidden') {
  11780. return;
  11781. }
  11782. var percent = _Slider.prototype.update.call(this);
  11783. this.requestNamedAnimationFrame('SeekBar#update', function () {
  11784. var currentTime = _this3.player_.ended() ? _this3.player_.duration() : _this3.getCurrentTime_();
  11785. var liveTracker = _this3.player_.liveTracker;
  11786. var duration = _this3.player_.duration();
  11787. if (liveTracker && liveTracker.isLive()) {
  11788. duration = _this3.player_.liveTracker.liveCurrentTime();
  11789. }
  11790. if (_this3.percent_ !== percent) {
  11791. // machine readable value of progress bar (percentage complete)
  11792. _this3.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  11793. _this3.percent_ = percent;
  11794. }
  11795. if (_this3.currentTime_ !== currentTime || _this3.duration_ !== duration) {
  11796. // human readable value of progress bar (time complete)
  11797. _this3.el_.setAttribute('aria-valuetext', _this3.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  11798. _this3.currentTime_ = currentTime;
  11799. _this3.duration_ = duration;
  11800. } // update the progress bar time tooltip with the current time
  11801. if (_this3.bar) {
  11802. _this3.bar.update(getBoundingClientRect(_this3.el()), _this3.getProgress());
  11803. }
  11804. });
  11805. return percent;
  11806. }
  11807. /**
  11808. * Prevent liveThreshold from causing seeks to seem like they
  11809. * are not happening from a user perspective.
  11810. *
  11811. * @param {number} ct
  11812. * current time to seek to
  11813. */
  11814. ;
  11815. _proto.userSeek_ = function userSeek_(ct) {
  11816. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  11817. this.player_.liveTracker.nextSeekedFromUser();
  11818. }
  11819. this.player_.currentTime(ct);
  11820. }
  11821. /**
  11822. * Get the value of current time but allows for smooth scrubbing,
  11823. * when player can't keep up.
  11824. *
  11825. * @return {number}
  11826. * The current time value to display
  11827. *
  11828. * @private
  11829. */
  11830. ;
  11831. _proto.getCurrentTime_ = function getCurrentTime_() {
  11832. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11833. }
  11834. /**
  11835. * Get the percentage of media played so far.
  11836. *
  11837. * @return {number}
  11838. * The percentage of media played so far (0 to 1).
  11839. */
  11840. ;
  11841. _proto.getPercent = function getPercent() {
  11842. var currentTime = this.getCurrentTime_();
  11843. var percent;
  11844. var liveTracker = this.player_.liveTracker;
  11845. if (liveTracker && liveTracker.isLive()) {
  11846. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow(); // prevent the percent from changing at the live edge
  11847. if (liveTracker.atLiveEdge()) {
  11848. percent = 1;
  11849. }
  11850. } else {
  11851. percent = currentTime / this.player_.duration();
  11852. }
  11853. return percent;
  11854. }
  11855. /**
  11856. * Handle mouse down on seek bar
  11857. *
  11858. * @param {EventTarget~Event} event
  11859. * The `mousedown` event that caused this to run.
  11860. *
  11861. * @listens mousedown
  11862. */
  11863. ;
  11864. _proto.handleMouseDown = function handleMouseDown(event) {
  11865. if (!isSingleLeftClick(event)) {
  11866. return;
  11867. } // Stop event propagation to prevent double fire in progress-control.js
  11868. event.stopPropagation();
  11869. this.videoWasPlaying = !this.player_.paused();
  11870. this.player_.pause();
  11871. _Slider.prototype.handleMouseDown.call(this, event);
  11872. }
  11873. /**
  11874. * Handle mouse move on seek bar
  11875. *
  11876. * @param {EventTarget~Event} event
  11877. * The `mousemove` event that caused this to run.
  11878. * @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
  11879. *
  11880. * @listens mousemove
  11881. */
  11882. ;
  11883. _proto.handleMouseMove = function handleMouseMove(event, mouseDown) {
  11884. if (mouseDown === void 0) {
  11885. mouseDown = false;
  11886. }
  11887. if (!isSingleLeftClick(event)) {
  11888. return;
  11889. }
  11890. if (!mouseDown && !this.player_.scrubbing()) {
  11891. this.player_.scrubbing(true);
  11892. }
  11893. var newTime;
  11894. var distance = this.calculateDistance(event);
  11895. var liveTracker = this.player_.liveTracker;
  11896. if (!liveTracker || !liveTracker.isLive()) {
  11897. newTime = distance * this.player_.duration(); // Don't let video end while scrubbing.
  11898. if (newTime === this.player_.duration()) {
  11899. newTime = newTime - 0.1;
  11900. }
  11901. } else {
  11902. if (distance >= 0.99) {
  11903. liveTracker.seekToLiveEdge();
  11904. return;
  11905. }
  11906. var seekableStart = liveTracker.seekableStart();
  11907. var seekableEnd = liveTracker.liveCurrentTime();
  11908. newTime = seekableStart + distance * liveTracker.liveWindow(); // Don't let video end while scrubbing.
  11909. if (newTime >= seekableEnd) {
  11910. newTime = seekableEnd;
  11911. } // Compensate for precision differences so that currentTime is not less
  11912. // than seekable start
  11913. if (newTime <= seekableStart) {
  11914. newTime = seekableStart + 0.1;
  11915. } // On android seekableEnd can be Infinity sometimes,
  11916. // this will cause newTime to be Infinity, which is
  11917. // not a valid currentTime.
  11918. if (newTime === Infinity) {
  11919. return;
  11920. }
  11921. } // Set new time (tell player to seek to new time)
  11922. this.userSeek_(newTime);
  11923. };
  11924. _proto.enable = function enable() {
  11925. _Slider.prototype.enable.call(this);
  11926. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11927. if (!mouseTimeDisplay) {
  11928. return;
  11929. }
  11930. mouseTimeDisplay.show();
  11931. };
  11932. _proto.disable = function disable() {
  11933. _Slider.prototype.disable.call(this);
  11934. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  11935. if (!mouseTimeDisplay) {
  11936. return;
  11937. }
  11938. mouseTimeDisplay.hide();
  11939. }
  11940. /**
  11941. * Handle mouse up on seek bar
  11942. *
  11943. * @param {EventTarget~Event} event
  11944. * The `mouseup` event that caused this to run.
  11945. *
  11946. * @listens mouseup
  11947. */
  11948. ;
  11949. _proto.handleMouseUp = function handleMouseUp(event) {
  11950. _Slider.prototype.handleMouseUp.call(this, event); // Stop event propagation to prevent double fire in progress-control.js
  11951. if (event) {
  11952. event.stopPropagation();
  11953. }
  11954. this.player_.scrubbing(false);
  11955. /**
  11956. * Trigger timeupdate because we're done seeking and the time has changed.
  11957. * This is particularly useful for if the player is paused to time the time displays.
  11958. *
  11959. * @event Tech#timeupdate
  11960. * @type {EventTarget~Event}
  11961. */
  11962. this.player_.trigger({
  11963. type: 'timeupdate',
  11964. target: this,
  11965. manuallyTriggered: true
  11966. });
  11967. if (this.videoWasPlaying) {
  11968. silencePromise(this.player_.play());
  11969. } else {
  11970. // We're done seeking and the time has changed.
  11971. // If the player is paused, make sure we display the correct time on the seek bar.
  11972. this.update_();
  11973. }
  11974. }
  11975. /**
  11976. * Move more quickly fast forward for keyboard-only users
  11977. */
  11978. ;
  11979. _proto.stepForward = function stepForward() {
  11980. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  11981. }
  11982. /**
  11983. * Move more quickly rewind for keyboard-only users
  11984. */
  11985. ;
  11986. _proto.stepBack = function stepBack() {
  11987. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  11988. }
  11989. /**
  11990. * Toggles the playback state of the player
  11991. * This gets called when enter or space is used on the seekbar
  11992. *
  11993. * @param {EventTarget~Event} event
  11994. * The `keydown` event that caused this function to be called
  11995. *
  11996. */
  11997. ;
  11998. _proto.handleAction = function handleAction(event) {
  11999. if (this.player_.paused()) {
  12000. this.player_.play();
  12001. } else {
  12002. this.player_.pause();
  12003. }
  12004. }
  12005. /**
  12006. * Called when this SeekBar has focus and a key gets pressed down.
  12007. * Supports the following keys:
  12008. *
  12009. * Space or Enter key fire a click event
  12010. * Home key moves to start of the timeline
  12011. * End key moves to end of the timeline
  12012. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  12013. * PageDown key moves back a larger step than ArrowDown
  12014. * PageUp key moves forward a large step
  12015. *
  12016. * @param {EventTarget~Event} event
  12017. * The `keydown` event that caused this function to be called.
  12018. *
  12019. * @listens keydown
  12020. */
  12021. ;
  12022. _proto.handleKeyDown = function handleKeyDown(event) {
  12023. var liveTracker = this.player_.liveTracker;
  12024. if (keycode__default['default'].isEventKey(event, 'Space') || keycode__default['default'].isEventKey(event, 'Enter')) {
  12025. event.preventDefault();
  12026. event.stopPropagation();
  12027. this.handleAction(event);
  12028. } else if (keycode__default['default'].isEventKey(event, 'Home')) {
  12029. event.preventDefault();
  12030. event.stopPropagation();
  12031. this.userSeek_(0);
  12032. } else if (keycode__default['default'].isEventKey(event, 'End')) {
  12033. event.preventDefault();
  12034. event.stopPropagation();
  12035. if (liveTracker && liveTracker.isLive()) {
  12036. this.userSeek_(liveTracker.liveCurrentTime());
  12037. } else {
  12038. this.userSeek_(this.player_.duration());
  12039. }
  12040. } else if (/^[0-9]$/.test(keycode__default['default'](event))) {
  12041. event.preventDefault();
  12042. event.stopPropagation();
  12043. var gotoFraction = (keycode__default['default'].codes[keycode__default['default'](event)] - keycode__default['default'].codes['0']) * 10.0 / 100.0;
  12044. if (liveTracker && liveTracker.isLive()) {
  12045. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  12046. } else {
  12047. this.userSeek_(this.player_.duration() * gotoFraction);
  12048. }
  12049. } else if (keycode__default['default'].isEventKey(event, 'PgDn')) {
  12050. event.preventDefault();
  12051. event.stopPropagation();
  12052. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12053. } else if (keycode__default['default'].isEventKey(event, 'PgUp')) {
  12054. event.preventDefault();
  12055. event.stopPropagation();
  12056. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12057. } else {
  12058. // Pass keydown handling up for unsupported keys
  12059. _Slider.prototype.handleKeyDown.call(this, event);
  12060. }
  12061. };
  12062. _proto.dispose = function dispose() {
  12063. this.disableInterval_();
  12064. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  12065. if (this.player_.liveTracker) {
  12066. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  12067. }
  12068. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  12069. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  12070. // also, this causes the CPU to spike and eventually crash the page on IE11.
  12071. if ('hidden' in document__default['default'] && 'visibilityState' in document__default['default']) {
  12072. this.off(document__default['default'], 'visibilitychange', this.toggleVisibility_);
  12073. }
  12074. _Slider.prototype.dispose.call(this);
  12075. };
  12076. return SeekBar;
  12077. }(Slider);
  12078. /**
  12079. * Default options for the `SeekBar`
  12080. *
  12081. * @type {Object}
  12082. * @private
  12083. */
  12084. SeekBar.prototype.options_ = {
  12085. children: ['loadProgressBar', 'playProgressBar'],
  12086. barName: 'playProgressBar'
  12087. }; // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  12088. if (!IS_IOS && !IS_ANDROID) {
  12089. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  12090. }
  12091. Component$1.registerComponent('SeekBar', SeekBar);
  12092. /**
  12093. * The Progress Control component contains the seek bar, load progress,
  12094. * and play progress.
  12095. *
  12096. * @extends Component
  12097. */
  12098. var ProgressControl = /*#__PURE__*/function (_Component) {
  12099. _inheritsLoose__default['default'](ProgressControl, _Component);
  12100. /**
  12101. * Creates an instance of this class.
  12102. *
  12103. * @param {Player} player
  12104. * The `Player` that this class should be attached to.
  12105. *
  12106. * @param {Object} [options]
  12107. * The key/value store of player options.
  12108. */
  12109. function ProgressControl(player, options) {
  12110. var _this;
  12111. _this = _Component.call(this, player, options) || this;
  12112. _this.handleMouseMove = throttle(bind(_assertThisInitialized__default['default'](_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12113. _this.throttledHandleMouseSeek = throttle(bind(_assertThisInitialized__default['default'](_this), _this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  12114. _this.handleMouseUpHandler_ = function (e) {
  12115. return _this.handleMouseUp(e);
  12116. };
  12117. _this.handleMouseDownHandler_ = function (e) {
  12118. return _this.handleMouseDown(e);
  12119. };
  12120. _this.enable();
  12121. return _this;
  12122. }
  12123. /**
  12124. * Create the `Component`'s DOM element
  12125. *
  12126. * @return {Element}
  12127. * The element that was created.
  12128. */
  12129. var _proto = ProgressControl.prototype;
  12130. _proto.createEl = function createEl() {
  12131. return _Component.prototype.createEl.call(this, 'div', {
  12132. className: 'vjs-progress-control vjs-control'
  12133. });
  12134. }
  12135. /**
  12136. * When the mouse moves over the `ProgressControl`, the pointer position
  12137. * gets passed down to the `MouseTimeDisplay` component.
  12138. *
  12139. * @param {EventTarget~Event} event
  12140. * The `mousemove` event that caused this function to run.
  12141. *
  12142. * @listen mousemove
  12143. */
  12144. ;
  12145. _proto.handleMouseMove = function handleMouseMove(event) {
  12146. var seekBar = this.getChild('seekBar');
  12147. if (!seekBar) {
  12148. return;
  12149. }
  12150. var playProgressBar = seekBar.getChild('playProgressBar');
  12151. var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  12152. if (!playProgressBar && !mouseTimeDisplay) {
  12153. return;
  12154. }
  12155. var seekBarEl = seekBar.el();
  12156. var seekBarRect = findPosition(seekBarEl);
  12157. var seekBarPoint = getPointerPosition(seekBarEl, event).x; // The default skin has a gap on either side of the `SeekBar`. This means
  12158. // that it's possible to trigger this behavior outside the boundaries of
  12159. // the `SeekBar`. This ensures we stay within it at all times.
  12160. seekBarPoint = clamp(seekBarPoint, 0, 1);
  12161. if (mouseTimeDisplay) {
  12162. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  12163. }
  12164. if (playProgressBar) {
  12165. playProgressBar.update(seekBarRect, seekBar.getProgress());
  12166. }
  12167. }
  12168. /**
  12169. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  12170. *
  12171. * @method ProgressControl#throttledHandleMouseSeek
  12172. * @param {EventTarget~Event} event
  12173. * The `mousemove` event that caused this function to run.
  12174. *
  12175. * @listen mousemove
  12176. * @listen touchmove
  12177. */
  12178. /**
  12179. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  12180. *
  12181. * @param {EventTarget~Event} event
  12182. * `mousedown` or `touchstart` event that triggered this function
  12183. *
  12184. * @listens mousemove
  12185. * @listens touchmove
  12186. */
  12187. ;
  12188. _proto.handleMouseSeek = function handleMouseSeek(event) {
  12189. var seekBar = this.getChild('seekBar');
  12190. if (seekBar) {
  12191. seekBar.handleMouseMove(event);
  12192. }
  12193. }
  12194. /**
  12195. * Are controls are currently enabled for this progress control.
  12196. *
  12197. * @return {boolean}
  12198. * true if controls are enabled, false otherwise
  12199. */
  12200. ;
  12201. _proto.enabled = function enabled() {
  12202. return this.enabled_;
  12203. }
  12204. /**
  12205. * Disable all controls on the progress control and its children
  12206. */
  12207. ;
  12208. _proto.disable = function disable() {
  12209. this.children().forEach(function (child) {
  12210. return child.disable && child.disable();
  12211. });
  12212. if (!this.enabled()) {
  12213. return;
  12214. }
  12215. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12216. this.off(this.el_, 'mousemove', this.handleMouseMove);
  12217. this.removeListenersAddedOnMousedownAndTouchstart();
  12218. this.addClass('disabled');
  12219. this.enabled_ = false; // Restore normal playback state if controls are disabled while scrubbing
  12220. if (this.player_.scrubbing()) {
  12221. var seekBar = this.getChild('seekBar');
  12222. this.player_.scrubbing(false);
  12223. if (seekBar.videoWasPlaying) {
  12224. silencePromise(this.player_.play());
  12225. }
  12226. }
  12227. }
  12228. /**
  12229. * Enable all controls on the progress control and its children
  12230. */
  12231. ;
  12232. _proto.enable = function enable() {
  12233. this.children().forEach(function (child) {
  12234. return child.enable && child.enable();
  12235. });
  12236. if (this.enabled()) {
  12237. return;
  12238. }
  12239. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12240. this.on(this.el_, 'mousemove', this.handleMouseMove);
  12241. this.removeClass('disabled');
  12242. this.enabled_ = true;
  12243. }
  12244. /**
  12245. * Cleanup listeners after the user finishes interacting with the progress controls
  12246. */
  12247. ;
  12248. _proto.removeListenersAddedOnMousedownAndTouchstart = function removeListenersAddedOnMousedownAndTouchstart() {
  12249. var doc = this.el_.ownerDocument;
  12250. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  12251. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  12252. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12253. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12254. }
  12255. /**
  12256. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  12257. *
  12258. * @param {EventTarget~Event} event
  12259. * `mousedown` or `touchstart` event that triggered this function
  12260. *
  12261. * @listens mousedown
  12262. * @listens touchstart
  12263. */
  12264. ;
  12265. _proto.handleMouseDown = function handleMouseDown(event) {
  12266. var doc = this.el_.ownerDocument;
  12267. var seekBar = this.getChild('seekBar');
  12268. if (seekBar) {
  12269. seekBar.handleMouseDown(event);
  12270. }
  12271. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  12272. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  12273. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12274. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12275. }
  12276. /**
  12277. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  12278. *
  12279. * @param {EventTarget~Event} event
  12280. * `mouseup` or `touchend` event that triggered this function.
  12281. *
  12282. * @listens touchend
  12283. * @listens mouseup
  12284. */
  12285. ;
  12286. _proto.handleMouseUp = function handleMouseUp(event) {
  12287. var seekBar = this.getChild('seekBar');
  12288. if (seekBar) {
  12289. seekBar.handleMouseUp(event);
  12290. }
  12291. this.removeListenersAddedOnMousedownAndTouchstart();
  12292. };
  12293. return ProgressControl;
  12294. }(Component$1);
  12295. /**
  12296. * Default options for `ProgressControl`
  12297. *
  12298. * @type {Object}
  12299. * @private
  12300. */
  12301. ProgressControl.prototype.options_ = {
  12302. children: ['seekBar']
  12303. };
  12304. Component$1.registerComponent('ProgressControl', ProgressControl);
  12305. /**
  12306. * Toggle Picture-in-Picture mode
  12307. *
  12308. * @extends Button
  12309. */
  12310. var PictureInPictureToggle = /*#__PURE__*/function (_Button) {
  12311. _inheritsLoose__default['default'](PictureInPictureToggle, _Button);
  12312. /**
  12313. * Creates an instance of this class.
  12314. *
  12315. * @param {Player} player
  12316. * The `Player` that this class should be attached to.
  12317. *
  12318. * @param {Object} [options]
  12319. * The key/value store of player options.
  12320. *
  12321. * @listens Player#enterpictureinpicture
  12322. * @listens Player#leavepictureinpicture
  12323. */
  12324. function PictureInPictureToggle(player, options) {
  12325. var _this;
  12326. _this = _Button.call(this, player, options) || this;
  12327. _this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], function (e) {
  12328. return _this.handlePictureInPictureChange(e);
  12329. });
  12330. _this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], function (e) {
  12331. return _this.handlePictureInPictureEnabledChange(e);
  12332. });
  12333. _this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], function () {
  12334. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  12335. var isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  12336. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  12337. if (player.isInPictureInPicture()) {
  12338. player.exitPictureInPicture();
  12339. }
  12340. _this.hide();
  12341. } else {
  12342. _this.show();
  12343. }
  12344. }); // TODO: Deactivate button on player emptied event.
  12345. _this.disable();
  12346. return _this;
  12347. }
  12348. /**
  12349. * Builds the default DOM `className`.
  12350. *
  12351. * @return {string}
  12352. * The DOM `className` for this object.
  12353. */
  12354. var _proto = PictureInPictureToggle.prototype;
  12355. _proto.buildCSSClass = function buildCSSClass() {
  12356. return "vjs-picture-in-picture-control " + _Button.prototype.buildCSSClass.call(this);
  12357. }
  12358. /**
  12359. * Enables or disables button based on document.pictureInPictureEnabled property value
  12360. * or on value returned by player.disablePictureInPicture() method.
  12361. */
  12362. ;
  12363. _proto.handlePictureInPictureEnabledChange = function handlePictureInPictureEnabledChange() {
  12364. if (document__default['default'].pictureInPictureEnabled && this.player_.disablePictureInPicture() === false) {
  12365. this.enable();
  12366. } else {
  12367. this.disable();
  12368. }
  12369. }
  12370. /**
  12371. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12372. *
  12373. * @param {EventTarget~Event} [event]
  12374. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12375. * called.
  12376. *
  12377. * @listens Player#enterpictureinpicture
  12378. * @listens Player#leavepictureinpicture
  12379. */
  12380. ;
  12381. _proto.handlePictureInPictureChange = function handlePictureInPictureChange(event) {
  12382. if (this.player_.isInPictureInPicture()) {
  12383. this.controlText('Exit Picture-in-Picture');
  12384. } else {
  12385. this.controlText('Picture-in-Picture');
  12386. }
  12387. this.handlePictureInPictureEnabledChange();
  12388. }
  12389. /**
  12390. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12391. * {@link ClickableComponent} for more detailed information on what a click can be.
  12392. *
  12393. * @param {EventTarget~Event} [event]
  12394. * The `keydown`, `tap`, or `click` event that caused this function to be
  12395. * called.
  12396. *
  12397. * @listens tap
  12398. * @listens click
  12399. */
  12400. ;
  12401. _proto.handleClick = function handleClick(event) {
  12402. if (!this.player_.isInPictureInPicture()) {
  12403. this.player_.requestPictureInPicture();
  12404. } else {
  12405. this.player_.exitPictureInPicture();
  12406. }
  12407. };
  12408. return PictureInPictureToggle;
  12409. }(Button);
  12410. /**
  12411. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12412. *
  12413. * @type {string}
  12414. * @private
  12415. */
  12416. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12417. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12418. /**
  12419. * Toggle fullscreen video
  12420. *
  12421. * @extends Button
  12422. */
  12423. var FullscreenToggle = /*#__PURE__*/function (_Button) {
  12424. _inheritsLoose__default['default'](FullscreenToggle, _Button);
  12425. /**
  12426. * Creates an instance of this class.
  12427. *
  12428. * @param {Player} player
  12429. * The `Player` that this class should be attached to.
  12430. *
  12431. * @param {Object} [options]
  12432. * The key/value store of player options.
  12433. */
  12434. function FullscreenToggle(player, options) {
  12435. var _this;
  12436. _this = _Button.call(this, player, options) || this;
  12437. _this.on(player, 'fullscreenchange', function (e) {
  12438. return _this.handleFullscreenChange(e);
  12439. });
  12440. if (document__default['default'][player.fsApi_.fullscreenEnabled] === false) {
  12441. _this.disable();
  12442. }
  12443. return _this;
  12444. }
  12445. /**
  12446. * Builds the default DOM `className`.
  12447. *
  12448. * @return {string}
  12449. * The DOM `className` for this object.
  12450. */
  12451. var _proto = FullscreenToggle.prototype;
  12452. _proto.buildCSSClass = function buildCSSClass() {
  12453. return "vjs-fullscreen-control " + _Button.prototype.buildCSSClass.call(this);
  12454. }
  12455. /**
  12456. * Handles fullscreenchange on the player and change control text accordingly.
  12457. *
  12458. * @param {EventTarget~Event} [event]
  12459. * The {@link Player#fullscreenchange} event that caused this function to be
  12460. * called.
  12461. *
  12462. * @listens Player#fullscreenchange
  12463. */
  12464. ;
  12465. _proto.handleFullscreenChange = function handleFullscreenChange(event) {
  12466. if (this.player_.isFullscreen()) {
  12467. this.controlText('Non-Fullscreen');
  12468. } else {
  12469. this.controlText('Fullscreen');
  12470. }
  12471. }
  12472. /**
  12473. * This gets called when an `FullscreenToggle` is "clicked". See
  12474. * {@link ClickableComponent} for more detailed information on what a click can be.
  12475. *
  12476. * @param {EventTarget~Event} [event]
  12477. * The `keydown`, `tap`, or `click` event that caused this function to be
  12478. * called.
  12479. *
  12480. * @listens tap
  12481. * @listens click
  12482. */
  12483. ;
  12484. _proto.handleClick = function handleClick(event) {
  12485. if (!this.player_.isFullscreen()) {
  12486. this.player_.requestFullscreen();
  12487. } else {
  12488. this.player_.exitFullscreen();
  12489. }
  12490. };
  12491. return FullscreenToggle;
  12492. }(Button);
  12493. /**
  12494. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12495. *
  12496. * @type {string}
  12497. * @private
  12498. */
  12499. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12500. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  12501. /**
  12502. * Check if volume control is supported and if it isn't hide the
  12503. * `Component` that was passed using the `vjs-hidden` class.
  12504. *
  12505. * @param {Component} self
  12506. * The component that should be hidden if volume is unsupported
  12507. *
  12508. * @param {Player} player
  12509. * A reference to the player
  12510. *
  12511. * @private
  12512. */
  12513. var checkVolumeSupport = function checkVolumeSupport(self, player) {
  12514. // hide volume controls when they're not supported by the current tech
  12515. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12516. self.addClass('vjs-hidden');
  12517. }
  12518. self.on(player, 'loadstart', function () {
  12519. if (!player.tech_.featuresVolumeControl) {
  12520. self.addClass('vjs-hidden');
  12521. } else {
  12522. self.removeClass('vjs-hidden');
  12523. }
  12524. });
  12525. };
  12526. /**
  12527. * Shows volume level
  12528. *
  12529. * @extends Component
  12530. */
  12531. var VolumeLevel = /*#__PURE__*/function (_Component) {
  12532. _inheritsLoose__default['default'](VolumeLevel, _Component);
  12533. function VolumeLevel() {
  12534. return _Component.apply(this, arguments) || this;
  12535. }
  12536. var _proto = VolumeLevel.prototype;
  12537. /**
  12538. * Create the `Component`'s DOM element
  12539. *
  12540. * @return {Element}
  12541. * The element that was created.
  12542. */
  12543. _proto.createEl = function createEl() {
  12544. var el = _Component.prototype.createEl.call(this, 'div', {
  12545. className: 'vjs-volume-level'
  12546. });
  12547. el.appendChild(_Component.prototype.createEl.call(this, 'span', {
  12548. className: 'vjs-control-text'
  12549. }));
  12550. return el;
  12551. };
  12552. return VolumeLevel;
  12553. }(Component$1);
  12554. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  12555. /**
  12556. * Volume level tooltips display a volume above or side by side the volume bar.
  12557. *
  12558. * @extends Component
  12559. */
  12560. var VolumeLevelTooltip = /*#__PURE__*/function (_Component) {
  12561. _inheritsLoose__default['default'](VolumeLevelTooltip, _Component);
  12562. /**
  12563. * Creates an instance of this class.
  12564. *
  12565. * @param {Player} player
  12566. * The {@link Player} that this class should be attached to.
  12567. *
  12568. * @param {Object} [options]
  12569. * The key/value store of player options.
  12570. */
  12571. function VolumeLevelTooltip(player, options) {
  12572. var _this;
  12573. _this = _Component.call(this, player, options) || this;
  12574. _this.update = throttle(bind(_assertThisInitialized__default['default'](_this), _this.update), UPDATE_REFRESH_INTERVAL);
  12575. return _this;
  12576. }
  12577. /**
  12578. * Create the volume tooltip DOM element
  12579. *
  12580. * @return {Element}
  12581. * The element that was created.
  12582. */
  12583. var _proto = VolumeLevelTooltip.prototype;
  12584. _proto.createEl = function createEl() {
  12585. return _Component.prototype.createEl.call(this, 'div', {
  12586. className: 'vjs-volume-tooltip'
  12587. }, {
  12588. 'aria-hidden': 'true'
  12589. });
  12590. }
  12591. /**
  12592. * Updates the position of the tooltip relative to the `VolumeBar` and
  12593. * its content text.
  12594. *
  12595. * @param {Object} rangeBarRect
  12596. * The `ClientRect` for the {@link VolumeBar} element.
  12597. *
  12598. * @param {number} rangeBarPoint
  12599. * A number from 0 to 1, representing a horizontal/vertical reference point
  12600. * from the left edge of the {@link VolumeBar}
  12601. *
  12602. * @param {boolean} vertical
  12603. * Referees to the Volume control position
  12604. * in the control bar{@link VolumeControl}
  12605. *
  12606. */
  12607. ;
  12608. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical, content) {
  12609. if (!vertical) {
  12610. var tooltipRect = getBoundingClientRect(this.el_);
  12611. var playerRect = getBoundingClientRect(this.player_.el());
  12612. var volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  12613. if (!playerRect || !tooltipRect) {
  12614. return;
  12615. }
  12616. var spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  12617. var spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  12618. var pullTooltipBy = tooltipRect.width / 2;
  12619. if (spaceLeftOfPoint < pullTooltipBy) {
  12620. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  12621. } else if (spaceRightOfPoint < pullTooltipBy) {
  12622. pullTooltipBy = spaceRightOfPoint;
  12623. }
  12624. if (pullTooltipBy < 0) {
  12625. pullTooltipBy = 0;
  12626. } else if (pullTooltipBy > tooltipRect.width) {
  12627. pullTooltipBy = tooltipRect.width;
  12628. }
  12629. this.el_.style.right = "-" + pullTooltipBy + "px";
  12630. }
  12631. this.write(content + "%");
  12632. }
  12633. /**
  12634. * Write the volume to the tooltip DOM element.
  12635. *
  12636. * @param {string} content
  12637. * The formatted volume for the tooltip.
  12638. */
  12639. ;
  12640. _proto.write = function write(content) {
  12641. textContent(this.el_, content);
  12642. }
  12643. /**
  12644. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  12645. *
  12646. * @param {Object} rangeBarRect
  12647. * The `ClientRect` for the {@link VolumeBar} element.
  12648. *
  12649. * @param {number} rangeBarPoint
  12650. * A number from 0 to 1, representing a horizontal/vertical reference point
  12651. * from the left edge of the {@link VolumeBar}
  12652. *
  12653. * @param {boolean} vertical
  12654. * Referees to the Volume control position
  12655. * in the control bar{@link VolumeControl}
  12656. *
  12657. * @param {number} volume
  12658. * The volume level to update the tooltip to
  12659. *
  12660. * @param {Function} cb
  12661. * A function that will be called during the request animation frame
  12662. * for tooltips that need to do additional animations from the default
  12663. */
  12664. ;
  12665. _proto.updateVolume = function updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  12666. var _this2 = this;
  12667. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', function () {
  12668. _this2.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  12669. if (cb) {
  12670. cb();
  12671. }
  12672. });
  12673. };
  12674. return VolumeLevelTooltip;
  12675. }(Component$1);
  12676. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  12677. /**
  12678. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  12679. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  12680. * indicating the volume level which is represented by a given point in the
  12681. * {@link VolumeBar}.
  12682. *
  12683. * @extends Component
  12684. */
  12685. var MouseVolumeLevelDisplay = /*#__PURE__*/function (_Component) {
  12686. _inheritsLoose__default['default'](MouseVolumeLevelDisplay, _Component);
  12687. /**
  12688. * Creates an instance of this class.
  12689. *
  12690. * @param {Player} player
  12691. * The {@link Player} that this class should be attached to.
  12692. *
  12693. * @param {Object} [options]
  12694. * The key/value store of player options.
  12695. */
  12696. function MouseVolumeLevelDisplay(player, options) {
  12697. var _this;
  12698. _this = _Component.call(this, player, options) || this;
  12699. _this.update = throttle(bind(_assertThisInitialized__default['default'](_this), _this.update), UPDATE_REFRESH_INTERVAL);
  12700. return _this;
  12701. }
  12702. /**
  12703. * Create the DOM element for this class.
  12704. *
  12705. * @return {Element}
  12706. * The element that was created.
  12707. */
  12708. var _proto = MouseVolumeLevelDisplay.prototype;
  12709. _proto.createEl = function createEl() {
  12710. return _Component.prototype.createEl.call(this, 'div', {
  12711. className: 'vjs-mouse-display'
  12712. });
  12713. }
  12714. /**
  12715. * Enquires updates to its own DOM as well as the DOM of its
  12716. * {@link VolumeLevelTooltip} child.
  12717. *
  12718. * @param {Object} rangeBarRect
  12719. * The `ClientRect` for the {@link VolumeBar} element.
  12720. *
  12721. * @param {number} rangeBarPoint
  12722. * A number from 0 to 1, representing a horizontal/vertical reference point
  12723. * from the left edge of the {@link VolumeBar}
  12724. *
  12725. * @param {boolean} vertical
  12726. * Referees to the Volume control position
  12727. * in the control bar{@link VolumeControl}
  12728. *
  12729. */
  12730. ;
  12731. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical) {
  12732. var _this2 = this;
  12733. var volume = 100 * rangeBarPoint;
  12734. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, function () {
  12735. if (vertical) {
  12736. _this2.el_.style.bottom = rangeBarRect.height * rangeBarPoint + "px";
  12737. } else {
  12738. _this2.el_.style.left = rangeBarRect.width * rangeBarPoint + "px";
  12739. }
  12740. });
  12741. };
  12742. return MouseVolumeLevelDisplay;
  12743. }(Component$1);
  12744. /**
  12745. * Default options for `MouseVolumeLevelDisplay`
  12746. *
  12747. * @type {Object}
  12748. * @private
  12749. */
  12750. MouseVolumeLevelDisplay.prototype.options_ = {
  12751. children: ['volumeLevelTooltip']
  12752. };
  12753. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  12754. /**
  12755. * The bar that contains the volume level and can be clicked on to adjust the level
  12756. *
  12757. * @extends Slider
  12758. */
  12759. var VolumeBar = /*#__PURE__*/function (_Slider) {
  12760. _inheritsLoose__default['default'](VolumeBar, _Slider);
  12761. /**
  12762. * Creates an instance of this class.
  12763. *
  12764. * @param {Player} player
  12765. * The `Player` that this class should be attached to.
  12766. *
  12767. * @param {Object} [options]
  12768. * The key/value store of player options.
  12769. */
  12770. function VolumeBar(player, options) {
  12771. var _this;
  12772. _this = _Slider.call(this, player, options) || this;
  12773. _this.on('slideractive', function (e) {
  12774. return _this.updateLastVolume_(e);
  12775. });
  12776. _this.on(player, 'volumechange', function (e) {
  12777. return _this.updateARIAAttributes(e);
  12778. });
  12779. player.ready(function () {
  12780. return _this.updateARIAAttributes();
  12781. });
  12782. return _this;
  12783. }
  12784. /**
  12785. * Create the `Component`'s DOM element
  12786. *
  12787. * @return {Element}
  12788. * The element that was created.
  12789. */
  12790. var _proto = VolumeBar.prototype;
  12791. _proto.createEl = function createEl() {
  12792. return _Slider.prototype.createEl.call(this, 'div', {
  12793. className: 'vjs-volume-bar vjs-slider-bar'
  12794. }, {
  12795. 'aria-label': this.localize('Volume Level'),
  12796. 'aria-live': 'polite'
  12797. });
  12798. }
  12799. /**
  12800. * Handle mouse down on volume bar
  12801. *
  12802. * @param {EventTarget~Event} event
  12803. * The `mousedown` event that caused this to run.
  12804. *
  12805. * @listens mousedown
  12806. */
  12807. ;
  12808. _proto.handleMouseDown = function handleMouseDown(event) {
  12809. if (!isSingleLeftClick(event)) {
  12810. return;
  12811. }
  12812. _Slider.prototype.handleMouseDown.call(this, event);
  12813. }
  12814. /**
  12815. * Handle movement events on the {@link VolumeMenuButton}.
  12816. *
  12817. * @param {EventTarget~Event} event
  12818. * The event that caused this function to run.
  12819. *
  12820. * @listens mousemove
  12821. */
  12822. ;
  12823. _proto.handleMouseMove = function handleMouseMove(event) {
  12824. var mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  12825. if (mouseVolumeLevelDisplay) {
  12826. var volumeBarEl = this.el();
  12827. var volumeBarRect = getBoundingClientRect(volumeBarEl);
  12828. var vertical = this.vertical();
  12829. var volumeBarPoint = getPointerPosition(volumeBarEl, event);
  12830. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x; // The default skin has a gap on either side of the `VolumeBar`. This means
  12831. // that it's possible to trigger this behavior outside the boundaries of
  12832. // the `VolumeBar`. This ensures we stay within it at all times.
  12833. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  12834. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  12835. }
  12836. if (!isSingleLeftClick(event)) {
  12837. return;
  12838. }
  12839. this.checkMuted();
  12840. this.player_.volume(this.calculateDistance(event));
  12841. }
  12842. /**
  12843. * If the player is muted unmute it.
  12844. */
  12845. ;
  12846. _proto.checkMuted = function checkMuted() {
  12847. if (this.player_.muted()) {
  12848. this.player_.muted(false);
  12849. }
  12850. }
  12851. /**
  12852. * Get percent of volume level
  12853. *
  12854. * @return {number}
  12855. * Volume level percent as a decimal number.
  12856. */
  12857. ;
  12858. _proto.getPercent = function getPercent() {
  12859. if (this.player_.muted()) {
  12860. return 0;
  12861. }
  12862. return this.player_.volume();
  12863. }
  12864. /**
  12865. * Increase volume level for keyboard users
  12866. */
  12867. ;
  12868. _proto.stepForward = function stepForward() {
  12869. this.checkMuted();
  12870. this.player_.volume(this.player_.volume() + 0.1);
  12871. }
  12872. /**
  12873. * Decrease volume level for keyboard users
  12874. */
  12875. ;
  12876. _proto.stepBack = function stepBack() {
  12877. this.checkMuted();
  12878. this.player_.volume(this.player_.volume() - 0.1);
  12879. }
  12880. /**
  12881. * Update ARIA accessibility attributes
  12882. *
  12883. * @param {EventTarget~Event} [event]
  12884. * The `volumechange` event that caused this function to run.
  12885. *
  12886. * @listens Player#volumechange
  12887. */
  12888. ;
  12889. _proto.updateARIAAttributes = function updateARIAAttributes(event) {
  12890. var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  12891. this.el_.setAttribute('aria-valuenow', ariaValue);
  12892. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  12893. }
  12894. /**
  12895. * Returns the current value of the player volume as a percentage
  12896. *
  12897. * @private
  12898. */
  12899. ;
  12900. _proto.volumeAsPercentage_ = function volumeAsPercentage_() {
  12901. return Math.round(this.player_.volume() * 100);
  12902. }
  12903. /**
  12904. * When user starts dragging the VolumeBar, store the volume and listen for
  12905. * the end of the drag. When the drag ends, if the volume was set to zero,
  12906. * set lastVolume to the stored volume.
  12907. *
  12908. * @listens slideractive
  12909. * @private
  12910. */
  12911. ;
  12912. _proto.updateLastVolume_ = function updateLastVolume_() {
  12913. var _this2 = this;
  12914. var volumeBeforeDrag = this.player_.volume();
  12915. this.one('sliderinactive', function () {
  12916. if (_this2.player_.volume() === 0) {
  12917. _this2.player_.lastVolume_(volumeBeforeDrag);
  12918. }
  12919. });
  12920. };
  12921. return VolumeBar;
  12922. }(Slider);
  12923. /**
  12924. * Default options for the `VolumeBar`
  12925. *
  12926. * @type {Object}
  12927. * @private
  12928. */
  12929. VolumeBar.prototype.options_ = {
  12930. children: ['volumeLevel'],
  12931. barName: 'volumeLevel'
  12932. }; // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  12933. if (!IS_IOS && !IS_ANDROID) {
  12934. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  12935. }
  12936. /**
  12937. * Call the update event for this Slider when this event happens on the player.
  12938. *
  12939. * @type {string}
  12940. */
  12941. VolumeBar.prototype.playerEvent = 'volumechange';
  12942. Component$1.registerComponent('VolumeBar', VolumeBar);
  12943. /**
  12944. * The component for controlling the volume level
  12945. *
  12946. * @extends Component
  12947. */
  12948. var VolumeControl = /*#__PURE__*/function (_Component) {
  12949. _inheritsLoose__default['default'](VolumeControl, _Component);
  12950. /**
  12951. * Creates an instance of this class.
  12952. *
  12953. * @param {Player} player
  12954. * The `Player` that this class should be attached to.
  12955. *
  12956. * @param {Object} [options={}]
  12957. * The key/value store of player options.
  12958. */
  12959. function VolumeControl(player, options) {
  12960. var _this;
  12961. if (options === void 0) {
  12962. options = {};
  12963. }
  12964. options.vertical = options.vertical || false; // Pass the vertical option down to the VolumeBar if
  12965. // the VolumeBar is turned on.
  12966. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  12967. options.volumeBar = options.volumeBar || {};
  12968. options.volumeBar.vertical = options.vertical;
  12969. }
  12970. _this = _Component.call(this, player, options) || this; // hide this control if volume support is missing
  12971. checkVolumeSupport(_assertThisInitialized__default['default'](_this), player);
  12972. _this.throttledHandleMouseMove = throttle(bind(_assertThisInitialized__default['default'](_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12973. _this.handleMouseUpHandler_ = function (e) {
  12974. return _this.handleMouseUp(e);
  12975. };
  12976. _this.on('mousedown', function (e) {
  12977. return _this.handleMouseDown(e);
  12978. });
  12979. _this.on('touchstart', function (e) {
  12980. return _this.handleMouseDown(e);
  12981. });
  12982. _this.on('mousemove', function (e) {
  12983. return _this.handleMouseMove(e);
  12984. }); // while the slider is active (the mouse has been pressed down and
  12985. // is dragging) or in focus we do not want to hide the VolumeBar
  12986. _this.on(_this.volumeBar, ['focus', 'slideractive'], function () {
  12987. _this.volumeBar.addClass('vjs-slider-active');
  12988. _this.addClass('vjs-slider-active');
  12989. _this.trigger('slideractive');
  12990. });
  12991. _this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () {
  12992. _this.volumeBar.removeClass('vjs-slider-active');
  12993. _this.removeClass('vjs-slider-active');
  12994. _this.trigger('sliderinactive');
  12995. });
  12996. return _this;
  12997. }
  12998. /**
  12999. * Create the `Component`'s DOM element
  13000. *
  13001. * @return {Element}
  13002. * The element that was created.
  13003. */
  13004. var _proto = VolumeControl.prototype;
  13005. _proto.createEl = function createEl() {
  13006. var orientationClass = 'vjs-volume-horizontal';
  13007. if (this.options_.vertical) {
  13008. orientationClass = 'vjs-volume-vertical';
  13009. }
  13010. return _Component.prototype.createEl.call(this, 'div', {
  13011. className: "vjs-volume-control vjs-control " + orientationClass
  13012. });
  13013. }
  13014. /**
  13015. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13016. *
  13017. * @param {EventTarget~Event} event
  13018. * `mousedown` or `touchstart` event that triggered this function
  13019. *
  13020. * @listens mousedown
  13021. * @listens touchstart
  13022. */
  13023. ;
  13024. _proto.handleMouseDown = function handleMouseDown(event) {
  13025. var doc = this.el_.ownerDocument;
  13026. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  13027. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  13028. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  13029. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  13030. }
  13031. /**
  13032. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  13033. *
  13034. * @param {EventTarget~Event} event
  13035. * `mouseup` or `touchend` event that triggered this function.
  13036. *
  13037. * @listens touchend
  13038. * @listens mouseup
  13039. */
  13040. ;
  13041. _proto.handleMouseUp = function handleMouseUp(event) {
  13042. var doc = this.el_.ownerDocument;
  13043. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  13044. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  13045. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  13046. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  13047. }
  13048. /**
  13049. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13050. *
  13051. * @param {EventTarget~Event} event
  13052. * `mousedown` or `touchstart` event that triggered this function
  13053. *
  13054. * @listens mousedown
  13055. * @listens touchstart
  13056. */
  13057. ;
  13058. _proto.handleMouseMove = function handleMouseMove(event) {
  13059. this.volumeBar.handleMouseMove(event);
  13060. };
  13061. return VolumeControl;
  13062. }(Component$1);
  13063. /**
  13064. * Default options for the `VolumeControl`
  13065. *
  13066. * @type {Object}
  13067. * @private
  13068. */
  13069. VolumeControl.prototype.options_ = {
  13070. children: ['volumeBar']
  13071. };
  13072. Component$1.registerComponent('VolumeControl', VolumeControl);
  13073. /**
  13074. * Check if muting volume is supported and if it isn't hide the mute toggle
  13075. * button.
  13076. *
  13077. * @param {Component} self
  13078. * A reference to the mute toggle button
  13079. *
  13080. * @param {Player} player
  13081. * A reference to the player
  13082. *
  13083. * @private
  13084. */
  13085. var checkMuteSupport = function checkMuteSupport(self, player) {
  13086. // hide mute toggle button if it's not supported by the current tech
  13087. if (player.tech_ && !player.tech_.featuresMuteControl) {
  13088. self.addClass('vjs-hidden');
  13089. }
  13090. self.on(player, 'loadstart', function () {
  13091. if (!player.tech_.featuresMuteControl) {
  13092. self.addClass('vjs-hidden');
  13093. } else {
  13094. self.removeClass('vjs-hidden');
  13095. }
  13096. });
  13097. };
  13098. /**
  13099. * A button component for muting the audio.
  13100. *
  13101. * @extends Button
  13102. */
  13103. var MuteToggle = /*#__PURE__*/function (_Button) {
  13104. _inheritsLoose__default['default'](MuteToggle, _Button);
  13105. /**
  13106. * Creates an instance of this class.
  13107. *
  13108. * @param {Player} player
  13109. * The `Player` that this class should be attached to.
  13110. *
  13111. * @param {Object} [options]
  13112. * The key/value store of player options.
  13113. */
  13114. function MuteToggle(player, options) {
  13115. var _this;
  13116. _this = _Button.call(this, player, options) || this; // hide this control if volume support is missing
  13117. checkMuteSupport(_assertThisInitialized__default['default'](_this), player);
  13118. _this.on(player, ['loadstart', 'volumechange'], function (e) {
  13119. return _this.update(e);
  13120. });
  13121. return _this;
  13122. }
  13123. /**
  13124. * Builds the default DOM `className`.
  13125. *
  13126. * @return {string}
  13127. * The DOM `className` for this object.
  13128. */
  13129. var _proto = MuteToggle.prototype;
  13130. _proto.buildCSSClass = function buildCSSClass() {
  13131. return "vjs-mute-control " + _Button.prototype.buildCSSClass.call(this);
  13132. }
  13133. /**
  13134. * This gets called when an `MuteToggle` is "clicked". See
  13135. * {@link ClickableComponent} for more detailed information on what a click can be.
  13136. *
  13137. * @param {EventTarget~Event} [event]
  13138. * The `keydown`, `tap`, or `click` event that caused this function to be
  13139. * called.
  13140. *
  13141. * @listens tap
  13142. * @listens click
  13143. */
  13144. ;
  13145. _proto.handleClick = function handleClick(event) {
  13146. var vol = this.player_.volume();
  13147. var lastVolume = this.player_.lastVolume_();
  13148. if (vol === 0) {
  13149. var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  13150. this.player_.volume(volumeToSet);
  13151. this.player_.muted(false);
  13152. } else {
  13153. this.player_.muted(this.player_.muted() ? false : true);
  13154. }
  13155. }
  13156. /**
  13157. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  13158. * on the player.
  13159. *
  13160. * @param {EventTarget~Event} [event]
  13161. * The {@link Player#loadstart} event if this function was called
  13162. * through an event.
  13163. *
  13164. * @listens Player#loadstart
  13165. * @listens Player#volumechange
  13166. */
  13167. ;
  13168. _proto.update = function update(event) {
  13169. this.updateIcon_();
  13170. this.updateControlText_();
  13171. }
  13172. /**
  13173. * Update the appearance of the `MuteToggle` icon.
  13174. *
  13175. * Possible states (given `level` variable below):
  13176. * - 0: crossed out
  13177. * - 1: zero bars of volume
  13178. * - 2: one bar of volume
  13179. * - 3: two bars of volume
  13180. *
  13181. * @private
  13182. */
  13183. ;
  13184. _proto.updateIcon_ = function updateIcon_() {
  13185. var vol = this.player_.volume();
  13186. var level = 3; // in iOS when a player is loaded with muted attribute
  13187. // and volume is changed with a native mute button
  13188. // we want to make sure muted state is updated
  13189. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  13190. this.player_.muted(this.player_.tech_.el_.muted);
  13191. }
  13192. if (vol === 0 || this.player_.muted()) {
  13193. level = 0;
  13194. } else if (vol < 0.33) {
  13195. level = 1;
  13196. } else if (vol < 0.67) {
  13197. level = 2;
  13198. } // TODO improve muted icon classes
  13199. for (var i = 0; i < 4; i++) {
  13200. removeClass(this.el_, "vjs-vol-" + i);
  13201. }
  13202. addClass(this.el_, "vjs-vol-" + level);
  13203. }
  13204. /**
  13205. * If `muted` has changed on the player, update the control text
  13206. * (`title` attribute on `vjs-mute-control` element and content of
  13207. * `vjs-control-text` element).
  13208. *
  13209. * @private
  13210. */
  13211. ;
  13212. _proto.updateControlText_ = function updateControlText_() {
  13213. var soundOff = this.player_.muted() || this.player_.volume() === 0;
  13214. var text = soundOff ? 'Unmute' : 'Mute';
  13215. if (this.controlText() !== text) {
  13216. this.controlText(text);
  13217. }
  13218. };
  13219. return MuteToggle;
  13220. }(Button);
  13221. /**
  13222. * The text that should display over the `MuteToggle`s controls. Added for localization.
  13223. *
  13224. * @type {string}
  13225. * @private
  13226. */
  13227. MuteToggle.prototype.controlText_ = 'Mute';
  13228. Component$1.registerComponent('MuteToggle', MuteToggle);
  13229. /**
  13230. * A Component to contain the MuteToggle and VolumeControl so that
  13231. * they can work together.
  13232. *
  13233. * @extends Component
  13234. */
  13235. var VolumePanel = /*#__PURE__*/function (_Component) {
  13236. _inheritsLoose__default['default'](VolumePanel, _Component);
  13237. /**
  13238. * Creates an instance of this class.
  13239. *
  13240. * @param {Player} player
  13241. * The `Player` that this class should be attached to.
  13242. *
  13243. * @param {Object} [options={}]
  13244. * The key/value store of player options.
  13245. */
  13246. function VolumePanel(player, options) {
  13247. var _this;
  13248. if (options === void 0) {
  13249. options = {};
  13250. }
  13251. if (typeof options.inline !== 'undefined') {
  13252. options.inline = options.inline;
  13253. } else {
  13254. options.inline = true;
  13255. } // pass the inline option down to the VolumeControl as vertical if
  13256. // the VolumeControl is on.
  13257. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  13258. options.volumeControl = options.volumeControl || {};
  13259. options.volumeControl.vertical = !options.inline;
  13260. }
  13261. _this = _Component.call(this, player, options) || this; // this handler is used by mouse handler methods below
  13262. _this.handleKeyPressHandler_ = function (e) {
  13263. return _this.handleKeyPress(e);
  13264. };
  13265. _this.on(player, ['loadstart'], function (e) {
  13266. return _this.volumePanelState_(e);
  13267. });
  13268. _this.on(_this.muteToggle, 'keyup', function (e) {
  13269. return _this.handleKeyPress(e);
  13270. });
  13271. _this.on(_this.volumeControl, 'keyup', function (e) {
  13272. return _this.handleVolumeControlKeyUp(e);
  13273. });
  13274. _this.on('keydown', function (e) {
  13275. return _this.handleKeyPress(e);
  13276. });
  13277. _this.on('mouseover', function (e) {
  13278. return _this.handleMouseOver(e);
  13279. });
  13280. _this.on('mouseout', function (e) {
  13281. return _this.handleMouseOut(e);
  13282. }); // while the slider is active (the mouse has been pressed down and
  13283. // is dragging) we do not want to hide the VolumeBar
  13284. _this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_);
  13285. _this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_);
  13286. return _this;
  13287. }
  13288. /**
  13289. * Add vjs-slider-active class to the VolumePanel
  13290. *
  13291. * @listens VolumeControl#slideractive
  13292. * @private
  13293. */
  13294. var _proto = VolumePanel.prototype;
  13295. _proto.sliderActive_ = function sliderActive_() {
  13296. this.addClass('vjs-slider-active');
  13297. }
  13298. /**
  13299. * Removes vjs-slider-active class to the VolumePanel
  13300. *
  13301. * @listens VolumeControl#sliderinactive
  13302. * @private
  13303. */
  13304. ;
  13305. _proto.sliderInactive_ = function sliderInactive_() {
  13306. this.removeClass('vjs-slider-active');
  13307. }
  13308. /**
  13309. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  13310. * depending on MuteToggle and VolumeControl state
  13311. *
  13312. * @listens Player#loadstart
  13313. * @private
  13314. */
  13315. ;
  13316. _proto.volumePanelState_ = function volumePanelState_() {
  13317. // hide volume panel if neither volume control or mute toggle
  13318. // are displayed
  13319. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  13320. this.addClass('vjs-hidden');
  13321. } // if only mute toggle is visible we don't want
  13322. // volume panel expanding when hovered or active
  13323. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  13324. this.addClass('vjs-mute-toggle-only');
  13325. }
  13326. }
  13327. /**
  13328. * Create the `Component`'s DOM element
  13329. *
  13330. * @return {Element}
  13331. * The element that was created.
  13332. */
  13333. ;
  13334. _proto.createEl = function createEl() {
  13335. var orientationClass = 'vjs-volume-panel-horizontal';
  13336. if (!this.options_.inline) {
  13337. orientationClass = 'vjs-volume-panel-vertical';
  13338. }
  13339. return _Component.prototype.createEl.call(this, 'div', {
  13340. className: "vjs-volume-panel vjs-control " + orientationClass
  13341. });
  13342. }
  13343. /**
  13344. * Dispose of the `volume-panel` and all child components.
  13345. */
  13346. ;
  13347. _proto.dispose = function dispose() {
  13348. this.handleMouseOut();
  13349. _Component.prototype.dispose.call(this);
  13350. }
  13351. /**
  13352. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  13353. * the volume panel and sets focus on `MuteToggle`.
  13354. *
  13355. * @param {EventTarget~Event} event
  13356. * The `keyup` event that caused this function to be called.
  13357. *
  13358. * @listens keyup
  13359. */
  13360. ;
  13361. _proto.handleVolumeControlKeyUp = function handleVolumeControlKeyUp(event) {
  13362. if (keycode__default['default'].isEventKey(event, 'Esc')) {
  13363. this.muteToggle.focus();
  13364. }
  13365. }
  13366. /**
  13367. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  13368. * Turns on listening for `mouseover` event. When they happen it
  13369. * calls `this.handleMouseOver`.
  13370. *
  13371. * @param {EventTarget~Event} event
  13372. * The `mouseover` event that caused this function to be called.
  13373. *
  13374. * @listens mouseover
  13375. */
  13376. ;
  13377. _proto.handleMouseOver = function handleMouseOver(event) {
  13378. this.addClass('vjs-hover');
  13379. on(document__default['default'], 'keyup', this.handleKeyPressHandler_);
  13380. }
  13381. /**
  13382. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  13383. * Turns on listening for `mouseout` event. When they happen it
  13384. * calls `this.handleMouseOut`.
  13385. *
  13386. * @param {EventTarget~Event} event
  13387. * The `mouseout` event that caused this function to be called.
  13388. *
  13389. * @listens mouseout
  13390. */
  13391. ;
  13392. _proto.handleMouseOut = function handleMouseOut(event) {
  13393. this.removeClass('vjs-hover');
  13394. off(document__default['default'], 'keyup', this.handleKeyPressHandler_);
  13395. }
  13396. /**
  13397. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  13398. * looking for ESC, which hides the `VolumeControl`.
  13399. *
  13400. * @param {EventTarget~Event} event
  13401. * The keypress that triggered this event.
  13402. *
  13403. * @listens keydown | keyup
  13404. */
  13405. ;
  13406. _proto.handleKeyPress = function handleKeyPress(event) {
  13407. if (keycode__default['default'].isEventKey(event, 'Esc')) {
  13408. this.handleMouseOut();
  13409. }
  13410. };
  13411. return VolumePanel;
  13412. }(Component$1);
  13413. /**
  13414. * Default options for the `VolumeControl`
  13415. *
  13416. * @type {Object}
  13417. * @private
  13418. */
  13419. VolumePanel.prototype.options_ = {
  13420. children: ['muteToggle', 'volumeControl']
  13421. };
  13422. Component$1.registerComponent('VolumePanel', VolumePanel);
  13423. /**
  13424. * The Menu component is used to build popup menus, including subtitle and
  13425. * captions selection menus.
  13426. *
  13427. * @extends Component
  13428. */
  13429. var Menu = /*#__PURE__*/function (_Component) {
  13430. _inheritsLoose__default['default'](Menu, _Component);
  13431. /**
  13432. * Create an instance of this class.
  13433. *
  13434. * @param {Player} player
  13435. * the player that this component should attach to
  13436. *
  13437. * @param {Object} [options]
  13438. * Object of option names and values
  13439. *
  13440. */
  13441. function Menu(player, options) {
  13442. var _this;
  13443. _this = _Component.call(this, player, options) || this;
  13444. if (options) {
  13445. _this.menuButton_ = options.menuButton;
  13446. }
  13447. _this.focusedChild_ = -1;
  13448. _this.on('keydown', function (e) {
  13449. return _this.handleKeyDown(e);
  13450. }); // All the menu item instances share the same blur handler provided by the menu container.
  13451. _this.boundHandleBlur_ = function (e) {
  13452. return _this.handleBlur(e);
  13453. };
  13454. _this.boundHandleTapClick_ = function (e) {
  13455. return _this.handleTapClick(e);
  13456. };
  13457. return _this;
  13458. }
  13459. /**
  13460. * Add event listeners to the {@link MenuItem}.
  13461. *
  13462. * @param {Object} component
  13463. * The instance of the `MenuItem` to add listeners to.
  13464. *
  13465. */
  13466. var _proto = Menu.prototype;
  13467. _proto.addEventListenerForItem = function addEventListenerForItem(component) {
  13468. if (!(component instanceof Component$1)) {
  13469. return;
  13470. }
  13471. this.on(component, 'blur', this.boundHandleBlur_);
  13472. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13473. }
  13474. /**
  13475. * Remove event listeners from the {@link MenuItem}.
  13476. *
  13477. * @param {Object} component
  13478. * The instance of the `MenuItem` to remove listeners.
  13479. *
  13480. */
  13481. ;
  13482. _proto.removeEventListenerForItem = function removeEventListenerForItem(component) {
  13483. if (!(component instanceof Component$1)) {
  13484. return;
  13485. }
  13486. this.off(component, 'blur', this.boundHandleBlur_);
  13487. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13488. }
  13489. /**
  13490. * This method will be called indirectly when the component has been added
  13491. * before the component adds to the new menu instance by `addItem`.
  13492. * In this case, the original menu instance will remove the component
  13493. * by calling `removeChild`.
  13494. *
  13495. * @param {Object} component
  13496. * The instance of the `MenuItem`
  13497. */
  13498. ;
  13499. _proto.removeChild = function removeChild(component) {
  13500. if (typeof component === 'string') {
  13501. component = this.getChild(component);
  13502. }
  13503. this.removeEventListenerForItem(component);
  13504. _Component.prototype.removeChild.call(this, component);
  13505. }
  13506. /**
  13507. * Add a {@link MenuItem} to the menu.
  13508. *
  13509. * @param {Object|string} component
  13510. * The name or instance of the `MenuItem` to add.
  13511. *
  13512. */
  13513. ;
  13514. _proto.addItem = function addItem(component) {
  13515. var childComponent = this.addChild(component);
  13516. if (childComponent) {
  13517. this.addEventListenerForItem(childComponent);
  13518. }
  13519. }
  13520. /**
  13521. * Create the `Menu`s DOM element.
  13522. *
  13523. * @return {Element}
  13524. * the element that was created
  13525. */
  13526. ;
  13527. _proto.createEl = function createEl$1() {
  13528. var contentElType = this.options_.contentElType || 'ul';
  13529. this.contentEl_ = createEl(contentElType, {
  13530. className: 'vjs-menu-content'
  13531. });
  13532. this.contentEl_.setAttribute('role', 'menu');
  13533. var el = _Component.prototype.createEl.call(this, 'div', {
  13534. append: this.contentEl_,
  13535. className: 'vjs-menu'
  13536. });
  13537. el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons,
  13538. // where a click on the parent is significant
  13539. on(el, 'click', function (event) {
  13540. event.preventDefault();
  13541. event.stopImmediatePropagation();
  13542. });
  13543. return el;
  13544. };
  13545. _proto.dispose = function dispose() {
  13546. this.contentEl_ = null;
  13547. this.boundHandleBlur_ = null;
  13548. this.boundHandleTapClick_ = null;
  13549. _Component.prototype.dispose.call(this);
  13550. }
  13551. /**
  13552. * Called when a `MenuItem` loses focus.
  13553. *
  13554. * @param {EventTarget~Event} event
  13555. * The `blur` event that caused this function to be called.
  13556. *
  13557. * @listens blur
  13558. */
  13559. ;
  13560. _proto.handleBlur = function handleBlur(event) {
  13561. var relatedTarget = event.relatedTarget || document__default['default'].activeElement; // Close menu popup when a user clicks outside the menu
  13562. if (!this.children().some(function (element) {
  13563. return element.el() === relatedTarget;
  13564. })) {
  13565. var btn = this.menuButton_;
  13566. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  13567. btn.unpressButton();
  13568. }
  13569. }
  13570. }
  13571. /**
  13572. * Called when a `MenuItem` gets clicked or tapped.
  13573. *
  13574. * @param {EventTarget~Event} event
  13575. * The `click` or `tap` event that caused this function to be called.
  13576. *
  13577. * @listens click,tap
  13578. */
  13579. ;
  13580. _proto.handleTapClick = function handleTapClick(event) {
  13581. // Unpress the associated MenuButton, and move focus back to it
  13582. if (this.menuButton_) {
  13583. this.menuButton_.unpressButton();
  13584. var childComponents = this.children();
  13585. if (!Array.isArray(childComponents)) {
  13586. return;
  13587. }
  13588. var foundComponent = childComponents.filter(function (component) {
  13589. return component.el() === event.target;
  13590. })[0];
  13591. if (!foundComponent) {
  13592. return;
  13593. } // don't focus menu button if item is a caption settings item
  13594. // because focus will move elsewhere
  13595. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  13596. this.menuButton_.focus();
  13597. }
  13598. }
  13599. }
  13600. /**
  13601. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  13602. *
  13603. * @param {EventTarget~Event} event
  13604. * A `keydown` event that happened on the menu.
  13605. *
  13606. * @listens keydown
  13607. */
  13608. ;
  13609. _proto.handleKeyDown = function handleKeyDown(event) {
  13610. // Left and Down Arrows
  13611. if (keycode__default['default'].isEventKey(event, 'Left') || keycode__default['default'].isEventKey(event, 'Down')) {
  13612. event.preventDefault();
  13613. event.stopPropagation();
  13614. this.stepForward(); // Up and Right Arrows
  13615. } else if (keycode__default['default'].isEventKey(event, 'Right') || keycode__default['default'].isEventKey(event, 'Up')) {
  13616. event.preventDefault();
  13617. event.stopPropagation();
  13618. this.stepBack();
  13619. }
  13620. }
  13621. /**
  13622. * Move to next (lower) menu item for keyboard users.
  13623. */
  13624. ;
  13625. _proto.stepForward = function stepForward() {
  13626. var stepChild = 0;
  13627. if (this.focusedChild_ !== undefined) {
  13628. stepChild = this.focusedChild_ + 1;
  13629. }
  13630. this.focus(stepChild);
  13631. }
  13632. /**
  13633. * Move to previous (higher) menu item for keyboard users.
  13634. */
  13635. ;
  13636. _proto.stepBack = function stepBack() {
  13637. var stepChild = 0;
  13638. if (this.focusedChild_ !== undefined) {
  13639. stepChild = this.focusedChild_ - 1;
  13640. }
  13641. this.focus(stepChild);
  13642. }
  13643. /**
  13644. * Set focus on a {@link MenuItem} in the `Menu`.
  13645. *
  13646. * @param {Object|string} [item=0]
  13647. * Index of child item set focus on.
  13648. */
  13649. ;
  13650. _proto.focus = function focus(item) {
  13651. if (item === void 0) {
  13652. item = 0;
  13653. }
  13654. var children = this.children().slice();
  13655. var haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  13656. if (haveTitle) {
  13657. children.shift();
  13658. }
  13659. if (children.length > 0) {
  13660. if (item < 0) {
  13661. item = 0;
  13662. } else if (item >= children.length) {
  13663. item = children.length - 1;
  13664. }
  13665. this.focusedChild_ = item;
  13666. children[item].el_.focus();
  13667. }
  13668. };
  13669. return Menu;
  13670. }(Component$1);
  13671. Component$1.registerComponent('Menu', Menu);
  13672. /**
  13673. * A `MenuButton` class for any popup {@link Menu}.
  13674. *
  13675. * @extends Component
  13676. */
  13677. var MenuButton = /*#__PURE__*/function (_Component) {
  13678. _inheritsLoose__default['default'](MenuButton, _Component);
  13679. /**
  13680. * Creates an instance of this class.
  13681. *
  13682. * @param {Player} player
  13683. * The `Player` that this class should be attached to.
  13684. *
  13685. * @param {Object} [options={}]
  13686. * The key/value store of player options.
  13687. */
  13688. function MenuButton(player, options) {
  13689. var _this;
  13690. if (options === void 0) {
  13691. options = {};
  13692. }
  13693. _this = _Component.call(this, player, options) || this;
  13694. _this.menuButton_ = new Button(player, options);
  13695. _this.menuButton_.controlText(_this.controlText_);
  13696. _this.menuButton_.el_.setAttribute('aria-haspopup', 'true'); // Add buildCSSClass values to the button, not the wrapper
  13697. var buttonClass = Button.prototype.buildCSSClass();
  13698. _this.menuButton_.el_.className = _this.buildCSSClass() + ' ' + buttonClass;
  13699. _this.menuButton_.removeClass('vjs-control');
  13700. _this.addChild(_this.menuButton_);
  13701. _this.update();
  13702. _this.enabled_ = true;
  13703. var handleClick = function handleClick(e) {
  13704. return _this.handleClick(e);
  13705. };
  13706. _this.handleMenuKeyUp_ = function (e) {
  13707. return _this.handleMenuKeyUp(e);
  13708. };
  13709. _this.on(_this.menuButton_, 'tap', handleClick);
  13710. _this.on(_this.menuButton_, 'click', handleClick);
  13711. _this.on(_this.menuButton_, 'keydown', function (e) {
  13712. return _this.handleKeyDown(e);
  13713. });
  13714. _this.on(_this.menuButton_, 'mouseenter', function () {
  13715. _this.addClass('vjs-hover');
  13716. _this.menu.show();
  13717. on(document__default['default'], 'keyup', _this.handleMenuKeyUp_);
  13718. });
  13719. _this.on('mouseleave', function (e) {
  13720. return _this.handleMouseLeave(e);
  13721. });
  13722. _this.on('keydown', function (e) {
  13723. return _this.handleSubmenuKeyDown(e);
  13724. });
  13725. return _this;
  13726. }
  13727. /**
  13728. * Update the menu based on the current state of its items.
  13729. */
  13730. var _proto = MenuButton.prototype;
  13731. _proto.update = function update() {
  13732. var menu = this.createMenu();
  13733. if (this.menu) {
  13734. this.menu.dispose();
  13735. this.removeChild(this.menu);
  13736. }
  13737. this.menu = menu;
  13738. this.addChild(menu);
  13739. /**
  13740. * Track the state of the menu button
  13741. *
  13742. * @type {Boolean}
  13743. * @private
  13744. */
  13745. this.buttonPressed_ = false;
  13746. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  13747. if (this.items && this.items.length <= this.hideThreshold_) {
  13748. this.hide();
  13749. this.menu.contentEl_.removeAttribute('role');
  13750. } else {
  13751. this.show();
  13752. this.menu.contentEl_.setAttribute('role', 'menu');
  13753. }
  13754. }
  13755. /**
  13756. * Create the menu and add all items to it.
  13757. *
  13758. * @return {Menu}
  13759. * The constructed menu
  13760. */
  13761. ;
  13762. _proto.createMenu = function createMenu() {
  13763. var menu = new Menu(this.player_, {
  13764. menuButton: this
  13765. });
  13766. /**
  13767. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  13768. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  13769. * it here because every time we run `createMenu` we need to reset the value.
  13770. *
  13771. * @protected
  13772. * @type {Number}
  13773. */
  13774. this.hideThreshold_ = 0; // Add a title list item to the top
  13775. if (this.options_.title) {
  13776. var titleEl = createEl('li', {
  13777. className: 'vjs-menu-title',
  13778. textContent: toTitleCase$1(this.options_.title),
  13779. tabIndex: -1
  13780. });
  13781. var titleComponent = new Component$1(this.player_, {
  13782. el: titleEl
  13783. });
  13784. menu.addItem(titleComponent);
  13785. }
  13786. this.items = this.createItems();
  13787. if (this.items) {
  13788. // Add menu items to the menu
  13789. for (var i = 0; i < this.items.length; i++) {
  13790. menu.addItem(this.items[i]);
  13791. }
  13792. }
  13793. return menu;
  13794. }
  13795. /**
  13796. * Create the list of menu items. Specific to each subclass.
  13797. *
  13798. * @abstract
  13799. */
  13800. ;
  13801. _proto.createItems = function createItems() {}
  13802. /**
  13803. * Create the `MenuButtons`s DOM element.
  13804. *
  13805. * @return {Element}
  13806. * The element that gets created.
  13807. */
  13808. ;
  13809. _proto.createEl = function createEl() {
  13810. return _Component.prototype.createEl.call(this, 'div', {
  13811. className: this.buildWrapperCSSClass()
  13812. }, {});
  13813. }
  13814. /**
  13815. * Allow sub components to stack CSS class names for the wrapper element
  13816. *
  13817. * @return {string}
  13818. * The constructed wrapper DOM `className`
  13819. */
  13820. ;
  13821. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  13822. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  13823. if (this.options_.inline === true) {
  13824. menuButtonClass += '-inline';
  13825. } else {
  13826. menuButtonClass += '-popup';
  13827. } // TODO: Fix the CSS so that this isn't necessary
  13828. var buttonClass = Button.prototype.buildCSSClass();
  13829. return "vjs-menu-button " + menuButtonClass + " " + buttonClass + " " + _Component.prototype.buildCSSClass.call(this);
  13830. }
  13831. /**
  13832. * Builds the default DOM `className`.
  13833. *
  13834. * @return {string}
  13835. * The DOM `className` for this object.
  13836. */
  13837. ;
  13838. _proto.buildCSSClass = function buildCSSClass() {
  13839. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  13840. if (this.options_.inline === true) {
  13841. menuButtonClass += '-inline';
  13842. } else {
  13843. menuButtonClass += '-popup';
  13844. }
  13845. return "vjs-menu-button " + menuButtonClass + " " + _Component.prototype.buildCSSClass.call(this);
  13846. }
  13847. /**
  13848. * Get or set the localized control text that will be used for accessibility.
  13849. *
  13850. * > NOTE: This will come from the internal `menuButton_` element.
  13851. *
  13852. * @param {string} [text]
  13853. * Control text for element.
  13854. *
  13855. * @param {Element} [el=this.menuButton_.el()]
  13856. * Element to set the title on.
  13857. *
  13858. * @return {string}
  13859. * - The control text when getting
  13860. */
  13861. ;
  13862. _proto.controlText = function controlText(text, el) {
  13863. if (el === void 0) {
  13864. el = this.menuButton_.el();
  13865. }
  13866. return this.menuButton_.controlText(text, el);
  13867. }
  13868. /**
  13869. * Dispose of the `menu-button` and all child components.
  13870. */
  13871. ;
  13872. _proto.dispose = function dispose() {
  13873. this.handleMouseLeave();
  13874. _Component.prototype.dispose.call(this);
  13875. }
  13876. /**
  13877. * Handle a click on a `MenuButton`.
  13878. * See {@link ClickableComponent#handleClick} for instances where this is called.
  13879. *
  13880. * @param {EventTarget~Event} event
  13881. * The `keydown`, `tap`, or `click` event that caused this function to be
  13882. * called.
  13883. *
  13884. * @listens tap
  13885. * @listens click
  13886. */
  13887. ;
  13888. _proto.handleClick = function handleClick(event) {
  13889. if (this.buttonPressed_) {
  13890. this.unpressButton();
  13891. } else {
  13892. this.pressButton();
  13893. }
  13894. }
  13895. /**
  13896. * Handle `mouseleave` for `MenuButton`.
  13897. *
  13898. * @param {EventTarget~Event} event
  13899. * The `mouseleave` event that caused this function to be called.
  13900. *
  13901. * @listens mouseleave
  13902. */
  13903. ;
  13904. _proto.handleMouseLeave = function handleMouseLeave(event) {
  13905. this.removeClass('vjs-hover');
  13906. off(document__default['default'], 'keyup', this.handleMenuKeyUp_);
  13907. }
  13908. /**
  13909. * Set the focus to the actual button, not to this element
  13910. */
  13911. ;
  13912. _proto.focus = function focus() {
  13913. this.menuButton_.focus();
  13914. }
  13915. /**
  13916. * Remove the focus from the actual button, not this element
  13917. */
  13918. ;
  13919. _proto.blur = function blur() {
  13920. this.menuButton_.blur();
  13921. }
  13922. /**
  13923. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  13924. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  13925. *
  13926. * @param {EventTarget~Event} event
  13927. * The `keydown` event that caused this function to be called.
  13928. *
  13929. * @listens keydown
  13930. */
  13931. ;
  13932. _proto.handleKeyDown = function handleKeyDown(event) {
  13933. // Escape or Tab unpress the 'button'
  13934. if (keycode__default['default'].isEventKey(event, 'Esc') || keycode__default['default'].isEventKey(event, 'Tab')) {
  13935. if (this.buttonPressed_) {
  13936. this.unpressButton();
  13937. } // Don't preventDefault for Tab key - we still want to lose focus
  13938. if (!keycode__default['default'].isEventKey(event, 'Tab')) {
  13939. event.preventDefault(); // Set focus back to the menu button's button
  13940. this.menuButton_.focus();
  13941. } // Up Arrow or Down Arrow also 'press' the button to open the menu
  13942. } else if (keycode__default['default'].isEventKey(event, 'Up') || keycode__default['default'].isEventKey(event, 'Down')) {
  13943. if (!this.buttonPressed_) {
  13944. event.preventDefault();
  13945. this.pressButton();
  13946. }
  13947. }
  13948. }
  13949. /**
  13950. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  13951. * the constructor.
  13952. *
  13953. * @param {EventTarget~Event} event
  13954. * Key press event
  13955. *
  13956. * @listens keyup
  13957. */
  13958. ;
  13959. _proto.handleMenuKeyUp = function handleMenuKeyUp(event) {
  13960. // Escape hides popup menu
  13961. if (keycode__default['default'].isEventKey(event, 'Esc') || keycode__default['default'].isEventKey(event, 'Tab')) {
  13962. this.removeClass('vjs-hover');
  13963. }
  13964. }
  13965. /**
  13966. * This method name now delegates to `handleSubmenuKeyDown`. This means
  13967. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  13968. * stop working.
  13969. *
  13970. * @param {EventTarget~Event} event
  13971. * The event that caused this function to be called.
  13972. */
  13973. ;
  13974. _proto.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) {
  13975. this.handleSubmenuKeyDown(event);
  13976. }
  13977. /**
  13978. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  13979. * the constructor.
  13980. *
  13981. * @param {EventTarget~Event} event
  13982. * Key press event
  13983. *
  13984. * @listens keydown
  13985. */
  13986. ;
  13987. _proto.handleSubmenuKeyDown = function handleSubmenuKeyDown(event) {
  13988. // Escape or Tab unpress the 'button'
  13989. if (keycode__default['default'].isEventKey(event, 'Esc') || keycode__default['default'].isEventKey(event, 'Tab')) {
  13990. if (this.buttonPressed_) {
  13991. this.unpressButton();
  13992. } // Don't preventDefault for Tab key - we still want to lose focus
  13993. if (!keycode__default['default'].isEventKey(event, 'Tab')) {
  13994. event.preventDefault(); // Set focus back to the menu button's button
  13995. this.menuButton_.focus();
  13996. }
  13997. }
  13998. }
  13999. /**
  14000. * Put the current `MenuButton` into a pressed state.
  14001. */
  14002. ;
  14003. _proto.pressButton = function pressButton() {
  14004. if (this.enabled_) {
  14005. this.buttonPressed_ = true;
  14006. this.menu.show();
  14007. this.menu.lockShowing();
  14008. this.menuButton_.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu, except on iOS where it is resulting in
  14009. // undesired scrolling behavior when the player is in an iframe
  14010. if (IS_IOS && isInFrame()) {
  14011. // Return early so that the menu isn't focused
  14012. return;
  14013. }
  14014. this.menu.focus();
  14015. }
  14016. }
  14017. /**
  14018. * Take the current `MenuButton` out of a pressed state.
  14019. */
  14020. ;
  14021. _proto.unpressButton = function unpressButton() {
  14022. if (this.enabled_) {
  14023. this.buttonPressed_ = false;
  14024. this.menu.unlockShowing();
  14025. this.menu.hide();
  14026. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  14027. }
  14028. }
  14029. /**
  14030. * Disable the `MenuButton`. Don't allow it to be clicked.
  14031. */
  14032. ;
  14033. _proto.disable = function disable() {
  14034. this.unpressButton();
  14035. this.enabled_ = false;
  14036. this.addClass('vjs-disabled');
  14037. this.menuButton_.disable();
  14038. }
  14039. /**
  14040. * Enable the `MenuButton`. Allow it to be clicked.
  14041. */
  14042. ;
  14043. _proto.enable = function enable() {
  14044. this.enabled_ = true;
  14045. this.removeClass('vjs-disabled');
  14046. this.menuButton_.enable();
  14047. };
  14048. return MenuButton;
  14049. }(Component$1);
  14050. Component$1.registerComponent('MenuButton', MenuButton);
  14051. /**
  14052. * The base class for buttons that toggle specific track types (e.g. subtitles).
  14053. *
  14054. * @extends MenuButton
  14055. */
  14056. var TrackButton = /*#__PURE__*/function (_MenuButton) {
  14057. _inheritsLoose__default['default'](TrackButton, _MenuButton);
  14058. /**
  14059. * Creates an instance of this class.
  14060. *
  14061. * @param {Player} player
  14062. * The `Player` that this class should be attached to.
  14063. *
  14064. * @param {Object} [options]
  14065. * The key/value store of player options.
  14066. */
  14067. function TrackButton(player, options) {
  14068. var _this;
  14069. var tracks = options.tracks;
  14070. _this = _MenuButton.call(this, player, options) || this;
  14071. if (_this.items.length <= 1) {
  14072. _this.hide();
  14073. }
  14074. if (!tracks) {
  14075. return _assertThisInitialized__default['default'](_this);
  14076. }
  14077. var updateHandler = bind(_assertThisInitialized__default['default'](_this), _this.update);
  14078. tracks.addEventListener('removetrack', updateHandler);
  14079. tracks.addEventListener('addtrack', updateHandler);
  14080. tracks.addEventListener('labelchange', updateHandler);
  14081. _this.player_.on('ready', updateHandler);
  14082. _this.player_.on('dispose', function () {
  14083. tracks.removeEventListener('removetrack', updateHandler);
  14084. tracks.removeEventListener('addtrack', updateHandler);
  14085. tracks.removeEventListener('labelchange', updateHandler);
  14086. });
  14087. return _this;
  14088. }
  14089. return TrackButton;
  14090. }(MenuButton);
  14091. Component$1.registerComponent('TrackButton', TrackButton);
  14092. /**
  14093. * @file menu-keys.js
  14094. */
  14095. /**
  14096. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  14097. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  14098. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  14099. * @typedef MenuKeys
  14100. * @array
  14101. */
  14102. var MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  14103. /**
  14104. * The component for a menu item. `<li>`
  14105. *
  14106. * @extends ClickableComponent
  14107. */
  14108. var MenuItem = /*#__PURE__*/function (_ClickableComponent) {
  14109. _inheritsLoose__default['default'](MenuItem, _ClickableComponent);
  14110. /**
  14111. * Creates an instance of the this class.
  14112. *
  14113. * @param {Player} player
  14114. * The `Player` that this class should be attached to.
  14115. *
  14116. * @param {Object} [options={}]
  14117. * The key/value store of player options.
  14118. *
  14119. */
  14120. function MenuItem(player, options) {
  14121. var _this;
  14122. _this = _ClickableComponent.call(this, player, options) || this;
  14123. _this.selectable = options.selectable;
  14124. _this.isSelected_ = options.selected || false;
  14125. _this.multiSelectable = options.multiSelectable;
  14126. _this.selected(_this.isSelected_);
  14127. if (_this.selectable) {
  14128. if (_this.multiSelectable) {
  14129. _this.el_.setAttribute('role', 'menuitemcheckbox');
  14130. } else {
  14131. _this.el_.setAttribute('role', 'menuitemradio');
  14132. }
  14133. } else {
  14134. _this.el_.setAttribute('role', 'menuitem');
  14135. }
  14136. return _this;
  14137. }
  14138. /**
  14139. * Create the `MenuItem's DOM element
  14140. *
  14141. * @param {string} [type=li]
  14142. * Element's node type, not actually used, always set to `li`.
  14143. *
  14144. * @param {Object} [props={}]
  14145. * An object of properties that should be set on the element
  14146. *
  14147. * @param {Object} [attrs={}]
  14148. * An object of attributes that should be set on the element
  14149. *
  14150. * @return {Element}
  14151. * The element that gets created.
  14152. */
  14153. var _proto = MenuItem.prototype;
  14154. _proto.createEl = function createEl$1(type, props, attrs) {
  14155. // The control is textual, not just an icon
  14156. this.nonIconControl = true;
  14157. var el = _ClickableComponent.prototype.createEl.call(this, 'li', assign({
  14158. className: 'vjs-menu-item',
  14159. tabIndex: -1
  14160. }, props), attrs); // swap icon with menu item text.
  14161. el.replaceChild(createEl('span', {
  14162. className: 'vjs-menu-item-text',
  14163. textContent: this.localize(this.options_.label)
  14164. }), el.querySelector('.vjs-icon-placeholder'));
  14165. return el;
  14166. }
  14167. /**
  14168. * Ignore keys which are used by the menu, but pass any other ones up. See
  14169. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  14170. *
  14171. * @param {EventTarget~Event} event
  14172. * The `keydown` event that caused this function to be called.
  14173. *
  14174. * @listens keydown
  14175. */
  14176. ;
  14177. _proto.handleKeyDown = function handleKeyDown(event) {
  14178. if (!MenuKeys.some(function (key) {
  14179. return keycode__default['default'].isEventKey(event, key);
  14180. })) {
  14181. // Pass keydown handling up for unused keys
  14182. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  14183. }
  14184. }
  14185. /**
  14186. * Any click on a `MenuItem` puts it into the selected state.
  14187. * See {@link ClickableComponent#handleClick} for instances where this is called.
  14188. *
  14189. * @param {EventTarget~Event} event
  14190. * The `keydown`, `tap`, or `click` event that caused this function to be
  14191. * called.
  14192. *
  14193. * @listens tap
  14194. * @listens click
  14195. */
  14196. ;
  14197. _proto.handleClick = function handleClick(event) {
  14198. this.selected(true);
  14199. }
  14200. /**
  14201. * Set the state for this menu item as selected or not.
  14202. *
  14203. * @param {boolean} selected
  14204. * if the menu item is selected or not
  14205. */
  14206. ;
  14207. _proto.selected = function selected(_selected) {
  14208. if (this.selectable) {
  14209. if (_selected) {
  14210. this.addClass('vjs-selected');
  14211. this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers,
  14212. // so indicate selected state to screen reader in the control text.
  14213. this.controlText(', selected');
  14214. this.isSelected_ = true;
  14215. } else {
  14216. this.removeClass('vjs-selected');
  14217. this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader
  14218. this.controlText('');
  14219. this.isSelected_ = false;
  14220. }
  14221. }
  14222. };
  14223. return MenuItem;
  14224. }(ClickableComponent);
  14225. Component$1.registerComponent('MenuItem', MenuItem);
  14226. /**
  14227. * The specific menu item type for selecting a language within a text track kind
  14228. *
  14229. * @extends MenuItem
  14230. */
  14231. var TextTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  14232. _inheritsLoose__default['default'](TextTrackMenuItem, _MenuItem);
  14233. /**
  14234. * Creates an instance of this class.
  14235. *
  14236. * @param {Player} player
  14237. * The `Player` that this class should be attached to.
  14238. *
  14239. * @param {Object} [options]
  14240. * The key/value store of player options.
  14241. */
  14242. function TextTrackMenuItem(player, options) {
  14243. var _this;
  14244. var track = options.track;
  14245. var tracks = player.textTracks(); // Modify options for parent MenuItem class's init.
  14246. options.label = track.label || track.language || 'Unknown';
  14247. options.selected = track.mode === 'showing';
  14248. _this = _MenuItem.call(this, player, options) || this;
  14249. _this.track = track; // Determine the relevant kind(s) of tracks for this component and filter
  14250. // out empty kinds.
  14251. _this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(Boolean);
  14252. var changeHandler = function changeHandler() {
  14253. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  14254. args[_key] = arguments[_key];
  14255. }
  14256. _this.handleTracksChange.apply(_assertThisInitialized__default['default'](_this), args);
  14257. };
  14258. var selectedLanguageChangeHandler = function selectedLanguageChangeHandler() {
  14259. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  14260. args[_key2] = arguments[_key2];
  14261. }
  14262. _this.handleSelectedLanguageChange.apply(_assertThisInitialized__default['default'](_this), args);
  14263. };
  14264. player.on(['loadstart', 'texttrackchange'], changeHandler);
  14265. tracks.addEventListener('change', changeHandler);
  14266. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14267. _this.on('dispose', function () {
  14268. player.off(['loadstart', 'texttrackchange'], changeHandler);
  14269. tracks.removeEventListener('change', changeHandler);
  14270. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14271. }); // iOS7 doesn't dispatch change events to TextTrackLists when an
  14272. // associated track's mode changes. Without something like
  14273. // Object.observe() (also not present on iOS7), it's not
  14274. // possible to detect changes to the mode attribute and polyfill
  14275. // the change event. As a poor substitute, we manually dispatch
  14276. // change events whenever the controls modify the mode.
  14277. if (tracks.onchange === undefined) {
  14278. var event;
  14279. _this.on(['tap', 'click'], function () {
  14280. if (typeof window__default['default'].Event !== 'object') {
  14281. // Android 2.3 throws an Illegal Constructor error for window.Event
  14282. try {
  14283. event = new window__default['default'].Event('change');
  14284. } catch (err) {// continue regardless of error
  14285. }
  14286. }
  14287. if (!event) {
  14288. event = document__default['default'].createEvent('Event');
  14289. event.initEvent('change', true, true);
  14290. }
  14291. tracks.dispatchEvent(event);
  14292. });
  14293. } // set the default state based on current tracks
  14294. _this.handleTracksChange();
  14295. return _this;
  14296. }
  14297. /**
  14298. * This gets called when an `TextTrackMenuItem` is "clicked". See
  14299. * {@link ClickableComponent} for more detailed information on what a click can be.
  14300. *
  14301. * @param {EventTarget~Event} event
  14302. * The `keydown`, `tap`, or `click` event that caused this function to be
  14303. * called.
  14304. *
  14305. * @listens tap
  14306. * @listens click
  14307. */
  14308. var _proto = TextTrackMenuItem.prototype;
  14309. _proto.handleClick = function handleClick(event) {
  14310. var referenceTrack = this.track;
  14311. var tracks = this.player_.textTracks();
  14312. _MenuItem.prototype.handleClick.call(this, event);
  14313. if (!tracks) {
  14314. return;
  14315. }
  14316. for (var i = 0; i < tracks.length; i++) {
  14317. var track = tracks[i]; // If the track from the text tracks list is not of the right kind,
  14318. // skip it. We do not want to affect tracks of incompatible kind(s).
  14319. if (this.kinds.indexOf(track.kind) === -1) {
  14320. continue;
  14321. } // If this text track is the component's track and it is not showing,
  14322. // set it to showing.
  14323. if (track === referenceTrack) {
  14324. if (track.mode !== 'showing') {
  14325. track.mode = 'showing';
  14326. } // If this text track is not the component's track and it is not
  14327. // disabled, set it to disabled.
  14328. } else if (track.mode !== 'disabled') {
  14329. track.mode = 'disabled';
  14330. }
  14331. }
  14332. }
  14333. /**
  14334. * Handle text track list change
  14335. *
  14336. * @param {EventTarget~Event} event
  14337. * The `change` event that caused this function to be called.
  14338. *
  14339. * @listens TextTrackList#change
  14340. */
  14341. ;
  14342. _proto.handleTracksChange = function handleTracksChange(event) {
  14343. var shouldBeSelected = this.track.mode === 'showing'; // Prevent redundant selected() calls because they may cause
  14344. // screen readers to read the appended control text unnecessarily
  14345. if (shouldBeSelected !== this.isSelected_) {
  14346. this.selected(shouldBeSelected);
  14347. }
  14348. };
  14349. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  14350. if (this.track.mode === 'showing') {
  14351. var selectedLanguage = this.player_.cache_.selectedLanguage; // Don't replace the kind of track across the same language
  14352. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14353. return;
  14354. }
  14355. this.player_.cache_.selectedLanguage = {
  14356. enabled: true,
  14357. language: this.track.language,
  14358. kind: this.track.kind
  14359. };
  14360. }
  14361. };
  14362. _proto.dispose = function dispose() {
  14363. // remove reference to track object on dispose
  14364. this.track = null;
  14365. _MenuItem.prototype.dispose.call(this);
  14366. };
  14367. return TextTrackMenuItem;
  14368. }(MenuItem);
  14369. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14370. /**
  14371. * A special menu item for turning of a specific type of text track
  14372. *
  14373. * @extends TextTrackMenuItem
  14374. */
  14375. var OffTextTrackMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  14376. _inheritsLoose__default['default'](OffTextTrackMenuItem, _TextTrackMenuItem);
  14377. /**
  14378. * Creates an instance of this class.
  14379. *
  14380. * @param {Player} player
  14381. * The `Player` that this class should be attached to.
  14382. *
  14383. * @param {Object} [options]
  14384. * The key/value store of player options.
  14385. */
  14386. function OffTextTrackMenuItem(player, options) {
  14387. // Create pseudo track info
  14388. // Requires options['kind']
  14389. options.track = {
  14390. player: player,
  14391. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14392. // since they are now stored in the `kinds` property of all instances of
  14393. // TextTrackMenuItem, but this will remain for backwards compatibility
  14394. kind: options.kind,
  14395. kinds: options.kinds,
  14396. "default": false,
  14397. mode: 'disabled'
  14398. };
  14399. if (!options.kinds) {
  14400. options.kinds = [options.kind];
  14401. }
  14402. if (options.label) {
  14403. options.track.label = options.label;
  14404. } else {
  14405. options.track.label = options.kinds.join(' and ') + ' off';
  14406. } // MenuItem is selectable
  14407. options.selectable = true; // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14408. options.multiSelectable = false;
  14409. return _TextTrackMenuItem.call(this, player, options) || this;
  14410. }
  14411. /**
  14412. * Handle text track change
  14413. *
  14414. * @param {EventTarget~Event} event
  14415. * The event that caused this function to run
  14416. */
  14417. var _proto = OffTextTrackMenuItem.prototype;
  14418. _proto.handleTracksChange = function handleTracksChange(event) {
  14419. var tracks = this.player().textTracks();
  14420. var shouldBeSelected = true;
  14421. for (var i = 0, l = tracks.length; i < l; i++) {
  14422. var track = tracks[i];
  14423. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14424. shouldBeSelected = false;
  14425. break;
  14426. }
  14427. } // Prevent redundant selected() calls because they may cause
  14428. // screen readers to read the appended control text unnecessarily
  14429. if (shouldBeSelected !== this.isSelected_) {
  14430. this.selected(shouldBeSelected);
  14431. }
  14432. };
  14433. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  14434. var tracks = this.player().textTracks();
  14435. var allHidden = true;
  14436. for (var i = 0, l = tracks.length; i < l; i++) {
  14437. var track = tracks[i];
  14438. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14439. allHidden = false;
  14440. break;
  14441. }
  14442. }
  14443. if (allHidden) {
  14444. this.player_.cache_.selectedLanguage = {
  14445. enabled: false
  14446. };
  14447. }
  14448. };
  14449. return OffTextTrackMenuItem;
  14450. }(TextTrackMenuItem);
  14451. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14452. /**
  14453. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14454. *
  14455. * @extends MenuButton
  14456. */
  14457. var TextTrackButton = /*#__PURE__*/function (_TrackButton) {
  14458. _inheritsLoose__default['default'](TextTrackButton, _TrackButton);
  14459. /**
  14460. * Creates an instance of this class.
  14461. *
  14462. * @param {Player} player
  14463. * The `Player` that this class should be attached to.
  14464. *
  14465. * @param {Object} [options={}]
  14466. * The key/value store of player options.
  14467. */
  14468. function TextTrackButton(player, options) {
  14469. if (options === void 0) {
  14470. options = {};
  14471. }
  14472. options.tracks = player.textTracks();
  14473. return _TrackButton.call(this, player, options) || this;
  14474. }
  14475. /**
  14476. * Create a menu item for each text track
  14477. *
  14478. * @param {TextTrackMenuItem[]} [items=[]]
  14479. * Existing array of items to use during creation
  14480. *
  14481. * @return {TextTrackMenuItem[]}
  14482. * Array of menu items that were created
  14483. */
  14484. var _proto = TextTrackButton.prototype;
  14485. _proto.createItems = function createItems(items, TrackMenuItem) {
  14486. if (items === void 0) {
  14487. items = [];
  14488. }
  14489. if (TrackMenuItem === void 0) {
  14490. TrackMenuItem = TextTrackMenuItem;
  14491. }
  14492. // Label is an override for the [track] off label
  14493. // USed to localise captions/subtitles
  14494. var label;
  14495. if (this.label_) {
  14496. label = this.label_ + " off";
  14497. } // Add an OFF menu item to turn all tracks off
  14498. items.push(new OffTextTrackMenuItem(this.player_, {
  14499. kinds: this.kinds_,
  14500. kind: this.kind_,
  14501. label: label
  14502. }));
  14503. this.hideThreshold_ += 1;
  14504. var tracks = this.player_.textTracks();
  14505. if (!Array.isArray(this.kinds_)) {
  14506. this.kinds_ = [this.kind_];
  14507. }
  14508. for (var i = 0; i < tracks.length; i++) {
  14509. var track = tracks[i]; // only add tracks that are of an appropriate kind and have a label
  14510. if (this.kinds_.indexOf(track.kind) > -1) {
  14511. var item = new TrackMenuItem(this.player_, {
  14512. track: track,
  14513. kinds: this.kinds_,
  14514. kind: this.kind_,
  14515. // MenuItem is selectable
  14516. selectable: true,
  14517. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14518. multiSelectable: false
  14519. });
  14520. item.addClass("vjs-" + track.kind + "-menu-item");
  14521. items.push(item);
  14522. }
  14523. }
  14524. return items;
  14525. };
  14526. return TextTrackButton;
  14527. }(TrackButton);
  14528. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  14529. /**
  14530. * The chapter track menu item
  14531. *
  14532. * @extends MenuItem
  14533. */
  14534. var ChaptersTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  14535. _inheritsLoose__default['default'](ChaptersTrackMenuItem, _MenuItem);
  14536. /**
  14537. * Creates an instance of this class.
  14538. *
  14539. * @param {Player} player
  14540. * The `Player` that this class should be attached to.
  14541. *
  14542. * @param {Object} [options]
  14543. * The key/value store of player options.
  14544. */
  14545. function ChaptersTrackMenuItem(player, options) {
  14546. var _this;
  14547. var track = options.track;
  14548. var cue = options.cue;
  14549. var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init.
  14550. options.selectable = true;
  14551. options.multiSelectable = false;
  14552. options.label = cue.text;
  14553. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  14554. _this = _MenuItem.call(this, player, options) || this;
  14555. _this.track = track;
  14556. _this.cue = cue;
  14557. return _this;
  14558. }
  14559. /**
  14560. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  14561. * {@link ClickableComponent} for more detailed information on what a click can be.
  14562. *
  14563. * @param {EventTarget~Event} [event]
  14564. * The `keydown`, `tap`, or `click` event that caused this function to be
  14565. * called.
  14566. *
  14567. * @listens tap
  14568. * @listens click
  14569. */
  14570. var _proto = ChaptersTrackMenuItem.prototype;
  14571. _proto.handleClick = function handleClick(event) {
  14572. _MenuItem.prototype.handleClick.call(this);
  14573. this.player_.currentTime(this.cue.startTime);
  14574. };
  14575. return ChaptersTrackMenuItem;
  14576. }(MenuItem);
  14577. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  14578. /**
  14579. * The button component for toggling and selecting chapters
  14580. * Chapters act much differently than other text tracks
  14581. * Cues are navigation vs. other tracks of alternative languages
  14582. *
  14583. * @extends TextTrackButton
  14584. */
  14585. var ChaptersButton = /*#__PURE__*/function (_TextTrackButton) {
  14586. _inheritsLoose__default['default'](ChaptersButton, _TextTrackButton);
  14587. /**
  14588. * Creates an instance of this class.
  14589. *
  14590. * @param {Player} player
  14591. * The `Player` that this class should be attached to.
  14592. *
  14593. * @param {Object} [options]
  14594. * The key/value store of player options.
  14595. *
  14596. * @param {Component~ReadyCallback} [ready]
  14597. * The function to call when this function is ready.
  14598. */
  14599. function ChaptersButton(player, options, ready) {
  14600. var _this;
  14601. _this = _TextTrackButton.call(this, player, options, ready) || this;
  14602. _this.selectCurrentItem_ = function () {
  14603. _this.items.forEach(function (item) {
  14604. item.selected(_this.track_.activeCues[0] === item.cue);
  14605. });
  14606. };
  14607. return _this;
  14608. }
  14609. /**
  14610. * Builds the default DOM `className`.
  14611. *
  14612. * @return {string}
  14613. * The DOM `className` for this object.
  14614. */
  14615. var _proto = ChaptersButton.prototype;
  14616. _proto.buildCSSClass = function buildCSSClass() {
  14617. return "vjs-chapters-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  14618. };
  14619. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  14620. return "vjs-chapters-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  14621. }
  14622. /**
  14623. * Update the menu based on the current state of its items.
  14624. *
  14625. * @param {EventTarget~Event} [event]
  14626. * An event that triggered this function to run.
  14627. *
  14628. * @listens TextTrackList#addtrack
  14629. * @listens TextTrackList#removetrack
  14630. * @listens TextTrackList#change
  14631. */
  14632. ;
  14633. _proto.update = function update(event) {
  14634. if (event && event.track && event.track.kind !== 'chapters') {
  14635. return;
  14636. }
  14637. var track = this.findChaptersTrack();
  14638. if (track !== this.track_) {
  14639. this.setTrack(track);
  14640. _TextTrackButton.prototype.update.call(this);
  14641. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  14642. // Update the menu initially or if the number of cues has changed since set
  14643. _TextTrackButton.prototype.update.call(this);
  14644. }
  14645. }
  14646. /**
  14647. * Set the currently selected track for the chapters button.
  14648. *
  14649. * @param {TextTrack} track
  14650. * The new track to select. Nothing will change if this is the currently selected
  14651. * track.
  14652. */
  14653. ;
  14654. _proto.setTrack = function setTrack(track) {
  14655. if (this.track_ === track) {
  14656. return;
  14657. }
  14658. if (!this.updateHandler_) {
  14659. this.updateHandler_ = this.update.bind(this);
  14660. } // here this.track_ refers to the old track instance
  14661. if (this.track_) {
  14662. var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14663. if (remoteTextTrackEl) {
  14664. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  14665. }
  14666. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  14667. this.track_ = null;
  14668. }
  14669. this.track_ = track; // here this.track_ refers to the new track instance
  14670. if (this.track_) {
  14671. this.track_.mode = 'hidden';
  14672. var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  14673. if (_remoteTextTrackEl) {
  14674. _remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  14675. }
  14676. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  14677. }
  14678. }
  14679. /**
  14680. * Find the track object that is currently in use by this ChaptersButton
  14681. *
  14682. * @return {TextTrack|undefined}
  14683. * The current track or undefined if none was found.
  14684. */
  14685. ;
  14686. _proto.findChaptersTrack = function findChaptersTrack() {
  14687. var tracks = this.player_.textTracks() || [];
  14688. for (var i = tracks.length - 1; i >= 0; i--) {
  14689. // We will always choose the last track as our chaptersTrack
  14690. var track = tracks[i];
  14691. if (track.kind === this.kind_) {
  14692. return track;
  14693. }
  14694. }
  14695. }
  14696. /**
  14697. * Get the caption for the ChaptersButton based on the track label. This will also
  14698. * use the current tracks localized kind as a fallback if a label does not exist.
  14699. *
  14700. * @return {string}
  14701. * The tracks current label or the localized track kind.
  14702. */
  14703. ;
  14704. _proto.getMenuCaption = function getMenuCaption() {
  14705. if (this.track_ && this.track_.label) {
  14706. return this.track_.label;
  14707. }
  14708. return this.localize(toTitleCase$1(this.kind_));
  14709. }
  14710. /**
  14711. * Create menu from chapter track
  14712. *
  14713. * @return {Menu}
  14714. * New menu for the chapter buttons
  14715. */
  14716. ;
  14717. _proto.createMenu = function createMenu() {
  14718. this.options_.title = this.getMenuCaption();
  14719. return _TextTrackButton.prototype.createMenu.call(this);
  14720. }
  14721. /**
  14722. * Create a menu item for each text track
  14723. *
  14724. * @return {TextTrackMenuItem[]}
  14725. * Array of menu items
  14726. */
  14727. ;
  14728. _proto.createItems = function createItems() {
  14729. var items = [];
  14730. if (!this.track_) {
  14731. return items;
  14732. }
  14733. var cues = this.track_.cues;
  14734. if (!cues) {
  14735. return items;
  14736. }
  14737. for (var i = 0, l = cues.length; i < l; i++) {
  14738. var cue = cues[i];
  14739. var mi = new ChaptersTrackMenuItem(this.player_, {
  14740. track: this.track_,
  14741. cue: cue
  14742. });
  14743. items.push(mi);
  14744. }
  14745. return items;
  14746. };
  14747. return ChaptersButton;
  14748. }(TextTrackButton);
  14749. /**
  14750. * `kind` of TextTrack to look for to associate it with this menu.
  14751. *
  14752. * @type {string}
  14753. * @private
  14754. */
  14755. ChaptersButton.prototype.kind_ = 'chapters';
  14756. /**
  14757. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  14758. *
  14759. * @type {string}
  14760. * @private
  14761. */
  14762. ChaptersButton.prototype.controlText_ = 'Chapters';
  14763. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  14764. /**
  14765. * The button component for toggling and selecting descriptions
  14766. *
  14767. * @extends TextTrackButton
  14768. */
  14769. var DescriptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  14770. _inheritsLoose__default['default'](DescriptionsButton, _TextTrackButton);
  14771. /**
  14772. * Creates an instance of this class.
  14773. *
  14774. * @param {Player} player
  14775. * The `Player` that this class should be attached to.
  14776. *
  14777. * @param {Object} [options]
  14778. * The key/value store of player options.
  14779. *
  14780. * @param {Component~ReadyCallback} [ready]
  14781. * The function to call when this component is ready.
  14782. */
  14783. function DescriptionsButton(player, options, ready) {
  14784. var _this;
  14785. _this = _TextTrackButton.call(this, player, options, ready) || this;
  14786. var tracks = player.textTracks();
  14787. var changeHandler = bind(_assertThisInitialized__default['default'](_this), _this.handleTracksChange);
  14788. tracks.addEventListener('change', changeHandler);
  14789. _this.on('dispose', function () {
  14790. tracks.removeEventListener('change', changeHandler);
  14791. });
  14792. return _this;
  14793. }
  14794. /**
  14795. * Handle text track change
  14796. *
  14797. * @param {EventTarget~Event} event
  14798. * The event that caused this function to run
  14799. *
  14800. * @listens TextTrackList#change
  14801. */
  14802. var _proto = DescriptionsButton.prototype;
  14803. _proto.handleTracksChange = function handleTracksChange(event) {
  14804. var tracks = this.player().textTracks();
  14805. var disabled = false; // Check whether a track of a different kind is showing
  14806. for (var i = 0, l = tracks.length; i < l; i++) {
  14807. var track = tracks[i];
  14808. if (track.kind !== this.kind_ && track.mode === 'showing') {
  14809. disabled = true;
  14810. break;
  14811. }
  14812. } // If another track is showing, disable this menu button
  14813. if (disabled) {
  14814. this.disable();
  14815. } else {
  14816. this.enable();
  14817. }
  14818. }
  14819. /**
  14820. * Builds the default DOM `className`.
  14821. *
  14822. * @return {string}
  14823. * The DOM `className` for this object.
  14824. */
  14825. ;
  14826. _proto.buildCSSClass = function buildCSSClass() {
  14827. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  14828. };
  14829. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  14830. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  14831. };
  14832. return DescriptionsButton;
  14833. }(TextTrackButton);
  14834. /**
  14835. * `kind` of TextTrack to look for to associate it with this menu.
  14836. *
  14837. * @type {string}
  14838. * @private
  14839. */
  14840. DescriptionsButton.prototype.kind_ = 'descriptions';
  14841. /**
  14842. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  14843. *
  14844. * @type {string}
  14845. * @private
  14846. */
  14847. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  14848. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  14849. /**
  14850. * The button component for toggling and selecting subtitles
  14851. *
  14852. * @extends TextTrackButton
  14853. */
  14854. var SubtitlesButton = /*#__PURE__*/function (_TextTrackButton) {
  14855. _inheritsLoose__default['default'](SubtitlesButton, _TextTrackButton);
  14856. /**
  14857. * Creates an instance of this class.
  14858. *
  14859. * @param {Player} player
  14860. * The `Player` that this class should be attached to.
  14861. *
  14862. * @param {Object} [options]
  14863. * The key/value store of player options.
  14864. *
  14865. * @param {Component~ReadyCallback} [ready]
  14866. * The function to call when this component is ready.
  14867. */
  14868. function SubtitlesButton(player, options, ready) {
  14869. return _TextTrackButton.call(this, player, options, ready) || this;
  14870. }
  14871. /**
  14872. * Builds the default DOM `className`.
  14873. *
  14874. * @return {string}
  14875. * The DOM `className` for this object.
  14876. */
  14877. var _proto = SubtitlesButton.prototype;
  14878. _proto.buildCSSClass = function buildCSSClass() {
  14879. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  14880. };
  14881. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  14882. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  14883. };
  14884. return SubtitlesButton;
  14885. }(TextTrackButton);
  14886. /**
  14887. * `kind` of TextTrack to look for to associate it with this menu.
  14888. *
  14889. * @type {string}
  14890. * @private
  14891. */
  14892. SubtitlesButton.prototype.kind_ = 'subtitles';
  14893. /**
  14894. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  14895. *
  14896. * @type {string}
  14897. * @private
  14898. */
  14899. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  14900. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  14901. /**
  14902. * The menu item for caption track settings menu
  14903. *
  14904. * @extends TextTrackMenuItem
  14905. */
  14906. var CaptionSettingsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  14907. _inheritsLoose__default['default'](CaptionSettingsMenuItem, _TextTrackMenuItem);
  14908. /**
  14909. * Creates an instance of this class.
  14910. *
  14911. * @param {Player} player
  14912. * The `Player` that this class should be attached to.
  14913. *
  14914. * @param {Object} [options]
  14915. * The key/value store of player options.
  14916. */
  14917. function CaptionSettingsMenuItem(player, options) {
  14918. var _this;
  14919. options.track = {
  14920. player: player,
  14921. kind: options.kind,
  14922. label: options.kind + ' settings',
  14923. selectable: false,
  14924. "default": false,
  14925. mode: 'disabled'
  14926. }; // CaptionSettingsMenuItem has no concept of 'selected'
  14927. options.selectable = false;
  14928. options.name = 'CaptionSettingsMenuItem';
  14929. _this = _TextTrackMenuItem.call(this, player, options) || this;
  14930. _this.addClass('vjs-texttrack-settings');
  14931. _this.controlText(', opens ' + options.kind + ' settings dialog');
  14932. return _this;
  14933. }
  14934. /**
  14935. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  14936. * {@link ClickableComponent} for more detailed information on what a click can be.
  14937. *
  14938. * @param {EventTarget~Event} [event]
  14939. * The `keydown`, `tap`, or `click` event that caused this function to be
  14940. * called.
  14941. *
  14942. * @listens tap
  14943. * @listens click
  14944. */
  14945. var _proto = CaptionSettingsMenuItem.prototype;
  14946. _proto.handleClick = function handleClick(event) {
  14947. this.player().getChild('textTrackSettings').open();
  14948. };
  14949. return CaptionSettingsMenuItem;
  14950. }(TextTrackMenuItem);
  14951. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  14952. /**
  14953. * The button component for toggling and selecting captions
  14954. *
  14955. * @extends TextTrackButton
  14956. */
  14957. var CaptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  14958. _inheritsLoose__default['default'](CaptionsButton, _TextTrackButton);
  14959. /**
  14960. * Creates an instance of this class.
  14961. *
  14962. * @param {Player} player
  14963. * The `Player` that this class should be attached to.
  14964. *
  14965. * @param {Object} [options]
  14966. * The key/value store of player options.
  14967. *
  14968. * @param {Component~ReadyCallback} [ready]
  14969. * The function to call when this component is ready.
  14970. */
  14971. function CaptionsButton(player, options, ready) {
  14972. return _TextTrackButton.call(this, player, options, ready) || this;
  14973. }
  14974. /**
  14975. * Builds the default DOM `className`.
  14976. *
  14977. * @return {string}
  14978. * The DOM `className` for this object.
  14979. */
  14980. var _proto = CaptionsButton.prototype;
  14981. _proto.buildCSSClass = function buildCSSClass() {
  14982. return "vjs-captions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  14983. };
  14984. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  14985. return "vjs-captions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  14986. }
  14987. /**
  14988. * Create caption menu items
  14989. *
  14990. * @return {CaptionSettingsMenuItem[]}
  14991. * The array of current menu items.
  14992. */
  14993. ;
  14994. _proto.createItems = function createItems() {
  14995. var items = [];
  14996. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  14997. items.push(new CaptionSettingsMenuItem(this.player_, {
  14998. kind: this.kind_
  14999. }));
  15000. this.hideThreshold_ += 1;
  15001. }
  15002. return _TextTrackButton.prototype.createItems.call(this, items);
  15003. };
  15004. return CaptionsButton;
  15005. }(TextTrackButton);
  15006. /**
  15007. * `kind` of TextTrack to look for to associate it with this menu.
  15008. *
  15009. * @type {string}
  15010. * @private
  15011. */
  15012. CaptionsButton.prototype.kind_ = 'captions';
  15013. /**
  15014. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  15015. *
  15016. * @type {string}
  15017. * @private
  15018. */
  15019. CaptionsButton.prototype.controlText_ = 'Captions';
  15020. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  15021. /**
  15022. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  15023. * in the SubsCapsMenu.
  15024. *
  15025. * @extends TextTrackMenuItem
  15026. */
  15027. var SubsCapsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  15028. _inheritsLoose__default['default'](SubsCapsMenuItem, _TextTrackMenuItem);
  15029. function SubsCapsMenuItem() {
  15030. return _TextTrackMenuItem.apply(this, arguments) || this;
  15031. }
  15032. var _proto = SubsCapsMenuItem.prototype;
  15033. _proto.createEl = function createEl$1(type, props, attrs) {
  15034. var el = _TextTrackMenuItem.prototype.createEl.call(this, type, props, attrs);
  15035. var parentSpan = el.querySelector('.vjs-menu-item-text');
  15036. if (this.options_.track.kind === 'captions') {
  15037. parentSpan.appendChild(createEl('span', {
  15038. className: 'vjs-icon-placeholder'
  15039. }, {
  15040. 'aria-hidden': true
  15041. }));
  15042. parentSpan.appendChild(createEl('span', {
  15043. className: 'vjs-control-text',
  15044. // space added as the text will visually flow with the
  15045. // label
  15046. textContent: " " + this.localize('Captions')
  15047. }));
  15048. }
  15049. return el;
  15050. };
  15051. return SubsCapsMenuItem;
  15052. }(TextTrackMenuItem);
  15053. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  15054. /**
  15055. * The button component for toggling and selecting captions and/or subtitles
  15056. *
  15057. * @extends TextTrackButton
  15058. */
  15059. var SubsCapsButton = /*#__PURE__*/function (_TextTrackButton) {
  15060. _inheritsLoose__default['default'](SubsCapsButton, _TextTrackButton);
  15061. function SubsCapsButton(player, options) {
  15062. var _this;
  15063. if (options === void 0) {
  15064. options = {};
  15065. }
  15066. _this = _TextTrackButton.call(this, player, options) || this; // Although North America uses "captions" in most cases for
  15067. // "captions and subtitles" other locales use "subtitles"
  15068. _this.label_ = 'subtitles';
  15069. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(_this.player_.language_) > -1) {
  15070. _this.label_ = 'captions';
  15071. }
  15072. _this.menuButton_.controlText(toTitleCase$1(_this.label_));
  15073. return _this;
  15074. }
  15075. /**
  15076. * Builds the default DOM `className`.
  15077. *
  15078. * @return {string}
  15079. * The DOM `className` for this object.
  15080. */
  15081. var _proto = SubsCapsButton.prototype;
  15082. _proto.buildCSSClass = function buildCSSClass() {
  15083. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15084. };
  15085. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15086. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15087. }
  15088. /**
  15089. * Create caption/subtitles menu items
  15090. *
  15091. * @return {CaptionSettingsMenuItem[]}
  15092. * The array of current menu items.
  15093. */
  15094. ;
  15095. _proto.createItems = function createItems() {
  15096. var items = [];
  15097. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  15098. items.push(new CaptionSettingsMenuItem(this.player_, {
  15099. kind: this.label_
  15100. }));
  15101. this.hideThreshold_ += 1;
  15102. }
  15103. items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem);
  15104. return items;
  15105. };
  15106. return SubsCapsButton;
  15107. }(TextTrackButton);
  15108. /**
  15109. * `kind`s of TextTrack to look for to associate it with this menu.
  15110. *
  15111. * @type {array}
  15112. * @private
  15113. */
  15114. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  15115. /**
  15116. * The text that should display over the `SubsCapsButton`s controls.
  15117. *
  15118. *
  15119. * @type {string}
  15120. * @private
  15121. */
  15122. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  15123. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  15124. /**
  15125. * An {@link AudioTrack} {@link MenuItem}
  15126. *
  15127. * @extends MenuItem
  15128. */
  15129. var AudioTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  15130. _inheritsLoose__default['default'](AudioTrackMenuItem, _MenuItem);
  15131. /**
  15132. * Creates an instance of this class.
  15133. *
  15134. * @param {Player} player
  15135. * The `Player` that this class should be attached to.
  15136. *
  15137. * @param {Object} [options]
  15138. * The key/value store of player options.
  15139. */
  15140. function AudioTrackMenuItem(player, options) {
  15141. var _this;
  15142. var track = options.track;
  15143. var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init.
  15144. options.label = track.label || track.language || 'Unknown';
  15145. options.selected = track.enabled;
  15146. _this = _MenuItem.call(this, player, options) || this;
  15147. _this.track = track;
  15148. _this.addClass("vjs-" + track.kind + "-menu-item");
  15149. var changeHandler = function changeHandler() {
  15150. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  15151. args[_key] = arguments[_key];
  15152. }
  15153. _this.handleTracksChange.apply(_assertThisInitialized__default['default'](_this), args);
  15154. };
  15155. tracks.addEventListener('change', changeHandler);
  15156. _this.on('dispose', function () {
  15157. tracks.removeEventListener('change', changeHandler);
  15158. });
  15159. return _this;
  15160. }
  15161. var _proto = AudioTrackMenuItem.prototype;
  15162. _proto.createEl = function createEl$1(type, props, attrs) {
  15163. var el = _MenuItem.prototype.createEl.call(this, type, props, attrs);
  15164. var parentSpan = el.querySelector('.vjs-menu-item-text');
  15165. if (this.options_.track.kind === 'main-desc') {
  15166. parentSpan.appendChild(createEl('span', {
  15167. className: 'vjs-icon-placeholder'
  15168. }, {
  15169. 'aria-hidden': true
  15170. }));
  15171. parentSpan.appendChild(createEl('span', {
  15172. className: 'vjs-control-text',
  15173. textContent: ' ' + this.localize('Descriptions')
  15174. }));
  15175. }
  15176. return el;
  15177. }
  15178. /**
  15179. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  15180. * for more detailed information on what a click can be.
  15181. *
  15182. * @param {EventTarget~Event} [event]
  15183. * The `keydown`, `tap`, or `click` event that caused this function to be
  15184. * called.
  15185. *
  15186. * @listens tap
  15187. * @listens click
  15188. */
  15189. ;
  15190. _proto.handleClick = function handleClick(event) {
  15191. _MenuItem.prototype.handleClick.call(this, event); // the audio track list will automatically toggle other tracks
  15192. // off for us.
  15193. this.track.enabled = true; // when native audio tracks are used, we want to make sure that other tracks are turned off
  15194. if (this.player_.tech_.featuresNativeAudioTracks) {
  15195. var tracks = this.player_.audioTracks();
  15196. for (var i = 0; i < tracks.length; i++) {
  15197. var track = tracks[i]; // skip the current track since we enabled it above
  15198. if (track === this.track) {
  15199. continue;
  15200. }
  15201. track.enabled = track === this.track;
  15202. }
  15203. }
  15204. }
  15205. /**
  15206. * Handle any {@link AudioTrack} change.
  15207. *
  15208. * @param {EventTarget~Event} [event]
  15209. * The {@link AudioTrackList#change} event that caused this to run.
  15210. *
  15211. * @listens AudioTrackList#change
  15212. */
  15213. ;
  15214. _proto.handleTracksChange = function handleTracksChange(event) {
  15215. this.selected(this.track.enabled);
  15216. };
  15217. return AudioTrackMenuItem;
  15218. }(MenuItem);
  15219. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  15220. /**
  15221. * The base class for buttons that toggle specific {@link AudioTrack} types.
  15222. *
  15223. * @extends TrackButton
  15224. */
  15225. var AudioTrackButton = /*#__PURE__*/function (_TrackButton) {
  15226. _inheritsLoose__default['default'](AudioTrackButton, _TrackButton);
  15227. /**
  15228. * Creates an instance of this class.
  15229. *
  15230. * @param {Player} player
  15231. * The `Player` that this class should be attached to.
  15232. *
  15233. * @param {Object} [options={}]
  15234. * The key/value store of player options.
  15235. */
  15236. function AudioTrackButton(player, options) {
  15237. if (options === void 0) {
  15238. options = {};
  15239. }
  15240. options.tracks = player.audioTracks();
  15241. return _TrackButton.call(this, player, options) || this;
  15242. }
  15243. /**
  15244. * Builds the default DOM `className`.
  15245. *
  15246. * @return {string}
  15247. * The DOM `className` for this object.
  15248. */
  15249. var _proto = AudioTrackButton.prototype;
  15250. _proto.buildCSSClass = function buildCSSClass() {
  15251. return "vjs-audio-button " + _TrackButton.prototype.buildCSSClass.call(this);
  15252. };
  15253. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15254. return "vjs-audio-button " + _TrackButton.prototype.buildWrapperCSSClass.call(this);
  15255. }
  15256. /**
  15257. * Create a menu item for each audio track
  15258. *
  15259. * @param {AudioTrackMenuItem[]} [items=[]]
  15260. * An array of existing menu items to use.
  15261. *
  15262. * @return {AudioTrackMenuItem[]}
  15263. * An array of menu items
  15264. */
  15265. ;
  15266. _proto.createItems = function createItems(items) {
  15267. if (items === void 0) {
  15268. items = [];
  15269. }
  15270. // if there's only one audio track, there no point in showing it
  15271. this.hideThreshold_ = 1;
  15272. var tracks = this.player_.audioTracks();
  15273. for (var i = 0; i < tracks.length; i++) {
  15274. var track = tracks[i];
  15275. items.push(new AudioTrackMenuItem(this.player_, {
  15276. track: track,
  15277. // MenuItem is selectable
  15278. selectable: true,
  15279. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  15280. multiSelectable: false
  15281. }));
  15282. }
  15283. return items;
  15284. };
  15285. return AudioTrackButton;
  15286. }(TrackButton);
  15287. /**
  15288. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  15289. *
  15290. * @type {string}
  15291. * @private
  15292. */
  15293. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  15294. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  15295. /**
  15296. * The specific menu item type for selecting a playback rate.
  15297. *
  15298. * @extends MenuItem
  15299. */
  15300. var PlaybackRateMenuItem = /*#__PURE__*/function (_MenuItem) {
  15301. _inheritsLoose__default['default'](PlaybackRateMenuItem, _MenuItem);
  15302. /**
  15303. * Creates an instance of this class.
  15304. *
  15305. * @param {Player} player
  15306. * The `Player` that this class should be attached to.
  15307. *
  15308. * @param {Object} [options]
  15309. * The key/value store of player options.
  15310. */
  15311. function PlaybackRateMenuItem(player, options) {
  15312. var _this;
  15313. var label = options.rate;
  15314. var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init.
  15315. options.label = label;
  15316. options.selected = rate === player.playbackRate();
  15317. options.selectable = true;
  15318. options.multiSelectable = false;
  15319. _this = _MenuItem.call(this, player, options) || this;
  15320. _this.label = label;
  15321. _this.rate = rate;
  15322. _this.on(player, 'ratechange', function (e) {
  15323. return _this.update(e);
  15324. });
  15325. return _this;
  15326. }
  15327. /**
  15328. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  15329. * {@link ClickableComponent} for more detailed information on what a click can be.
  15330. *
  15331. * @param {EventTarget~Event} [event]
  15332. * The `keydown`, `tap`, or `click` event that caused this function to be
  15333. * called.
  15334. *
  15335. * @listens tap
  15336. * @listens click
  15337. */
  15338. var _proto = PlaybackRateMenuItem.prototype;
  15339. _proto.handleClick = function handleClick(event) {
  15340. _MenuItem.prototype.handleClick.call(this);
  15341. this.player().playbackRate(this.rate);
  15342. }
  15343. /**
  15344. * Update the PlaybackRateMenuItem when the playbackrate changes.
  15345. *
  15346. * @param {EventTarget~Event} [event]
  15347. * The `ratechange` event that caused this function to run.
  15348. *
  15349. * @listens Player#ratechange
  15350. */
  15351. ;
  15352. _proto.update = function update(event) {
  15353. this.selected(this.player().playbackRate() === this.rate);
  15354. };
  15355. return PlaybackRateMenuItem;
  15356. }(MenuItem);
  15357. /**
  15358. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  15359. *
  15360. * @type {string}
  15361. * @private
  15362. */
  15363. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15364. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15365. /**
  15366. * The component for controlling the playback rate.
  15367. *
  15368. * @extends MenuButton
  15369. */
  15370. var PlaybackRateMenuButton = /*#__PURE__*/function (_MenuButton) {
  15371. _inheritsLoose__default['default'](PlaybackRateMenuButton, _MenuButton);
  15372. /**
  15373. * Creates an instance of this class.
  15374. *
  15375. * @param {Player} player
  15376. * The `Player` that this class should be attached to.
  15377. *
  15378. * @param {Object} [options]
  15379. * The key/value store of player options.
  15380. */
  15381. function PlaybackRateMenuButton(player, options) {
  15382. var _this;
  15383. _this = _MenuButton.call(this, player, options) || this;
  15384. _this.menuButton_.el_.setAttribute('aria-describedby', _this.labelElId_);
  15385. _this.updateVisibility();
  15386. _this.updateLabel();
  15387. _this.on(player, 'loadstart', function (e) {
  15388. return _this.updateVisibility(e);
  15389. });
  15390. _this.on(player, 'ratechange', function (e) {
  15391. return _this.updateLabel(e);
  15392. });
  15393. _this.on(player, 'playbackrateschange', function (e) {
  15394. return _this.handlePlaybackRateschange(e);
  15395. });
  15396. return _this;
  15397. }
  15398. /**
  15399. * Create the `Component`'s DOM element
  15400. *
  15401. * @return {Element}
  15402. * The element that was created.
  15403. */
  15404. var _proto = PlaybackRateMenuButton.prototype;
  15405. _proto.createEl = function createEl$1() {
  15406. var el = _MenuButton.prototype.createEl.call(this);
  15407. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15408. this.labelEl_ = createEl('div', {
  15409. className: 'vjs-playback-rate-value',
  15410. id: this.labelElId_,
  15411. textContent: '1x'
  15412. });
  15413. el.appendChild(this.labelEl_);
  15414. return el;
  15415. };
  15416. _proto.dispose = function dispose() {
  15417. this.labelEl_ = null;
  15418. _MenuButton.prototype.dispose.call(this);
  15419. }
  15420. /**
  15421. * Builds the default DOM `className`.
  15422. *
  15423. * @return {string}
  15424. * The DOM `className` for this object.
  15425. */
  15426. ;
  15427. _proto.buildCSSClass = function buildCSSClass() {
  15428. return "vjs-playback-rate " + _MenuButton.prototype.buildCSSClass.call(this);
  15429. };
  15430. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15431. return "vjs-playback-rate " + _MenuButton.prototype.buildWrapperCSSClass.call(this);
  15432. }
  15433. /**
  15434. * Create the list of menu items. Specific to each subclass.
  15435. *
  15436. */
  15437. ;
  15438. _proto.createItems = function createItems() {
  15439. var rates = this.playbackRates();
  15440. var items = [];
  15441. for (var i = rates.length - 1; i >= 0; i--) {
  15442. items.push(new PlaybackRateMenuItem(this.player(), {
  15443. rate: rates[i] + 'x'
  15444. }));
  15445. }
  15446. return items;
  15447. }
  15448. /**
  15449. * Updates ARIA accessibility attributes
  15450. */
  15451. ;
  15452. _proto.updateARIAAttributes = function updateARIAAttributes() {
  15453. // Current playback rate
  15454. this.el().setAttribute('aria-valuenow', this.player().playbackRate());
  15455. }
  15456. /**
  15457. * This gets called when an `PlaybackRateMenuButton` is "clicked". See
  15458. * {@link ClickableComponent} for more detailed information on what a click can be.
  15459. *
  15460. * @param {EventTarget~Event} [event]
  15461. * The `keydown`, `tap`, or `click` event that caused this function to be
  15462. * called.
  15463. *
  15464. * @listens tap
  15465. * @listens click
  15466. */
  15467. ;
  15468. _proto.handleClick = function handleClick(event) {
  15469. // select next rate option
  15470. var currentRate = this.player().playbackRate();
  15471. var rates = this.playbackRates();
  15472. var currentIndex = rates.indexOf(currentRate); // this get the next rate and it will select first one if the last one currently selected
  15473. var newIndex = (currentIndex + 1) % rates.length;
  15474. this.player().playbackRate(rates[newIndex]);
  15475. }
  15476. /**
  15477. * On playbackrateschange, update the menu to account for the new items.
  15478. *
  15479. * @listens Player#playbackrateschange
  15480. */
  15481. ;
  15482. _proto.handlePlaybackRateschange = function handlePlaybackRateschange(event) {
  15483. this.update();
  15484. }
  15485. /**
  15486. * Get possible playback rates
  15487. *
  15488. * @return {Array}
  15489. * All possible playback rates
  15490. */
  15491. ;
  15492. _proto.playbackRates = function playbackRates() {
  15493. var player = this.player();
  15494. return player.playbackRates && player.playbackRates() || [];
  15495. }
  15496. /**
  15497. * Get whether playback rates is supported by the tech
  15498. * and an array of playback rates exists
  15499. *
  15500. * @return {boolean}
  15501. * Whether changing playback rate is supported
  15502. */
  15503. ;
  15504. _proto.playbackRateSupported = function playbackRateSupported() {
  15505. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15506. }
  15507. /**
  15508. * Hide playback rate controls when they're no playback rate options to select
  15509. *
  15510. * @param {EventTarget~Event} [event]
  15511. * The event that caused this function to run.
  15512. *
  15513. * @listens Player#loadstart
  15514. */
  15515. ;
  15516. _proto.updateVisibility = function updateVisibility(event) {
  15517. if (this.playbackRateSupported()) {
  15518. this.removeClass('vjs-hidden');
  15519. } else {
  15520. this.addClass('vjs-hidden');
  15521. }
  15522. }
  15523. /**
  15524. * Update button label when rate changed
  15525. *
  15526. * @param {EventTarget~Event} [event]
  15527. * The event that caused this function to run.
  15528. *
  15529. * @listens Player#ratechange
  15530. */
  15531. ;
  15532. _proto.updateLabel = function updateLabel(event) {
  15533. if (this.playbackRateSupported()) {
  15534. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  15535. }
  15536. };
  15537. return PlaybackRateMenuButton;
  15538. }(MenuButton);
  15539. /**
  15540. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  15541. *
  15542. * @type {string}
  15543. * @private
  15544. */
  15545. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  15546. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  15547. /**
  15548. * Just an empty spacer element that can be used as an append point for plugins, etc.
  15549. * Also can be used to create space between elements when necessary.
  15550. *
  15551. * @extends Component
  15552. */
  15553. var Spacer = /*#__PURE__*/function (_Component) {
  15554. _inheritsLoose__default['default'](Spacer, _Component);
  15555. function Spacer() {
  15556. return _Component.apply(this, arguments) || this;
  15557. }
  15558. var _proto = Spacer.prototype;
  15559. /**
  15560. * Builds the default DOM `className`.
  15561. *
  15562. * @return {string}
  15563. * The DOM `className` for this object.
  15564. */
  15565. _proto.buildCSSClass = function buildCSSClass() {
  15566. return "vjs-spacer " + _Component.prototype.buildCSSClass.call(this);
  15567. }
  15568. /**
  15569. * Create the `Component`'s DOM element
  15570. *
  15571. * @return {Element}
  15572. * The element that was created.
  15573. */
  15574. ;
  15575. _proto.createEl = function createEl(tag, props, attributes) {
  15576. if (tag === void 0) {
  15577. tag = 'div';
  15578. }
  15579. if (props === void 0) {
  15580. props = {};
  15581. }
  15582. if (attributes === void 0) {
  15583. attributes = {};
  15584. }
  15585. if (!props.className) {
  15586. props.className = this.buildCSSClass();
  15587. }
  15588. return _Component.prototype.createEl.call(this, tag, props, attributes);
  15589. };
  15590. return Spacer;
  15591. }(Component$1);
  15592. Component$1.registerComponent('Spacer', Spacer);
  15593. /**
  15594. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  15595. *
  15596. * @extends Spacer
  15597. */
  15598. var CustomControlSpacer = /*#__PURE__*/function (_Spacer) {
  15599. _inheritsLoose__default['default'](CustomControlSpacer, _Spacer);
  15600. function CustomControlSpacer() {
  15601. return _Spacer.apply(this, arguments) || this;
  15602. }
  15603. var _proto = CustomControlSpacer.prototype;
  15604. /**
  15605. * Builds the default DOM `className`.
  15606. *
  15607. * @return {string}
  15608. * The DOM `className` for this object.
  15609. */
  15610. _proto.buildCSSClass = function buildCSSClass() {
  15611. return "vjs-custom-control-spacer " + _Spacer.prototype.buildCSSClass.call(this);
  15612. }
  15613. /**
  15614. * Create the `Component`'s DOM element
  15615. *
  15616. * @return {Element}
  15617. * The element that was created.
  15618. */
  15619. ;
  15620. _proto.createEl = function createEl() {
  15621. return _Spacer.prototype.createEl.call(this, 'div', {
  15622. className: this.buildCSSClass(),
  15623. // No-flex/table-cell mode requires there be some content
  15624. // in the cell to fill the remaining space of the table.
  15625. textContent: "\xA0"
  15626. });
  15627. };
  15628. return CustomControlSpacer;
  15629. }(Spacer);
  15630. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  15631. /**
  15632. * Container of main controls.
  15633. *
  15634. * @extends Component
  15635. */
  15636. var ControlBar = /*#__PURE__*/function (_Component) {
  15637. _inheritsLoose__default['default'](ControlBar, _Component);
  15638. function ControlBar() {
  15639. return _Component.apply(this, arguments) || this;
  15640. }
  15641. var _proto = ControlBar.prototype;
  15642. /**
  15643. * Create the `Component`'s DOM element
  15644. *
  15645. * @return {Element}
  15646. * The element that was created.
  15647. */
  15648. _proto.createEl = function createEl() {
  15649. return _Component.prototype.createEl.call(this, 'div', {
  15650. className: 'vjs-control-bar',
  15651. dir: 'ltr'
  15652. });
  15653. };
  15654. return ControlBar;
  15655. }(Component$1);
  15656. /**
  15657. * Default options for `ControlBar`
  15658. *
  15659. * @type {Object}
  15660. * @private
  15661. */
  15662. ControlBar.prototype.options_ = {
  15663. children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  15664. };
  15665. if ('exitPictureInPicture' in document__default['default']) {
  15666. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  15667. }
  15668. Component$1.registerComponent('ControlBar', ControlBar);
  15669. /**
  15670. * A display that indicates an error has occurred. This means that the video
  15671. * is unplayable.
  15672. *
  15673. * @extends ModalDialog
  15674. */
  15675. var ErrorDisplay = /*#__PURE__*/function (_ModalDialog) {
  15676. _inheritsLoose__default['default'](ErrorDisplay, _ModalDialog);
  15677. /**
  15678. * Creates an instance of this class.
  15679. *
  15680. * @param {Player} player
  15681. * The `Player` that this class should be attached to.
  15682. *
  15683. * @param {Object} [options]
  15684. * The key/value store of player options.
  15685. */
  15686. function ErrorDisplay(player, options) {
  15687. var _this;
  15688. _this = _ModalDialog.call(this, player, options) || this;
  15689. _this.on(player, 'error', function (e) {
  15690. return _this.open(e);
  15691. });
  15692. return _this;
  15693. }
  15694. /**
  15695. * Builds the default DOM `className`.
  15696. *
  15697. * @return {string}
  15698. * The DOM `className` for this object.
  15699. *
  15700. * @deprecated Since version 5.
  15701. */
  15702. var _proto = ErrorDisplay.prototype;
  15703. _proto.buildCSSClass = function buildCSSClass() {
  15704. return "vjs-error-display " + _ModalDialog.prototype.buildCSSClass.call(this);
  15705. }
  15706. /**
  15707. * Gets the localized error message based on the `Player`s error.
  15708. *
  15709. * @return {string}
  15710. * The `Player`s error message localized or an empty string.
  15711. */
  15712. ;
  15713. _proto.content = function content() {
  15714. var error = this.player().error();
  15715. return error ? this.localize(error.message) : '';
  15716. };
  15717. return ErrorDisplay;
  15718. }(ModalDialog);
  15719. /**
  15720. * The default options for an `ErrorDisplay`.
  15721. *
  15722. * @private
  15723. */
  15724. ErrorDisplay.prototype.options_ = _extends__default['default']({}, ModalDialog.prototype.options_, {
  15725. pauseOnOpen: false,
  15726. fillAlways: true,
  15727. temporary: false,
  15728. uncloseable: true
  15729. });
  15730. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  15731. var LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  15732. var COLOR_BLACK = ['#000', 'Black'];
  15733. var COLOR_BLUE = ['#00F', 'Blue'];
  15734. var COLOR_CYAN = ['#0FF', 'Cyan'];
  15735. var COLOR_GREEN = ['#0F0', 'Green'];
  15736. var COLOR_MAGENTA = ['#F0F', 'Magenta'];
  15737. var COLOR_RED = ['#F00', 'Red'];
  15738. var COLOR_WHITE = ['#FFF', 'White'];
  15739. var COLOR_YELLOW = ['#FF0', 'Yellow'];
  15740. var OPACITY_OPAQUE = ['1', 'Opaque'];
  15741. var OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  15742. var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component.
  15743. //
  15744. // Possible keys include:
  15745. //
  15746. // `default`:
  15747. // The default option index. Only needs to be provided if not zero.
  15748. // `parser`:
  15749. // A function which is used to parse the value from the selected option in
  15750. // a customized way.
  15751. // `selector`:
  15752. // The selector used to find the associated <select> element.
  15753. var selectConfigs = {
  15754. backgroundColor: {
  15755. selector: '.vjs-bg-color > select',
  15756. id: 'captions-background-color-%s',
  15757. label: 'Color',
  15758. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15759. },
  15760. backgroundOpacity: {
  15761. selector: '.vjs-bg-opacity > select',
  15762. id: 'captions-background-opacity-%s',
  15763. label: 'Transparency',
  15764. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  15765. },
  15766. color: {
  15767. selector: '.vjs-fg-color > select',
  15768. id: 'captions-foreground-color-%s',
  15769. label: 'Color',
  15770. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  15771. },
  15772. edgeStyle: {
  15773. selector: '.vjs-edge-style > select',
  15774. id: '%s',
  15775. label: 'Text Edge Style',
  15776. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  15777. },
  15778. fontFamily: {
  15779. selector: '.vjs-font-family > select',
  15780. id: 'captions-font-family-%s',
  15781. label: 'Font Family',
  15782. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  15783. },
  15784. fontPercent: {
  15785. selector: '.vjs-font-percent > select',
  15786. id: 'captions-font-size-%s',
  15787. label: 'Font Size',
  15788. 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%']],
  15789. "default": 2,
  15790. parser: function parser(v) {
  15791. return v === '1.00' ? null : Number(v);
  15792. }
  15793. },
  15794. textOpacity: {
  15795. selector: '.vjs-text-opacity > select',
  15796. id: 'captions-foreground-opacity-%s',
  15797. label: 'Transparency',
  15798. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  15799. },
  15800. // Options for this object are defined below.
  15801. windowColor: {
  15802. selector: '.vjs-window-color > select',
  15803. id: 'captions-window-color-%s',
  15804. label: 'Color'
  15805. },
  15806. // Options for this object are defined below.
  15807. windowOpacity: {
  15808. selector: '.vjs-window-opacity > select',
  15809. id: 'captions-window-opacity-%s',
  15810. label: 'Transparency',
  15811. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  15812. }
  15813. };
  15814. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  15815. /**
  15816. * Get the actual value of an option.
  15817. *
  15818. * @param {string} value
  15819. * The value to get
  15820. *
  15821. * @param {Function} [parser]
  15822. * Optional function to adjust the value.
  15823. *
  15824. * @return {Mixed}
  15825. * - Will be `undefined` if no value exists
  15826. * - Will be `undefined` if the given value is "none".
  15827. * - Will be the actual value otherwise.
  15828. *
  15829. * @private
  15830. */
  15831. function parseOptionValue(value, parser) {
  15832. if (parser) {
  15833. value = parser(value);
  15834. }
  15835. if (value && value !== 'none') {
  15836. return value;
  15837. }
  15838. }
  15839. /**
  15840. * Gets the value of the selected <option> element within a <select> element.
  15841. *
  15842. * @param {Element} el
  15843. * the element to look in
  15844. *
  15845. * @param {Function} [parser]
  15846. * Optional function to adjust the value.
  15847. *
  15848. * @return {Mixed}
  15849. * - Will be `undefined` if no value exists
  15850. * - Will be `undefined` if the given value is "none".
  15851. * - Will be the actual value otherwise.
  15852. *
  15853. * @private
  15854. */
  15855. function getSelectedOptionValue(el, parser) {
  15856. var value = el.options[el.options.selectedIndex].value;
  15857. return parseOptionValue(value, parser);
  15858. }
  15859. /**
  15860. * Sets the selected <option> element within a <select> element based on a
  15861. * given value.
  15862. *
  15863. * @param {Element} el
  15864. * The element to look in.
  15865. *
  15866. * @param {string} value
  15867. * the property to look on.
  15868. *
  15869. * @param {Function} [parser]
  15870. * Optional function to adjust the value before comparing.
  15871. *
  15872. * @private
  15873. */
  15874. function setSelectedOption(el, value, parser) {
  15875. if (!value) {
  15876. return;
  15877. }
  15878. for (var i = 0; i < el.options.length; i++) {
  15879. if (parseOptionValue(el.options[i].value, parser) === value) {
  15880. el.selectedIndex = i;
  15881. break;
  15882. }
  15883. }
  15884. }
  15885. /**
  15886. * Manipulate Text Tracks settings.
  15887. *
  15888. * @extends ModalDialog
  15889. */
  15890. var TextTrackSettings = /*#__PURE__*/function (_ModalDialog) {
  15891. _inheritsLoose__default['default'](TextTrackSettings, _ModalDialog);
  15892. /**
  15893. * Creates an instance of this class.
  15894. *
  15895. * @param {Player} player
  15896. * The `Player` that this class should be attached to.
  15897. *
  15898. * @param {Object} [options]
  15899. * The key/value store of player options.
  15900. */
  15901. function TextTrackSettings(player, options) {
  15902. var _this;
  15903. options.temporary = false;
  15904. _this = _ModalDialog.call(this, player, options) || this;
  15905. _this.updateDisplay = _this.updateDisplay.bind(_assertThisInitialized__default['default'](_this)); // fill the modal and pretend we have opened it
  15906. _this.fill();
  15907. _this.hasBeenOpened_ = _this.hasBeenFilled_ = true;
  15908. _this.endDialog = createEl('p', {
  15909. className: 'vjs-control-text',
  15910. textContent: _this.localize('End of dialog window.')
  15911. });
  15912. _this.el().appendChild(_this.endDialog);
  15913. _this.setDefaults(); // Grab `persistTextTrackSettings` from the player options if not passed in child options
  15914. if (options.persistTextTrackSettings === undefined) {
  15915. _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings;
  15916. }
  15917. _this.on(_this.$('.vjs-done-button'), 'click', function () {
  15918. _this.saveSettings();
  15919. _this.close();
  15920. });
  15921. _this.on(_this.$('.vjs-default-button'), 'click', function () {
  15922. _this.setDefaults();
  15923. _this.updateDisplay();
  15924. });
  15925. each(selectConfigs, function (config) {
  15926. _this.on(_this.$(config.selector), 'change', _this.updateDisplay);
  15927. });
  15928. if (_this.options_.persistTextTrackSettings) {
  15929. _this.restoreSettings();
  15930. }
  15931. return _this;
  15932. }
  15933. var _proto = TextTrackSettings.prototype;
  15934. _proto.dispose = function dispose() {
  15935. this.endDialog = null;
  15936. _ModalDialog.prototype.dispose.call(this);
  15937. }
  15938. /**
  15939. * Create a <select> element with configured options.
  15940. *
  15941. * @param {string} key
  15942. * Configuration key to use during creation.
  15943. *
  15944. * @return {string}
  15945. * An HTML string.
  15946. *
  15947. * @private
  15948. */
  15949. ;
  15950. _proto.createElSelect_ = function createElSelect_(key, legendId, type) {
  15951. var _this2 = this;
  15952. if (legendId === void 0) {
  15953. legendId = '';
  15954. }
  15955. if (type === void 0) {
  15956. type = 'label';
  15957. }
  15958. var config = selectConfigs[key];
  15959. var id = config.id.replace('%s', this.id_);
  15960. var selectLabelledbyIds = [legendId, id].join(' ').trim();
  15961. return ["<" + type + " id=\"" + id + "\" class=\"" + (type === 'label' ? 'vjs-label' : '') + "\">", this.localize(config.label), "</" + type + ">", "<select aria-labelledby=\"" + selectLabelledbyIds + "\">"].concat(config.options.map(function (o) {
  15962. var optionId = id + '-' + o[1].replace(/\W+/g, '');
  15963. return ["<option id=\"" + optionId + "\" value=\"" + o[0] + "\" ", "aria-labelledby=\"" + selectLabelledbyIds + " " + optionId + "\">", _this2.localize(o[1]), '</option>'].join('');
  15964. })).concat('</select>').join('');
  15965. }
  15966. /**
  15967. * Create foreground color element for the component
  15968. *
  15969. * @return {string}
  15970. * An HTML string.
  15971. *
  15972. * @private
  15973. */
  15974. ;
  15975. _proto.createElFgColor_ = function createElFgColor_() {
  15976. var legendId = "captions-text-legend-" + this.id_;
  15977. return ['<fieldset class="vjs-fg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Text'), '</legend>', this.createElSelect_('color', legendId), '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
  15978. }
  15979. /**
  15980. * Create background color element for the component
  15981. *
  15982. * @return {string}
  15983. * An HTML string.
  15984. *
  15985. * @private
  15986. */
  15987. ;
  15988. _proto.createElBgColor_ = function createElBgColor_() {
  15989. var legendId = "captions-background-" + this.id_;
  15990. return ['<fieldset class="vjs-bg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Background'), '</legend>', this.createElSelect_('backgroundColor', legendId), '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
  15991. }
  15992. /**
  15993. * Create window color element for the component
  15994. *
  15995. * @return {string}
  15996. * An HTML string.
  15997. *
  15998. * @private
  15999. */
  16000. ;
  16001. _proto.createElWinColor_ = function createElWinColor_() {
  16002. var legendId = "captions-window-" + this.id_;
  16003. return ['<fieldset class="vjs-window-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Window'), '</legend>', this.createElSelect_('windowColor', legendId), '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
  16004. }
  16005. /**
  16006. * Create color elements for the component
  16007. *
  16008. * @return {Element}
  16009. * The element that was created
  16010. *
  16011. * @private
  16012. */
  16013. ;
  16014. _proto.createElColors_ = function createElColors_() {
  16015. return createEl('div', {
  16016. className: 'vjs-track-settings-colors',
  16017. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  16018. });
  16019. }
  16020. /**
  16021. * Create font elements for the component
  16022. *
  16023. * @return {Element}
  16024. * The element that was created.
  16025. *
  16026. * @private
  16027. */
  16028. ;
  16029. _proto.createElFont_ = function createElFont_() {
  16030. return createEl('div', {
  16031. className: 'vjs-track-settings-font',
  16032. 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('')
  16033. });
  16034. }
  16035. /**
  16036. * Create controls for the component
  16037. *
  16038. * @return {Element}
  16039. * The element that was created.
  16040. *
  16041. * @private
  16042. */
  16043. ;
  16044. _proto.createElControls_ = function createElControls_() {
  16045. var defaultsDescription = this.localize('restore all settings to the default values');
  16046. return createEl('div', {
  16047. className: 'vjs-track-settings-controls',
  16048. 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('')
  16049. });
  16050. };
  16051. _proto.content = function content() {
  16052. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  16053. };
  16054. _proto.label = function label() {
  16055. return this.localize('Caption Settings Dialog');
  16056. };
  16057. _proto.description = function description() {
  16058. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  16059. };
  16060. _proto.buildCSSClass = function buildCSSClass() {
  16061. return _ModalDialog.prototype.buildCSSClass.call(this) + ' vjs-text-track-settings';
  16062. }
  16063. /**
  16064. * Gets an object of text track settings (or null).
  16065. *
  16066. * @return {Object}
  16067. * An object with config values parsed from the DOM or localStorage.
  16068. */
  16069. ;
  16070. _proto.getValues = function getValues() {
  16071. var _this3 = this;
  16072. return reduce(selectConfigs, function (accum, config, key) {
  16073. var value = getSelectedOptionValue(_this3.$(config.selector), config.parser);
  16074. if (value !== undefined) {
  16075. accum[key] = value;
  16076. }
  16077. return accum;
  16078. }, {});
  16079. }
  16080. /**
  16081. * Sets text track settings from an object of values.
  16082. *
  16083. * @param {Object} values
  16084. * An object with config values parsed from the DOM or localStorage.
  16085. */
  16086. ;
  16087. _proto.setValues = function setValues(values) {
  16088. var _this4 = this;
  16089. each(selectConfigs, function (config, key) {
  16090. setSelectedOption(_this4.$(config.selector), values[key], config.parser);
  16091. });
  16092. }
  16093. /**
  16094. * Sets all `<select>` elements to their default values.
  16095. */
  16096. ;
  16097. _proto.setDefaults = function setDefaults() {
  16098. var _this5 = this;
  16099. each(selectConfigs, function (config) {
  16100. var index = config.hasOwnProperty('default') ? config["default"] : 0;
  16101. _this5.$(config.selector).selectedIndex = index;
  16102. });
  16103. }
  16104. /**
  16105. * Restore texttrack settings from localStorage
  16106. */
  16107. ;
  16108. _proto.restoreSettings = function restoreSettings() {
  16109. var values;
  16110. try {
  16111. values = JSON.parse(window__default['default'].localStorage.getItem(LOCAL_STORAGE_KEY$1));
  16112. } catch (err) {
  16113. log$1.warn(err);
  16114. }
  16115. if (values) {
  16116. this.setValues(values);
  16117. }
  16118. }
  16119. /**
  16120. * Save text track settings to localStorage
  16121. */
  16122. ;
  16123. _proto.saveSettings = function saveSettings() {
  16124. if (!this.options_.persistTextTrackSettings) {
  16125. return;
  16126. }
  16127. var values = this.getValues();
  16128. try {
  16129. if (Object.keys(values).length) {
  16130. window__default['default'].localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  16131. } else {
  16132. window__default['default'].localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  16133. }
  16134. } catch (err) {
  16135. log$1.warn(err);
  16136. }
  16137. }
  16138. /**
  16139. * Update display of text track settings
  16140. */
  16141. ;
  16142. _proto.updateDisplay = function updateDisplay() {
  16143. var ttDisplay = this.player_.getChild('textTrackDisplay');
  16144. if (ttDisplay) {
  16145. ttDisplay.updateDisplay();
  16146. }
  16147. }
  16148. /**
  16149. * conditionally blur the element and refocus the captions button
  16150. *
  16151. * @private
  16152. */
  16153. ;
  16154. _proto.conditionalBlur_ = function conditionalBlur_() {
  16155. this.previouslyActiveEl_ = null;
  16156. var cb = this.player_.controlBar;
  16157. var subsCapsBtn = cb && cb.subsCapsButton;
  16158. var ccBtn = cb && cb.captionsButton;
  16159. if (subsCapsBtn) {
  16160. subsCapsBtn.focus();
  16161. } else if (ccBtn) {
  16162. ccBtn.focus();
  16163. }
  16164. };
  16165. return TextTrackSettings;
  16166. }(ModalDialog);
  16167. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  16168. /**
  16169. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  16170. *
  16171. * 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}.
  16172. *
  16173. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  16174. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  16175. * @example <caption>How to disable the resize manager</caption>
  16176. * const player = videojs('#vid', {
  16177. * resizeManager: false
  16178. * });
  16179. *
  16180. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  16181. *
  16182. * @extends Component
  16183. */
  16184. var ResizeManager = /*#__PURE__*/function (_Component) {
  16185. _inheritsLoose__default['default'](ResizeManager, _Component);
  16186. /**
  16187. * Create the ResizeManager.
  16188. *
  16189. * @param {Object} player
  16190. * The `Player` that this class should be attached to.
  16191. *
  16192. * @param {Object} [options]
  16193. * The key/value store of ResizeManager options.
  16194. *
  16195. * @param {Object} [options.ResizeObserver]
  16196. * A polyfill for ResizeObserver can be passed in here.
  16197. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  16198. */
  16199. function ResizeManager(player, options) {
  16200. var _this;
  16201. var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window__default['default'].ResizeObserver; // if `null` was passed, we want to disable the ResizeObserver
  16202. if (options.ResizeObserver === null) {
  16203. RESIZE_OBSERVER_AVAILABLE = false;
  16204. } // Only create an element when ResizeObserver isn't available
  16205. var options_ = mergeOptions$3({
  16206. createEl: !RESIZE_OBSERVER_AVAILABLE,
  16207. reportTouchActivity: false
  16208. }, options);
  16209. _this = _Component.call(this, player, options_) || this;
  16210. _this.ResizeObserver = options.ResizeObserver || window__default['default'].ResizeObserver;
  16211. _this.loadListener_ = null;
  16212. _this.resizeObserver_ = null;
  16213. _this.debouncedHandler_ = debounce(function () {
  16214. _this.resizeHandler();
  16215. }, 100, false, _assertThisInitialized__default['default'](_this));
  16216. if (RESIZE_OBSERVER_AVAILABLE) {
  16217. _this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_);
  16218. _this.resizeObserver_.observe(player.el());
  16219. } else {
  16220. _this.loadListener_ = function () {
  16221. if (!_this.el_ || !_this.el_.contentWindow) {
  16222. return;
  16223. }
  16224. var debouncedHandler_ = _this.debouncedHandler_;
  16225. var unloadListener_ = _this.unloadListener_ = function () {
  16226. off(this, 'resize', debouncedHandler_);
  16227. off(this, 'unload', unloadListener_);
  16228. unloadListener_ = null;
  16229. }; // safari and edge can unload the iframe before resizemanager dispose
  16230. // we have to dispose of event handlers correctly before that happens
  16231. on(_this.el_.contentWindow, 'unload', unloadListener_);
  16232. on(_this.el_.contentWindow, 'resize', debouncedHandler_);
  16233. };
  16234. _this.one('load', _this.loadListener_);
  16235. }
  16236. return _this;
  16237. }
  16238. var _proto = ResizeManager.prototype;
  16239. _proto.createEl = function createEl() {
  16240. return _Component.prototype.createEl.call(this, 'iframe', {
  16241. className: 'vjs-resize-manager',
  16242. tabIndex: -1,
  16243. title: this.localize('No content')
  16244. }, {
  16245. 'aria-hidden': 'true'
  16246. });
  16247. }
  16248. /**
  16249. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  16250. *
  16251. * @fires Player#playerresize
  16252. */
  16253. ;
  16254. _proto.resizeHandler = function resizeHandler() {
  16255. /**
  16256. * Called when the player size has changed
  16257. *
  16258. * @event Player#playerresize
  16259. * @type {EventTarget~Event}
  16260. */
  16261. // make sure player is still around to trigger
  16262. // prevents this from causing an error after dispose
  16263. if (!this.player_ || !this.player_.trigger) {
  16264. return;
  16265. }
  16266. this.player_.trigger('playerresize');
  16267. };
  16268. _proto.dispose = function dispose() {
  16269. if (this.debouncedHandler_) {
  16270. this.debouncedHandler_.cancel();
  16271. }
  16272. if (this.resizeObserver_) {
  16273. if (this.player_.el()) {
  16274. this.resizeObserver_.unobserve(this.player_.el());
  16275. }
  16276. this.resizeObserver_.disconnect();
  16277. }
  16278. if (this.loadListener_) {
  16279. this.off('load', this.loadListener_);
  16280. }
  16281. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  16282. this.unloadListener_.call(this.el_.contentWindow);
  16283. }
  16284. this.ResizeObserver = null;
  16285. this.resizeObserver = null;
  16286. this.debouncedHandler_ = null;
  16287. this.loadListener_ = null;
  16288. _Component.prototype.dispose.call(this);
  16289. };
  16290. return ResizeManager;
  16291. }(Component$1);
  16292. Component$1.registerComponent('ResizeManager', ResizeManager);
  16293. var defaults = {
  16294. trackingThreshold: 20,
  16295. liveTolerance: 15
  16296. };
  16297. /*
  16298. track when we are at the live edge, and other helpers for live playback */
  16299. /**
  16300. * A class for checking live current time and determining when the player
  16301. * is at or behind the live edge.
  16302. */
  16303. var LiveTracker = /*#__PURE__*/function (_Component) {
  16304. _inheritsLoose__default['default'](LiveTracker, _Component);
  16305. /**
  16306. * Creates an instance of this class.
  16307. *
  16308. * @param {Player} player
  16309. * The `Player` that this class should be attached to.
  16310. *
  16311. * @param {Object} [options]
  16312. * The key/value store of player options.
  16313. *
  16314. * @param {number} [options.trackingThreshold=20]
  16315. * Number of seconds of live window (seekableEnd - seekableStart) that
  16316. * media needs to have before the liveui will be shown.
  16317. *
  16318. * @param {number} [options.liveTolerance=15]
  16319. * Number of seconds behind live that we have to be
  16320. * before we will be considered non-live. Note that this will only
  16321. * be used when playing at the live edge. This allows large seekable end
  16322. * changes to not effect wether we are live or not.
  16323. */
  16324. function LiveTracker(player, options) {
  16325. var _this;
  16326. // LiveTracker does not need an element
  16327. var options_ = mergeOptions$3(defaults, options, {
  16328. createEl: false
  16329. });
  16330. _this = _Component.call(this, player, options_) || this;
  16331. _this.handleVisibilityChange_ = function (e) {
  16332. return _this.handleVisibilityChange(e);
  16333. };
  16334. _this.trackLiveHandler_ = function () {
  16335. return _this.trackLive_();
  16336. };
  16337. _this.handlePlay_ = function (e) {
  16338. return _this.handlePlay(e);
  16339. };
  16340. _this.handleFirstTimeupdate_ = function (e) {
  16341. return _this.handleFirstTimeupdate(e);
  16342. };
  16343. _this.handleSeeked_ = function (e) {
  16344. return _this.handleSeeked(e);
  16345. };
  16346. _this.seekToLiveEdge_ = function (e) {
  16347. return _this.seekToLiveEdge(e);
  16348. };
  16349. _this.reset_();
  16350. _this.on(_this.player_, 'durationchange', function (e) {
  16351. return _this.handleDurationchange(e);
  16352. }); // we should try to toggle tracking on canplay as native playback engines, like Safari
  16353. // may not have the proper values for things like seekableEnd until then
  16354. _this.on(_this.player_, 'canplay', function () {
  16355. return _this.toggleTracking();
  16356. }); // we don't need to track live playback if the document is hidden,
  16357. // also, tracking when the document is hidden can
  16358. // cause the CPU to spike and eventually crash the page on IE11.
  16359. if (IE_VERSION && 'hidden' in document__default['default'] && 'visibilityState' in document__default['default']) {
  16360. _this.on(document__default['default'], 'visibilitychange', _this.handleVisibilityChange_);
  16361. }
  16362. return _this;
  16363. }
  16364. /**
  16365. * toggle tracking based on document visiblility
  16366. */
  16367. var _proto = LiveTracker.prototype;
  16368. _proto.handleVisibilityChange = function handleVisibilityChange() {
  16369. if (this.player_.duration() !== Infinity) {
  16370. return;
  16371. }
  16372. if (document__default['default'].hidden) {
  16373. this.stopTracking();
  16374. } else {
  16375. this.startTracking();
  16376. }
  16377. }
  16378. /**
  16379. * all the functionality for tracking when seek end changes
  16380. * and for tracking how far past seek end we should be
  16381. */
  16382. ;
  16383. _proto.trackLive_ = function trackLive_() {
  16384. var seekable = this.player_.seekable(); // skip undefined seekable
  16385. if (!seekable || !seekable.length) {
  16386. return;
  16387. }
  16388. var newTime = Number(window__default['default'].performance.now().toFixed(4));
  16389. var deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  16390. this.lastTime_ = newTime;
  16391. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  16392. var liveCurrentTime = this.liveCurrentTime();
  16393. var currentTime = this.player_.currentTime(); // we are behind live if any are true
  16394. // 1. the player is paused
  16395. // 2. the user seeked to a location 2 seconds away from live
  16396. // 3. the difference between live and current time is greater
  16397. // liveTolerance which defaults to 15s
  16398. var isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance; // we cannot be behind if
  16399. // 1. until we have not seen a timeupdate yet
  16400. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  16401. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  16402. isBehind = false;
  16403. }
  16404. if (isBehind !== this.behindLiveEdge_) {
  16405. this.behindLiveEdge_ = isBehind;
  16406. this.trigger('liveedgechange');
  16407. }
  16408. }
  16409. /**
  16410. * handle a durationchange event on the player
  16411. * and start/stop tracking accordingly.
  16412. */
  16413. ;
  16414. _proto.handleDurationchange = function handleDurationchange() {
  16415. this.toggleTracking();
  16416. }
  16417. /**
  16418. * start/stop tracking
  16419. */
  16420. ;
  16421. _proto.toggleTracking = function toggleTracking() {
  16422. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  16423. if (this.player_.options_.liveui) {
  16424. this.player_.addClass('vjs-liveui');
  16425. }
  16426. this.startTracking();
  16427. } else {
  16428. this.player_.removeClass('vjs-liveui');
  16429. this.stopTracking();
  16430. }
  16431. }
  16432. /**
  16433. * start tracking live playback
  16434. */
  16435. ;
  16436. _proto.startTracking = function startTracking() {
  16437. if (this.isTracking()) {
  16438. return;
  16439. } // If we haven't seen a timeupdate, we need to check whether playback
  16440. // began before this component started tracking. This can happen commonly
  16441. // when using autoplay.
  16442. if (!this.timeupdateSeen_) {
  16443. this.timeupdateSeen_ = this.player_.hasStarted();
  16444. }
  16445. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  16446. this.trackLive_();
  16447. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16448. if (!this.timeupdateSeen_) {
  16449. this.one(this.player_, 'play', this.handlePlay_);
  16450. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16451. } else {
  16452. this.on(this.player_, 'seeked', this.handleSeeked_);
  16453. }
  16454. }
  16455. /**
  16456. * handle the first timeupdate on the player if it wasn't already playing
  16457. * when live tracker started tracking.
  16458. */
  16459. ;
  16460. _proto.handleFirstTimeupdate = function handleFirstTimeupdate() {
  16461. this.timeupdateSeen_ = true;
  16462. this.on(this.player_, 'seeked', this.handleSeeked_);
  16463. }
  16464. /**
  16465. * Keep track of what time a seek starts, and listen for seeked
  16466. * to find where a seek ends.
  16467. */
  16468. ;
  16469. _proto.handleSeeked = function handleSeeked() {
  16470. var timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  16471. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  16472. this.nextSeekedFromUser_ = false;
  16473. this.trackLive_();
  16474. }
  16475. /**
  16476. * handle the first play on the player, and make sure that we seek
  16477. * right to the live edge.
  16478. */
  16479. ;
  16480. _proto.handlePlay = function handlePlay() {
  16481. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16482. }
  16483. /**
  16484. * Stop tracking, and set all internal variables to
  16485. * their initial value.
  16486. */
  16487. ;
  16488. _proto.reset_ = function reset_() {
  16489. this.lastTime_ = -1;
  16490. this.pastSeekEnd_ = 0;
  16491. this.lastSeekEnd_ = -1;
  16492. this.behindLiveEdge_ = true;
  16493. this.timeupdateSeen_ = false;
  16494. this.seekedBehindLive_ = false;
  16495. this.nextSeekedFromUser_ = false;
  16496. this.clearInterval(this.trackingInterval_);
  16497. this.trackingInterval_ = null;
  16498. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16499. this.off(this.player_, 'seeked', this.handleSeeked_);
  16500. this.off(this.player_, 'play', this.handlePlay_);
  16501. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16502. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16503. }
  16504. /**
  16505. * The next seeked event is from the user. Meaning that any seek
  16506. * > 2s behind live will be considered behind live for real and
  16507. * liveTolerance will be ignored.
  16508. */
  16509. ;
  16510. _proto.nextSeekedFromUser = function nextSeekedFromUser() {
  16511. this.nextSeekedFromUser_ = true;
  16512. }
  16513. /**
  16514. * stop tracking live playback
  16515. */
  16516. ;
  16517. _proto.stopTracking = function stopTracking() {
  16518. if (!this.isTracking()) {
  16519. return;
  16520. }
  16521. this.reset_();
  16522. this.trigger('liveedgechange');
  16523. }
  16524. /**
  16525. * A helper to get the player seekable end
  16526. * so that we don't have to null check everywhere
  16527. *
  16528. * @return {number}
  16529. * The furthest seekable end or Infinity.
  16530. */
  16531. ;
  16532. _proto.seekableEnd = function seekableEnd() {
  16533. var seekable = this.player_.seekable();
  16534. var seekableEnds = [];
  16535. var i = seekable ? seekable.length : 0;
  16536. while (i--) {
  16537. seekableEnds.push(seekable.end(i));
  16538. } // grab the furthest seekable end after sorting, or if there are none
  16539. // default to Infinity
  16540. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  16541. }
  16542. /**
  16543. * A helper to get the player seekable start
  16544. * so that we don't have to null check everywhere
  16545. *
  16546. * @return {number}
  16547. * The earliest seekable start or 0.
  16548. */
  16549. ;
  16550. _proto.seekableStart = function seekableStart() {
  16551. var seekable = this.player_.seekable();
  16552. var seekableStarts = [];
  16553. var i = seekable ? seekable.length : 0;
  16554. while (i--) {
  16555. seekableStarts.push(seekable.start(i));
  16556. } // grab the first seekable start after sorting, or if there are none
  16557. // default to 0
  16558. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  16559. }
  16560. /**
  16561. * Get the live time window aka
  16562. * the amount of time between seekable start and
  16563. * live current time.
  16564. *
  16565. * @return {number}
  16566. * The amount of seconds that are seekable in
  16567. * the live video.
  16568. */
  16569. ;
  16570. _proto.liveWindow = function liveWindow() {
  16571. var liveCurrentTime = this.liveCurrentTime(); // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  16572. if (liveCurrentTime === Infinity) {
  16573. return 0;
  16574. }
  16575. return liveCurrentTime - this.seekableStart();
  16576. }
  16577. /**
  16578. * Determines if the player is live, only checks if this component
  16579. * is tracking live playback or not
  16580. *
  16581. * @return {boolean}
  16582. * Wether liveTracker is tracking
  16583. */
  16584. ;
  16585. _proto.isLive = function isLive() {
  16586. return this.isTracking();
  16587. }
  16588. /**
  16589. * Determines if currentTime is at the live edge and won't fall behind
  16590. * on each seekableendchange
  16591. *
  16592. * @return {boolean}
  16593. * Wether playback is at the live edge
  16594. */
  16595. ;
  16596. _proto.atLiveEdge = function atLiveEdge() {
  16597. return !this.behindLiveEdge();
  16598. }
  16599. /**
  16600. * get what we expect the live current time to be
  16601. *
  16602. * @return {number}
  16603. * The expected live current time
  16604. */
  16605. ;
  16606. _proto.liveCurrentTime = function liveCurrentTime() {
  16607. return this.pastSeekEnd() + this.seekableEnd();
  16608. }
  16609. /**
  16610. * The number of seconds that have occured after seekable end
  16611. * changed. This will be reset to 0 once seekable end changes.
  16612. *
  16613. * @return {number}
  16614. * Seconds past the current seekable end
  16615. */
  16616. ;
  16617. _proto.pastSeekEnd = function pastSeekEnd() {
  16618. var seekableEnd = this.seekableEnd();
  16619. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  16620. this.pastSeekEnd_ = 0;
  16621. }
  16622. this.lastSeekEnd_ = seekableEnd;
  16623. return this.pastSeekEnd_;
  16624. }
  16625. /**
  16626. * If we are currently behind the live edge, aka currentTime will be
  16627. * behind on a seekableendchange
  16628. *
  16629. * @return {boolean}
  16630. * If we are behind the live edge
  16631. */
  16632. ;
  16633. _proto.behindLiveEdge = function behindLiveEdge() {
  16634. return this.behindLiveEdge_;
  16635. }
  16636. /**
  16637. * Wether live tracker is currently tracking or not.
  16638. */
  16639. ;
  16640. _proto.isTracking = function isTracking() {
  16641. return typeof this.trackingInterval_ === 'number';
  16642. }
  16643. /**
  16644. * Seek to the live edge if we are behind the live edge
  16645. */
  16646. ;
  16647. _proto.seekToLiveEdge = function seekToLiveEdge() {
  16648. this.seekedBehindLive_ = false;
  16649. if (this.atLiveEdge()) {
  16650. return;
  16651. }
  16652. this.nextSeekedFromUser_ = false;
  16653. this.player_.currentTime(this.liveCurrentTime());
  16654. }
  16655. /**
  16656. * Dispose of liveTracker
  16657. */
  16658. ;
  16659. _proto.dispose = function dispose() {
  16660. this.off(document__default['default'], 'visibilitychange', this.handleVisibilityChange_);
  16661. this.stopTracking();
  16662. _Component.prototype.dispose.call(this);
  16663. };
  16664. return LiveTracker;
  16665. }(Component$1);
  16666. Component$1.registerComponent('LiveTracker', LiveTracker);
  16667. /**
  16668. * This function is used to fire a sourceset when there is something
  16669. * similar to `mediaEl.load()` being called. It will try to find the source via
  16670. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  16671. * with the source that was found or empty string if we cannot know. If it cannot
  16672. * find a source then `sourceset` will not be fired.
  16673. *
  16674. * @param {Html5} tech
  16675. * The tech object that sourceset was setup on
  16676. *
  16677. * @return {boolean}
  16678. * returns false if the sourceset was not fired and true otherwise.
  16679. */
  16680. var sourcesetLoad = function sourcesetLoad(tech) {
  16681. var el = tech.el(); // if `el.src` is set, that source will be loaded.
  16682. if (el.hasAttribute('src')) {
  16683. tech.triggerSourceset(el.src);
  16684. return true;
  16685. }
  16686. /**
  16687. * Since there isn't a src property on the media element, source elements will be used for
  16688. * implementing the source selection algorithm. This happens asynchronously and
  16689. * for most cases were there is more than one source we cannot tell what source will
  16690. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  16691. * going to do that. There are three special cases that we do handle here though:
  16692. *
  16693. * 1. If there are no sources, do not fire `sourceset`.
  16694. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  16695. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  16696. * That will be our src.
  16697. */
  16698. var sources = tech.$$('source');
  16699. var srcUrls = [];
  16700. var src = ''; // if there are no sources, do not fire sourceset
  16701. if (!sources.length) {
  16702. return false;
  16703. } // only count valid/non-duplicate source elements
  16704. for (var i = 0; i < sources.length; i++) {
  16705. var url = sources[i].src;
  16706. if (url && srcUrls.indexOf(url) === -1) {
  16707. srcUrls.push(url);
  16708. }
  16709. } // there were no valid sources
  16710. if (!srcUrls.length) {
  16711. return false;
  16712. } // there is only one valid source element url
  16713. // use that
  16714. if (srcUrls.length === 1) {
  16715. src = srcUrls[0];
  16716. }
  16717. tech.triggerSourceset(src);
  16718. return true;
  16719. };
  16720. /**
  16721. * our implementation of an `innerHTML` descriptor for browsers
  16722. * that do not have one.
  16723. */
  16724. var innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  16725. get: function get() {
  16726. return this.cloneNode(true).innerHTML;
  16727. },
  16728. set: function set(v) {
  16729. // make a dummy node to use innerHTML on
  16730. var dummy = document__default['default'].createElement(this.nodeName.toLowerCase()); // set innerHTML to the value provided
  16731. dummy.innerHTML = v; // make a document fragment to hold the nodes from dummy
  16732. var docFrag = document__default['default'].createDocumentFragment(); // copy all of the nodes created by the innerHTML on dummy
  16733. // to the document fragment
  16734. while (dummy.childNodes.length) {
  16735. docFrag.appendChild(dummy.childNodes[0]);
  16736. } // remove content
  16737. this.innerText = ''; // now we add all of that html in one by appending the
  16738. // document fragment. This is how innerHTML does it.
  16739. window__default['default'].Element.prototype.appendChild.call(this, docFrag); // then return the result that innerHTML's setter would
  16740. return this.innerHTML;
  16741. }
  16742. });
  16743. /**
  16744. * Get a property descriptor given a list of priorities and the
  16745. * property to get.
  16746. */
  16747. var getDescriptor = function getDescriptor(priority, prop) {
  16748. var descriptor = {};
  16749. for (var i = 0; i < priority.length; i++) {
  16750. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  16751. if (descriptor && descriptor.set && descriptor.get) {
  16752. break;
  16753. }
  16754. }
  16755. descriptor.enumerable = true;
  16756. descriptor.configurable = true;
  16757. return descriptor;
  16758. };
  16759. var getInnerHTMLDescriptor = function getInnerHTMLDescriptor(tech) {
  16760. return getDescriptor([tech.el(), window__default['default'].HTMLMediaElement.prototype, window__default['default'].Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  16761. };
  16762. /**
  16763. * Patches browser internal functions so that we can tell synchronously
  16764. * if a `<source>` was appended to the media element. For some reason this
  16765. * causes a `sourceset` if the the media element is ready and has no source.
  16766. * This happens when:
  16767. * - The page has just loaded and the media element does not have a source.
  16768. * - The media element was emptied of all sources, then `load()` was called.
  16769. *
  16770. * It does this by patching the following functions/properties when they are supported:
  16771. *
  16772. * - `append()` - can be used to add a `<source>` element to the media element
  16773. * - `appendChild()` - can be used to add a `<source>` element to the media element
  16774. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  16775. * - `innerHTML` - can be used to add a `<source>` element to the media element
  16776. *
  16777. * @param {Html5} tech
  16778. * The tech object that sourceset is being setup on.
  16779. */
  16780. var firstSourceWatch = function firstSourceWatch(tech) {
  16781. var el = tech.el(); // make sure firstSourceWatch isn't setup twice.
  16782. if (el.resetSourceWatch_) {
  16783. return;
  16784. }
  16785. var old = {};
  16786. var innerDescriptor = getInnerHTMLDescriptor(tech);
  16787. var appendWrapper = function appendWrapper(appendFn) {
  16788. return function () {
  16789. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  16790. args[_key] = arguments[_key];
  16791. }
  16792. var retval = appendFn.apply(el, args);
  16793. sourcesetLoad(tech);
  16794. return retval;
  16795. };
  16796. };
  16797. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(function (k) {
  16798. if (!el[k]) {
  16799. return;
  16800. } // store the old function
  16801. old[k] = el[k]; // call the old function with a sourceset if a source
  16802. // was loaded
  16803. el[k] = appendWrapper(old[k]);
  16804. });
  16805. Object.defineProperty(el, 'innerHTML', mergeOptions$3(innerDescriptor, {
  16806. set: appendWrapper(innerDescriptor.set)
  16807. }));
  16808. el.resetSourceWatch_ = function () {
  16809. el.resetSourceWatch_ = null;
  16810. Object.keys(old).forEach(function (k) {
  16811. el[k] = old[k];
  16812. });
  16813. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  16814. }; // on the first sourceset, we need to revert our changes
  16815. tech.one('sourceset', el.resetSourceWatch_);
  16816. };
  16817. /**
  16818. * our implementation of a `src` descriptor for browsers
  16819. * that do not have one.
  16820. */
  16821. var srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  16822. get: function get() {
  16823. if (this.hasAttribute('src')) {
  16824. return getAbsoluteURL(window__default['default'].Element.prototype.getAttribute.call(this, 'src'));
  16825. }
  16826. return '';
  16827. },
  16828. set: function set(v) {
  16829. window__default['default'].Element.prototype.setAttribute.call(this, 'src', v);
  16830. return v;
  16831. }
  16832. });
  16833. var getSrcDescriptor = function getSrcDescriptor(tech) {
  16834. return getDescriptor([tech.el(), window__default['default'].HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  16835. };
  16836. /**
  16837. * setup `sourceset` handling on the `Html5` tech. This function
  16838. * patches the following element properties/functions:
  16839. *
  16840. * - `src` - to determine when `src` is set
  16841. * - `setAttribute()` - to determine when `src` is set
  16842. * - `load()` - this re-triggers the source selection algorithm, and can
  16843. * cause a sourceset.
  16844. *
  16845. * If there is no source when we are adding `sourceset` support or during a `load()`
  16846. * we also patch the functions listed in `firstSourceWatch`.
  16847. *
  16848. * @param {Html5} tech
  16849. * The tech to patch
  16850. */
  16851. var setupSourceset = function setupSourceset(tech) {
  16852. if (!tech.featuresSourceset) {
  16853. return;
  16854. }
  16855. var el = tech.el(); // make sure sourceset isn't setup twice.
  16856. if (el.resetSourceset_) {
  16857. return;
  16858. }
  16859. var srcDescriptor = getSrcDescriptor(tech);
  16860. var oldSetAttribute = el.setAttribute;
  16861. var oldLoad = el.load;
  16862. Object.defineProperty(el, 'src', mergeOptions$3(srcDescriptor, {
  16863. set: function set(v) {
  16864. var retval = srcDescriptor.set.call(el, v); // we use the getter here to get the actual value set on src
  16865. tech.triggerSourceset(el.src);
  16866. return retval;
  16867. }
  16868. }));
  16869. el.setAttribute = function (n, v) {
  16870. var retval = oldSetAttribute.call(el, n, v);
  16871. if (/src/i.test(n)) {
  16872. tech.triggerSourceset(el.src);
  16873. }
  16874. return retval;
  16875. };
  16876. el.load = function () {
  16877. var retval = oldLoad.call(el); // if load was called, but there was no source to fire
  16878. // sourceset on. We have to watch for a source append
  16879. // as that can trigger a `sourceset` when the media element
  16880. // has no source
  16881. if (!sourcesetLoad(tech)) {
  16882. tech.triggerSourceset('');
  16883. firstSourceWatch(tech);
  16884. }
  16885. return retval;
  16886. };
  16887. if (el.currentSrc) {
  16888. tech.triggerSourceset(el.currentSrc);
  16889. } else if (!sourcesetLoad(tech)) {
  16890. firstSourceWatch(tech);
  16891. }
  16892. el.resetSourceset_ = function () {
  16893. el.resetSourceset_ = null;
  16894. el.load = oldLoad;
  16895. el.setAttribute = oldSetAttribute;
  16896. Object.defineProperty(el, 'src', srcDescriptor);
  16897. if (el.resetSourceWatch_) {
  16898. el.resetSourceWatch_();
  16899. }
  16900. };
  16901. };
  16902. /**
  16903. * Object.defineProperty but "lazy", which means that the value is only set after
  16904. * it retrieved the first time, rather than being set right away.
  16905. *
  16906. * @param {Object} obj the object to set the property on
  16907. * @param {string} key the key for the property to set
  16908. * @param {Function} getValue the function used to get the value when it is needed.
  16909. * @param {boolean} setter wether a setter shoould be allowed or not
  16910. */
  16911. var defineLazyProperty = function defineLazyProperty(obj, key, getValue, setter) {
  16912. if (setter === void 0) {
  16913. setter = true;
  16914. }
  16915. var set = function set(value) {
  16916. return Object.defineProperty(obj, key, {
  16917. value: value,
  16918. enumerable: true,
  16919. writable: true
  16920. });
  16921. };
  16922. var options = {
  16923. configurable: true,
  16924. enumerable: true,
  16925. get: function get() {
  16926. var value = getValue();
  16927. set(value);
  16928. return value;
  16929. }
  16930. };
  16931. if (setter) {
  16932. options.set = set;
  16933. }
  16934. return Object.defineProperty(obj, key, options);
  16935. };
  16936. /**
  16937. * HTML5 Media Controller - Wrapper for HTML5 Media API
  16938. *
  16939. * @mixes Tech~SourceHandlerAdditions
  16940. * @extends Tech
  16941. */
  16942. var Html5 = /*#__PURE__*/function (_Tech) {
  16943. _inheritsLoose__default['default'](Html5, _Tech);
  16944. /**
  16945. * Create an instance of this Tech.
  16946. *
  16947. * @param {Object} [options]
  16948. * The key/value store of player options.
  16949. *
  16950. * @param {Component~ReadyCallback} ready
  16951. * Callback function to call when the `HTML5` Tech is ready.
  16952. */
  16953. function Html5(options, ready) {
  16954. var _this;
  16955. _this = _Tech.call(this, options, ready) || this;
  16956. var source = options.source;
  16957. var crossoriginTracks = false;
  16958. _this.featuresVideoFrameCallback = _this.featuresVideoFrameCallback && _this.el_.tagName === 'VIDEO'; // Set the source if one is provided
  16959. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  16960. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  16961. // anyway so the error gets fired.
  16962. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  16963. _this.setSource(source);
  16964. } else {
  16965. _this.handleLateInit_(_this.el_);
  16966. } // setup sourceset after late sourceset/init
  16967. if (options.enableSourceset) {
  16968. _this.setupSourcesetHandling_();
  16969. }
  16970. _this.isScrubbing_ = false;
  16971. if (_this.el_.hasChildNodes()) {
  16972. var nodes = _this.el_.childNodes;
  16973. var nodesLength = nodes.length;
  16974. var removeNodes = [];
  16975. while (nodesLength--) {
  16976. var node = nodes[nodesLength];
  16977. var nodeName = node.nodeName.toLowerCase();
  16978. if (nodeName === 'track') {
  16979. if (!_this.featuresNativeTextTracks) {
  16980. // Empty video tag tracks so the built-in player doesn't use them also.
  16981. // This may not be fast enough to stop HTML5 browsers from reading the tags
  16982. // so we'll need to turn off any default tracks if we're manually doing
  16983. // captions and subtitles. videoElement.textTracks
  16984. removeNodes.push(node);
  16985. } else {
  16986. // store HTMLTrackElement and TextTrack to remote list
  16987. _this.remoteTextTrackEls().addTrackElement_(node);
  16988. _this.remoteTextTracks().addTrack(node.track);
  16989. _this.textTracks().addTrack(node.track);
  16990. if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  16991. crossoriginTracks = true;
  16992. }
  16993. }
  16994. }
  16995. }
  16996. for (var i = 0; i < removeNodes.length; i++) {
  16997. _this.el_.removeChild(removeNodes[i]);
  16998. }
  16999. }
  17000. _this.proxyNativeTracks_();
  17001. if (_this.featuresNativeTextTracks && crossoriginTracks) {
  17002. 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.');
  17003. } // prevent iOS Safari from disabling metadata text tracks during native playback
  17004. _this.restoreMetadataTracksInIOSNativePlayer_(); // Determine if native controls should be used
  17005. // Our goal should be to get the custom controls on mobile solid everywhere
  17006. // so we can remove this all together. Right now this will block custom
  17007. // controls on touch enabled laptops like the Chrome Pixel
  17008. if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
  17009. _this.setControls(true);
  17010. } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  17011. // into a `fullscreenchange` event
  17012. _this.proxyWebkitFullscreen_();
  17013. _this.triggerReady();
  17014. return _this;
  17015. }
  17016. /**
  17017. * Dispose of `HTML5` media element and remove all tracks.
  17018. */
  17019. var _proto = Html5.prototype;
  17020. _proto.dispose = function dispose() {
  17021. if (this.el_ && this.el_.resetSourceset_) {
  17022. this.el_.resetSourceset_();
  17023. }
  17024. Html5.disposeMediaElement(this.el_);
  17025. this.options_ = null; // tech will handle clearing of the emulated track list
  17026. _Tech.prototype.dispose.call(this);
  17027. }
  17028. /**
  17029. * Modify the media element so that we can detect when
  17030. * the source is changed. Fires `sourceset` just after the source has changed
  17031. */
  17032. ;
  17033. _proto.setupSourcesetHandling_ = function setupSourcesetHandling_() {
  17034. setupSourceset(this);
  17035. }
  17036. /**
  17037. * When a captions track is enabled in the iOS Safari native player, all other
  17038. * tracks are disabled (including metadata tracks), which nulls all of their
  17039. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  17040. * state in those cases so that cue points are not needlessly lost.
  17041. *
  17042. * @private
  17043. */
  17044. ;
  17045. _proto.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() {
  17046. var textTracks = this.textTracks();
  17047. var metadataTracksPreFullscreenState; // captures a snapshot of every metadata track's current state
  17048. var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot() {
  17049. metadataTracksPreFullscreenState = [];
  17050. for (var i = 0; i < textTracks.length; i++) {
  17051. var track = textTracks[i];
  17052. if (track.kind === 'metadata') {
  17053. metadataTracksPreFullscreenState.push({
  17054. track: track,
  17055. storedMode: track.mode
  17056. });
  17057. }
  17058. }
  17059. }; // snapshot each metadata track's initial state, and update the snapshot
  17060. // each time there is a track 'change' event
  17061. takeMetadataTrackSnapshot();
  17062. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  17063. this.on('dispose', function () {
  17064. return textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17065. });
  17066. var restoreTrackMode = function restoreTrackMode() {
  17067. for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  17068. var storedTrack = metadataTracksPreFullscreenState[i];
  17069. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  17070. storedTrack.track.mode = storedTrack.storedMode;
  17071. }
  17072. } // we only want this handler to be executed on the first 'change' event
  17073. textTracks.removeEventListener('change', restoreTrackMode);
  17074. }; // when we enter fullscreen playback, stop updating the snapshot and
  17075. // restore all track modes to their pre-fullscreen state
  17076. this.on('webkitbeginfullscreen', function () {
  17077. textTracks.removeEventListener('change', takeMetadataTrackSnapshot); // remove the listener before adding it just in case it wasn't previously removed
  17078. textTracks.removeEventListener('change', restoreTrackMode);
  17079. textTracks.addEventListener('change', restoreTrackMode);
  17080. }); // start updating the snapshot again after leaving fullscreen
  17081. this.on('webkitendfullscreen', function () {
  17082. // remove the listener before adding it just in case it wasn't previously removed
  17083. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17084. textTracks.addEventListener('change', takeMetadataTrackSnapshot); // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  17085. textTracks.removeEventListener('change', restoreTrackMode);
  17086. });
  17087. }
  17088. /**
  17089. * Attempt to force override of tracks for the given type
  17090. *
  17091. * @param {string} type - Track type to override, possible values include 'Audio',
  17092. * 'Video', and 'Text'.
  17093. * @param {boolean} override - If set to true native audio/video will be overridden,
  17094. * otherwise native audio/video will potentially be used.
  17095. * @private
  17096. */
  17097. ;
  17098. _proto.overrideNative_ = function overrideNative_(type, override) {
  17099. var _this2 = this;
  17100. // If there is no behavioral change don't add/remove listeners
  17101. if (override !== this["featuresNative" + type + "Tracks"]) {
  17102. return;
  17103. }
  17104. var lowerCaseType = type.toLowerCase();
  17105. if (this[lowerCaseType + "TracksListeners_"]) {
  17106. Object.keys(this[lowerCaseType + "TracksListeners_"]).forEach(function (eventName) {
  17107. var elTracks = _this2.el()[lowerCaseType + "Tracks"];
  17108. elTracks.removeEventListener(eventName, _this2[lowerCaseType + "TracksListeners_"][eventName]);
  17109. });
  17110. }
  17111. this["featuresNative" + type + "Tracks"] = !override;
  17112. this[lowerCaseType + "TracksListeners_"] = null;
  17113. this.proxyNativeTracksForType_(lowerCaseType);
  17114. }
  17115. /**
  17116. * Attempt to force override of native audio tracks.
  17117. *
  17118. * @param {boolean} override - If set to true native audio will be overridden,
  17119. * otherwise native audio will potentially be used.
  17120. */
  17121. ;
  17122. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks(override) {
  17123. this.overrideNative_('Audio', override);
  17124. }
  17125. /**
  17126. * Attempt to force override of native video tracks.
  17127. *
  17128. * @param {boolean} override - If set to true native video will be overridden,
  17129. * otherwise native video will potentially be used.
  17130. */
  17131. ;
  17132. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks(override) {
  17133. this.overrideNative_('Video', override);
  17134. }
  17135. /**
  17136. * Proxy native track list events for the given type to our track
  17137. * lists if the browser we are playing in supports that type of track list.
  17138. *
  17139. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  17140. * @private
  17141. */
  17142. ;
  17143. _proto.proxyNativeTracksForType_ = function proxyNativeTracksForType_(name) {
  17144. var _this3 = this;
  17145. var props = NORMAL[name];
  17146. var elTracks = this.el()[props.getterName];
  17147. var techTracks = this[props.getterName]();
  17148. if (!this["featuresNative" + props.capitalName + "Tracks"] || !elTracks || !elTracks.addEventListener) {
  17149. return;
  17150. }
  17151. var listeners = {
  17152. change: function change(e) {
  17153. var event = {
  17154. type: 'change',
  17155. target: techTracks,
  17156. currentTarget: techTracks,
  17157. srcElement: techTracks
  17158. };
  17159. techTracks.trigger(event); // if we are a text track change event, we should also notify the
  17160. // remote text track list. This can potentially cause a false positive
  17161. // if we were to get a change event on a non-remote track and
  17162. // we triggered the event on the remote text track list which doesn't
  17163. // contain that track. However, best practices mean looping through the
  17164. // list of tracks and searching for the appropriate mode value, so,
  17165. // this shouldn't pose an issue
  17166. if (name === 'text') {
  17167. _this3[REMOTE.remoteText.getterName]().trigger(event);
  17168. }
  17169. },
  17170. addtrack: function addtrack(e) {
  17171. techTracks.addTrack(e.track);
  17172. },
  17173. removetrack: function removetrack(e) {
  17174. techTracks.removeTrack(e.track);
  17175. }
  17176. };
  17177. var removeOldTracks = function removeOldTracks() {
  17178. var removeTracks = [];
  17179. for (var i = 0; i < techTracks.length; i++) {
  17180. var found = false;
  17181. for (var j = 0; j < elTracks.length; j++) {
  17182. if (elTracks[j] === techTracks[i]) {
  17183. found = true;
  17184. break;
  17185. }
  17186. }
  17187. if (!found) {
  17188. removeTracks.push(techTracks[i]);
  17189. }
  17190. }
  17191. while (removeTracks.length) {
  17192. techTracks.removeTrack(removeTracks.shift());
  17193. }
  17194. };
  17195. this[props.getterName + 'Listeners_'] = listeners;
  17196. Object.keys(listeners).forEach(function (eventName) {
  17197. var listener = listeners[eventName];
  17198. elTracks.addEventListener(eventName, listener);
  17199. _this3.on('dispose', function (e) {
  17200. return elTracks.removeEventListener(eventName, listener);
  17201. });
  17202. }); // Remove (native) tracks that are not used anymore
  17203. this.on('loadstart', removeOldTracks);
  17204. this.on('dispose', function (e) {
  17205. return _this3.off('loadstart', removeOldTracks);
  17206. });
  17207. }
  17208. /**
  17209. * Proxy all native track list events to our track lists if the browser we are playing
  17210. * in supports that type of track list.
  17211. *
  17212. * @private
  17213. */
  17214. ;
  17215. _proto.proxyNativeTracks_ = function proxyNativeTracks_() {
  17216. var _this4 = this;
  17217. NORMAL.names.forEach(function (name) {
  17218. _this4.proxyNativeTracksForType_(name);
  17219. });
  17220. }
  17221. /**
  17222. * Create the `Html5` Tech's DOM element.
  17223. *
  17224. * @return {Element}
  17225. * The element that gets created.
  17226. */
  17227. ;
  17228. _proto.createEl = function createEl() {
  17229. var el = this.options_.tag; // Check if this browser supports moving the element into the box.
  17230. // On the iPhone video will break if you move the element,
  17231. // So we have to create a brand new element.
  17232. // If we ingested the player div, we do not need to move the media element.
  17233. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  17234. // If the original tag is still there, clone and remove it.
  17235. if (el) {
  17236. var clone = el.cloneNode(true);
  17237. if (el.parentNode) {
  17238. el.parentNode.insertBefore(clone, el);
  17239. }
  17240. Html5.disposeMediaElement(el);
  17241. el = clone;
  17242. } else {
  17243. el = document__default['default'].createElement('video'); // determine if native controls should be used
  17244. var tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  17245. var attributes = mergeOptions$3({}, tagAttributes);
  17246. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  17247. delete attributes.controls;
  17248. }
  17249. setAttributes(el, assign(attributes, {
  17250. id: this.options_.techId,
  17251. "class": 'vjs-tech'
  17252. }));
  17253. }
  17254. el.playerId = this.options_.playerId;
  17255. }
  17256. if (typeof this.options_.preload !== 'undefined') {
  17257. setAttribute(el, 'preload', this.options_.preload);
  17258. }
  17259. if (this.options_.disablePictureInPicture !== undefined) {
  17260. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  17261. } // Update specific tag settings, in case they were overridden
  17262. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  17263. // when iOS/Safari or other browsers attempt to autoplay.
  17264. var settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  17265. for (var i = 0; i < settingsAttrs.length; i++) {
  17266. var attr = settingsAttrs[i];
  17267. var value = this.options_[attr];
  17268. if (typeof value !== 'undefined') {
  17269. if (value) {
  17270. setAttribute(el, attr, attr);
  17271. } else {
  17272. removeAttribute(el, attr);
  17273. }
  17274. el[attr] = value;
  17275. }
  17276. }
  17277. return el;
  17278. }
  17279. /**
  17280. * This will be triggered if the loadstart event has already fired, before videojs was
  17281. * ready. Two known examples of when this can happen are:
  17282. * 1. If we're loading the playback object after it has started loading
  17283. * 2. The media is already playing the (often with autoplay on) then
  17284. *
  17285. * This function will fire another loadstart so that videojs can catchup.
  17286. *
  17287. * @fires Tech#loadstart
  17288. *
  17289. * @return {undefined}
  17290. * returns nothing.
  17291. */
  17292. ;
  17293. _proto.handleLateInit_ = function handleLateInit_(el) {
  17294. if (el.networkState === 0 || el.networkState === 3) {
  17295. // The video element hasn't started loading the source yet
  17296. // or didn't find a source
  17297. return;
  17298. }
  17299. if (el.readyState === 0) {
  17300. // NetworkState is set synchronously BUT loadstart is fired at the
  17301. // end of the current stack, usually before setInterval(fn, 0).
  17302. // So at this point we know loadstart may have already fired or is
  17303. // about to fire, and either way the player hasn't seen it yet.
  17304. // We don't want to fire loadstart prematurely here and cause a
  17305. // double loadstart so we'll wait and see if it happens between now
  17306. // and the next loop, and fire it if not.
  17307. // HOWEVER, we also want to make sure it fires before loadedmetadata
  17308. // which could also happen between now and the next loop, so we'll
  17309. // watch for that also.
  17310. var loadstartFired = false;
  17311. var setLoadstartFired = function setLoadstartFired() {
  17312. loadstartFired = true;
  17313. };
  17314. this.on('loadstart', setLoadstartFired);
  17315. var triggerLoadstart = function triggerLoadstart() {
  17316. // We did miss the original loadstart. Make sure the player
  17317. // sees loadstart before loadedmetadata
  17318. if (!loadstartFired) {
  17319. this.trigger('loadstart');
  17320. }
  17321. };
  17322. this.on('loadedmetadata', triggerLoadstart);
  17323. this.ready(function () {
  17324. this.off('loadstart', setLoadstartFired);
  17325. this.off('loadedmetadata', triggerLoadstart);
  17326. if (!loadstartFired) {
  17327. // We did miss the original native loadstart. Fire it now.
  17328. this.trigger('loadstart');
  17329. }
  17330. });
  17331. return;
  17332. } // From here on we know that loadstart already fired and we missed it.
  17333. // The other readyState events aren't as much of a problem if we double
  17334. // them, so not going to go to as much trouble as loadstart to prevent
  17335. // that unless we find reason to.
  17336. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  17337. eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  17338. if (el.readyState >= 2) {
  17339. eventsToTrigger.push('loadeddata');
  17340. } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  17341. if (el.readyState >= 3) {
  17342. eventsToTrigger.push('canplay');
  17343. } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  17344. if (el.readyState >= 4) {
  17345. eventsToTrigger.push('canplaythrough');
  17346. } // We still need to give the player time to add event listeners
  17347. this.ready(function () {
  17348. eventsToTrigger.forEach(function (type) {
  17349. this.trigger(type);
  17350. }, this);
  17351. });
  17352. }
  17353. /**
  17354. * Set whether we are scrubbing or not.
  17355. * This is used to decide whether we should use `fastSeek` or not.
  17356. * `fastSeek` is used to provide trick play on Safari browsers.
  17357. *
  17358. * @param {boolean} isScrubbing
  17359. * - true for we are currently scrubbing
  17360. * - false for we are no longer scrubbing
  17361. */
  17362. ;
  17363. _proto.setScrubbing = function setScrubbing(isScrubbing) {
  17364. this.isScrubbing_ = isScrubbing;
  17365. }
  17366. /**
  17367. * Get whether we are scrubbing or not.
  17368. *
  17369. * @return {boolean} isScrubbing
  17370. * - true for we are currently scrubbing
  17371. * - false for we are no longer scrubbing
  17372. */
  17373. ;
  17374. _proto.scrubbing = function scrubbing() {
  17375. return this.isScrubbing_;
  17376. }
  17377. /**
  17378. * Set current time for the `HTML5` tech.
  17379. *
  17380. * @param {number} seconds
  17381. * Set the current time of the media to this.
  17382. */
  17383. ;
  17384. _proto.setCurrentTime = function setCurrentTime(seconds) {
  17385. try {
  17386. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  17387. this.el_.fastSeek(seconds);
  17388. } else {
  17389. this.el_.currentTime = seconds;
  17390. }
  17391. } catch (e) {
  17392. log$1(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady);
  17393. }
  17394. }
  17395. /**
  17396. * Get the current duration of the HTML5 media element.
  17397. *
  17398. * @return {number}
  17399. * The duration of the media or 0 if there is no duration.
  17400. */
  17401. ;
  17402. _proto.duration = function duration() {
  17403. var _this5 = this;
  17404. // Android Chrome will report duration as Infinity for VOD HLS until after
  17405. // playback has started, which triggers the live display erroneously.
  17406. // Return NaN if playback has not started and trigger a durationupdate once
  17407. // the duration can be reliably known.
  17408. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  17409. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17410. // several with 0
  17411. var checkProgress = function checkProgress() {
  17412. if (_this5.el_.currentTime > 0) {
  17413. // Trigger durationchange for genuinely live video
  17414. if (_this5.el_.duration === Infinity) {
  17415. _this5.trigger('durationchange');
  17416. }
  17417. _this5.off('timeupdate', checkProgress);
  17418. }
  17419. };
  17420. this.on('timeupdate', checkProgress);
  17421. return NaN;
  17422. }
  17423. return this.el_.duration || NaN;
  17424. }
  17425. /**
  17426. * Get the current width of the HTML5 media element.
  17427. *
  17428. * @return {number}
  17429. * The width of the HTML5 media element.
  17430. */
  17431. ;
  17432. _proto.width = function width() {
  17433. return this.el_.offsetWidth;
  17434. }
  17435. /**
  17436. * Get the current height of the HTML5 media element.
  17437. *
  17438. * @return {number}
  17439. * The height of the HTML5 media element.
  17440. */
  17441. ;
  17442. _proto.height = function height() {
  17443. return this.el_.offsetHeight;
  17444. }
  17445. /**
  17446. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17447. * `fullscreenchange` event.
  17448. *
  17449. * @private
  17450. * @fires fullscreenchange
  17451. * @listens webkitendfullscreen
  17452. * @listens webkitbeginfullscreen
  17453. * @listens webkitbeginfullscreen
  17454. */
  17455. ;
  17456. _proto.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() {
  17457. var _this6 = this;
  17458. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17459. return;
  17460. }
  17461. var endFn = function endFn() {
  17462. this.trigger('fullscreenchange', {
  17463. isFullscreen: false
  17464. }); // Safari will sometimes set contols on the videoelement when existing fullscreen.
  17465. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17466. this.el_.controls = false;
  17467. }
  17468. };
  17469. var beginFn = function beginFn() {
  17470. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17471. this.one('webkitendfullscreen', endFn);
  17472. this.trigger('fullscreenchange', {
  17473. isFullscreen: true,
  17474. // set a flag in case another tech triggers fullscreenchange
  17475. nativeIOSFullscreen: true
  17476. });
  17477. }
  17478. };
  17479. this.on('webkitbeginfullscreen', beginFn);
  17480. this.on('dispose', function () {
  17481. _this6.off('webkitbeginfullscreen', beginFn);
  17482. _this6.off('webkitendfullscreen', endFn);
  17483. });
  17484. }
  17485. /**
  17486. * Check if fullscreen is supported on the current playback device.
  17487. *
  17488. * @return {boolean}
  17489. * - True if fullscreen is supported.
  17490. * - False if fullscreen is not supported.
  17491. */
  17492. ;
  17493. _proto.supportsFullScreen = function supportsFullScreen() {
  17494. if (typeof this.el_.webkitEnterFullScreen === 'function') {
  17495. var userAgent = window__default['default'].navigator && window__default['default'].navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard
  17496. if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
  17497. return true;
  17498. }
  17499. }
  17500. return false;
  17501. }
  17502. /**
  17503. * Request that the `HTML5` Tech enter fullscreen.
  17504. */
  17505. ;
  17506. _proto.enterFullScreen = function enterFullScreen() {
  17507. var video = this.el_;
  17508. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17509. // attempt to prime the video element for programmatic access
  17510. // this isn't necessary on the desktop but shouldn't hurt
  17511. silencePromise(this.el_.play()); // playing and pausing synchronously during the transition to fullscreen
  17512. // can get iOS ~6.1 devices into a play/pause loop
  17513. this.setTimeout(function () {
  17514. video.pause();
  17515. try {
  17516. video.webkitEnterFullScreen();
  17517. } catch (e) {
  17518. this.trigger('fullscreenerror', e);
  17519. }
  17520. }, 0);
  17521. } else {
  17522. try {
  17523. video.webkitEnterFullScreen();
  17524. } catch (e) {
  17525. this.trigger('fullscreenerror', e);
  17526. }
  17527. }
  17528. }
  17529. /**
  17530. * Request that the `HTML5` Tech exit fullscreen.
  17531. */
  17532. ;
  17533. _proto.exitFullScreen = function exitFullScreen() {
  17534. if (!this.el_.webkitDisplayingFullscreen) {
  17535. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  17536. return;
  17537. }
  17538. this.el_.webkitExitFullScreen();
  17539. }
  17540. /**
  17541. * Create a floating video window always on top of other windows so that users may
  17542. * continue consuming media while they interact with other content sites, or
  17543. * applications on their device.
  17544. *
  17545. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  17546. *
  17547. * @return {Promise}
  17548. * A promise with a Picture-in-Picture window.
  17549. */
  17550. ;
  17551. _proto.requestPictureInPicture = function requestPictureInPicture() {
  17552. return this.el_.requestPictureInPicture();
  17553. }
  17554. /**
  17555. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  17556. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  17557. * Needs to be checked later than the constructor
  17558. * This will be a false positive for clear sources loaded after a Fairplay source
  17559. *
  17560. * @param {function} cb function to call
  17561. * @return {number} id of request
  17562. */
  17563. ;
  17564. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  17565. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17566. return this.el_.requestVideoFrameCallback(cb);
  17567. }
  17568. return _Tech.prototype.requestVideoFrameCallback.call(this, cb);
  17569. }
  17570. /**
  17571. * Native or fallback requestVideoFrameCallback
  17572. *
  17573. * @param {number} id request id to cancel
  17574. */
  17575. ;
  17576. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  17577. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  17578. this.el_.cancelVideoFrameCallback(id);
  17579. } else {
  17580. _Tech.prototype.cancelVideoFrameCallback.call(this, id);
  17581. }
  17582. }
  17583. /**
  17584. * A getter/setter for the `Html5` Tech's source object.
  17585. * > Note: Please use {@link Html5#setSource}
  17586. *
  17587. * @param {Tech~SourceObject} [src]
  17588. * The source object you want to set on the `HTML5` techs element.
  17589. *
  17590. * @return {Tech~SourceObject|undefined}
  17591. * - The current source object when a source is not passed in.
  17592. * - undefined when setting
  17593. *
  17594. * @deprecated Since version 5.
  17595. */
  17596. ;
  17597. _proto.src = function src(_src) {
  17598. if (_src === undefined) {
  17599. return this.el_.src;
  17600. } // Setting src through `src` instead of `setSrc` will be deprecated
  17601. this.setSrc(_src);
  17602. }
  17603. /**
  17604. * Reset the tech by removing all sources and then calling
  17605. * {@link Html5.resetMediaElement}.
  17606. */
  17607. ;
  17608. _proto.reset = function reset() {
  17609. Html5.resetMediaElement(this.el_);
  17610. }
  17611. /**
  17612. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  17613. * the HTML5 media element.
  17614. *
  17615. * @return {Tech~SourceObject}
  17616. * The current source object from the HTML5 tech. With a fallback to the
  17617. * elements source.
  17618. */
  17619. ;
  17620. _proto.currentSrc = function currentSrc() {
  17621. if (this.currentSource_) {
  17622. return this.currentSource_.src;
  17623. }
  17624. return this.el_.currentSrc;
  17625. }
  17626. /**
  17627. * Set controls attribute for the HTML5 media Element.
  17628. *
  17629. * @param {string} val
  17630. * Value to set the controls attribute to
  17631. */
  17632. ;
  17633. _proto.setControls = function setControls(val) {
  17634. this.el_.controls = !!val;
  17635. }
  17636. /**
  17637. * Create and returns a remote {@link TextTrack} object.
  17638. *
  17639. * @param {string} kind
  17640. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  17641. *
  17642. * @param {string} [label]
  17643. * Label to identify the text track
  17644. *
  17645. * @param {string} [language]
  17646. * Two letter language abbreviation
  17647. *
  17648. * @return {TextTrack}
  17649. * The TextTrack that gets created.
  17650. */
  17651. ;
  17652. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  17653. if (!this.featuresNativeTextTracks) {
  17654. return _Tech.prototype.addTextTrack.call(this, kind, label, language);
  17655. }
  17656. return this.el_.addTextTrack(kind, label, language);
  17657. }
  17658. /**
  17659. * Creates either native TextTrack or an emulated TextTrack depending
  17660. * on the value of `featuresNativeTextTracks`
  17661. *
  17662. * @param {Object} options
  17663. * The object should contain the options to initialize the TextTrack with.
  17664. *
  17665. * @param {string} [options.kind]
  17666. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  17667. *
  17668. * @param {string} [options.label]
  17669. * Label to identify the text track
  17670. *
  17671. * @param {string} [options.language]
  17672. * Two letter language abbreviation.
  17673. *
  17674. * @param {boolean} [options.default]
  17675. * Default this track to on.
  17676. *
  17677. * @param {string} [options.id]
  17678. * The internal id to assign this track.
  17679. *
  17680. * @param {string} [options.src]
  17681. * A source url for the track.
  17682. *
  17683. * @return {HTMLTrackElement}
  17684. * The track element that gets created.
  17685. */
  17686. ;
  17687. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  17688. if (!this.featuresNativeTextTracks) {
  17689. return _Tech.prototype.createRemoteTextTrack.call(this, options);
  17690. }
  17691. var htmlTrackElement = document__default['default'].createElement('track');
  17692. if (options.kind) {
  17693. htmlTrackElement.kind = options.kind;
  17694. }
  17695. if (options.label) {
  17696. htmlTrackElement.label = options.label;
  17697. }
  17698. if (options.language || options.srclang) {
  17699. htmlTrackElement.srclang = options.language || options.srclang;
  17700. }
  17701. if (options["default"]) {
  17702. htmlTrackElement["default"] = options["default"];
  17703. }
  17704. if (options.id) {
  17705. htmlTrackElement.id = options.id;
  17706. }
  17707. if (options.src) {
  17708. htmlTrackElement.src = options.src;
  17709. }
  17710. return htmlTrackElement;
  17711. }
  17712. /**
  17713. * Creates a remote text track object and returns an html track element.
  17714. *
  17715. * @param {Object} options The object should contain values for
  17716. * kind, language, label, and src (location of the WebVTT file)
  17717. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  17718. * automatically removed from the video element whenever the source changes
  17719. * @return {HTMLTrackElement} An Html Track Element.
  17720. * This can be an emulated {@link HTMLTrackElement} or a native one.
  17721. * @deprecated The default value of the "manualCleanup" parameter will default
  17722. * to "false" in upcoming versions of Video.js
  17723. */
  17724. ;
  17725. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  17726. var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup);
  17727. if (this.featuresNativeTextTracks) {
  17728. this.el().appendChild(htmlTrackElement);
  17729. }
  17730. return htmlTrackElement;
  17731. }
  17732. /**
  17733. * Remove remote `TextTrack` from `TextTrackList` object
  17734. *
  17735. * @param {TextTrack} track
  17736. * `TextTrack` object to remove
  17737. */
  17738. ;
  17739. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  17740. _Tech.prototype.removeRemoteTextTrack.call(this, track);
  17741. if (this.featuresNativeTextTracks) {
  17742. var tracks = this.$$('track');
  17743. var i = tracks.length;
  17744. while (i--) {
  17745. if (track === tracks[i] || track === tracks[i].track) {
  17746. this.el().removeChild(tracks[i]);
  17747. }
  17748. }
  17749. }
  17750. }
  17751. /**
  17752. * Gets available media playback quality metrics as specified by the W3C's Media
  17753. * Playback Quality API.
  17754. *
  17755. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  17756. *
  17757. * @return {Object}
  17758. * An object with supported media playback quality metrics
  17759. */
  17760. ;
  17761. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  17762. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  17763. return this.el().getVideoPlaybackQuality();
  17764. }
  17765. var videoPlaybackQuality = {};
  17766. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  17767. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  17768. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  17769. }
  17770. if (window__default['default'].performance && typeof window__default['default'].performance.now === 'function') {
  17771. videoPlaybackQuality.creationTime = window__default['default'].performance.now();
  17772. } else if (window__default['default'].performance && window__default['default'].performance.timing && typeof window__default['default'].performance.timing.navigationStart === 'number') {
  17773. videoPlaybackQuality.creationTime = window__default['default'].Date.now() - window__default['default'].performance.timing.navigationStart;
  17774. }
  17775. return videoPlaybackQuality;
  17776. };
  17777. return Html5;
  17778. }(Tech);
  17779. /* HTML5 Support Testing ---------------------------------------------------- */
  17780. /**
  17781. * Element for testing browser HTML5 media capabilities
  17782. *
  17783. * @type {Element}
  17784. * @constant
  17785. * @private
  17786. */
  17787. defineLazyProperty(Html5, 'TEST_VID', function () {
  17788. if (!isReal()) {
  17789. return;
  17790. }
  17791. var video = document__default['default'].createElement('video');
  17792. var track = document__default['default'].createElement('track');
  17793. track.kind = 'captions';
  17794. track.srclang = 'en';
  17795. track.label = 'English';
  17796. video.appendChild(track);
  17797. return video;
  17798. });
  17799. /**
  17800. * Check if HTML5 media is supported by this browser/device.
  17801. *
  17802. * @return {boolean}
  17803. * - True if HTML5 media is supported.
  17804. * - False if HTML5 media is not supported.
  17805. */
  17806. Html5.isSupported = function () {
  17807. // IE with no Media Player is a LIAR! (#984)
  17808. try {
  17809. Html5.TEST_VID.volume = 0.5;
  17810. } catch (e) {
  17811. return false;
  17812. }
  17813. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  17814. };
  17815. /**
  17816. * Check if the tech can support the given type
  17817. *
  17818. * @param {string} type
  17819. * The mimetype to check
  17820. * @return {string} 'probably', 'maybe', or '' (empty string)
  17821. */
  17822. Html5.canPlayType = function (type) {
  17823. return Html5.TEST_VID.canPlayType(type);
  17824. };
  17825. /**
  17826. * Check if the tech can support the given source
  17827. *
  17828. * @param {Object} srcObj
  17829. * The source object
  17830. * @param {Object} options
  17831. * The options passed to the tech
  17832. * @return {string} 'probably', 'maybe', or '' (empty string)
  17833. */
  17834. Html5.canPlaySource = function (srcObj, options) {
  17835. return Html5.canPlayType(srcObj.type);
  17836. };
  17837. /**
  17838. * Check if the volume can be changed in this browser/device.
  17839. * Volume cannot be changed in a lot of mobile devices.
  17840. * Specifically, it can't be changed from 1 on iOS.
  17841. *
  17842. * @return {boolean}
  17843. * - True if volume can be controlled
  17844. * - False otherwise
  17845. */
  17846. Html5.canControlVolume = function () {
  17847. // IE will error if Windows Media Player not installed #3315
  17848. try {
  17849. var volume = Html5.TEST_VID.volume;
  17850. Html5.TEST_VID.volume = volume / 2 + 0.1;
  17851. var canControl = volume !== Html5.TEST_VID.volume; // With the introduction of iOS 15, there are cases where the volume is read as
  17852. // changed but reverts back to its original state at the start of the next tick.
  17853. // To determine whether volume can be controlled on iOS,
  17854. // a timeout is set and the volume is checked asynchronously.
  17855. // Since `features` doesn't currently work asynchronously, the value is manually set.
  17856. if (canControl && IS_IOS) {
  17857. window__default['default'].setTimeout(function () {
  17858. if (Html5 && Html5.prototype) {
  17859. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  17860. }
  17861. }); // default iOS to false, which will be updated in the timeout above.
  17862. return false;
  17863. }
  17864. return canControl;
  17865. } catch (e) {
  17866. return false;
  17867. }
  17868. };
  17869. /**
  17870. * Check if the volume can be muted in this browser/device.
  17871. * Some devices, e.g. iOS, don't allow changing volume
  17872. * but permits muting/unmuting.
  17873. *
  17874. * @return {bolean}
  17875. * - True if volume can be muted
  17876. * - False otherwise
  17877. */
  17878. Html5.canMuteVolume = function () {
  17879. try {
  17880. var muted = Html5.TEST_VID.muted; // in some versions of iOS muted property doesn't always
  17881. // work, so we want to set both property and attribute
  17882. Html5.TEST_VID.muted = !muted;
  17883. if (Html5.TEST_VID.muted) {
  17884. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  17885. } else {
  17886. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  17887. }
  17888. return muted !== Html5.TEST_VID.muted;
  17889. } catch (e) {
  17890. return false;
  17891. }
  17892. };
  17893. /**
  17894. * Check if the playback rate can be changed in this browser/device.
  17895. *
  17896. * @return {boolean}
  17897. * - True if playback rate can be controlled
  17898. * - False otherwise
  17899. */
  17900. Html5.canControlPlaybackRate = function () {
  17901. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  17902. // https://github.com/videojs/video.js/issues/3180
  17903. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  17904. return false;
  17905. } // IE will error if Windows Media Player not installed #3315
  17906. try {
  17907. var playbackRate = Html5.TEST_VID.playbackRate;
  17908. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  17909. return playbackRate !== Html5.TEST_VID.playbackRate;
  17910. } catch (e) {
  17911. return false;
  17912. }
  17913. };
  17914. /**
  17915. * Check if we can override a video/audio elements attributes, with
  17916. * Object.defineProperty.
  17917. *
  17918. * @return {boolean}
  17919. * - True if builtin attributes can be overridden
  17920. * - False otherwise
  17921. */
  17922. Html5.canOverrideAttributes = function () {
  17923. // if we cannot overwrite the src/innerHTML property, there is no support
  17924. // iOS 7 safari for instance cannot do this.
  17925. try {
  17926. var noop = function noop() {};
  17927. Object.defineProperty(document__default['default'].createElement('video'), 'src', {
  17928. get: noop,
  17929. set: noop
  17930. });
  17931. Object.defineProperty(document__default['default'].createElement('audio'), 'src', {
  17932. get: noop,
  17933. set: noop
  17934. });
  17935. Object.defineProperty(document__default['default'].createElement('video'), 'innerHTML', {
  17936. get: noop,
  17937. set: noop
  17938. });
  17939. Object.defineProperty(document__default['default'].createElement('audio'), 'innerHTML', {
  17940. get: noop,
  17941. set: noop
  17942. });
  17943. } catch (e) {
  17944. return false;
  17945. }
  17946. return true;
  17947. };
  17948. /**
  17949. * Check to see if native `TextTrack`s are supported by this browser/device.
  17950. *
  17951. * @return {boolean}
  17952. * - True if native `TextTrack`s are supported.
  17953. * - False otherwise
  17954. */
  17955. Html5.supportsNativeTextTracks = function () {
  17956. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  17957. };
  17958. /**
  17959. * Check to see if native `VideoTrack`s are supported by this browser/device
  17960. *
  17961. * @return {boolean}
  17962. * - True if native `VideoTrack`s are supported.
  17963. * - False otherwise
  17964. */
  17965. Html5.supportsNativeVideoTracks = function () {
  17966. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  17967. };
  17968. /**
  17969. * Check to see if native `AudioTrack`s are supported by this browser/device
  17970. *
  17971. * @return {boolean}
  17972. * - True if native `AudioTrack`s are supported.
  17973. * - False otherwise
  17974. */
  17975. Html5.supportsNativeAudioTracks = function () {
  17976. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  17977. };
  17978. /**
  17979. * An array of events available on the Html5 tech.
  17980. *
  17981. * @private
  17982. * @type {Array}
  17983. */
  17984. 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'];
  17985. /**
  17986. * Boolean indicating whether the `Tech` supports volume control.
  17987. *
  17988. * @type {boolean}
  17989. * @default {@link Html5.canControlVolume}
  17990. */
  17991. /**
  17992. * Boolean indicating whether the `Tech` supports muting volume.
  17993. *
  17994. * @type {bolean}
  17995. * @default {@link Html5.canMuteVolume}
  17996. */
  17997. /**
  17998. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  17999. * plays. Examples:
  18000. * - Set player to play 2x (twice) as fast
  18001. * - Set player to play 0.5x (half) as fast
  18002. *
  18003. * @type {boolean}
  18004. * @default {@link Html5.canControlPlaybackRate}
  18005. */
  18006. /**
  18007. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  18008. *
  18009. * @type {boolean}
  18010. * @default
  18011. */
  18012. /**
  18013. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  18014. *
  18015. * @type {boolean}
  18016. * @default {@link Html5.supportsNativeTextTracks}
  18017. */
  18018. /**
  18019. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  18020. *
  18021. * @type {boolean}
  18022. * @default {@link Html5.supportsNativeVideoTracks}
  18023. */
  18024. /**
  18025. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  18026. *
  18027. * @type {boolean}
  18028. * @default {@link Html5.supportsNativeAudioTracks}
  18029. */
  18030. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function (_ref) {
  18031. var key = _ref[0],
  18032. fn = _ref[1];
  18033. defineLazyProperty(Html5.prototype, key, function () {
  18034. return Html5[fn]();
  18035. }, true);
  18036. });
  18037. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  18038. /**
  18039. * Boolean indicating whether the `HTML5` tech currently supports the media element
  18040. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  18041. * false there. Everywhere else this should be true.
  18042. *
  18043. * @type {boolean}
  18044. * @default
  18045. */
  18046. Html5.prototype.movingMediaElementInDOM = !IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  18047. // Is this true?
  18048. /**
  18049. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  18050. * when going into fullscreen.
  18051. *
  18052. * @type {boolean}
  18053. * @default
  18054. */
  18055. Html5.prototype.featuresFullscreenResize = true;
  18056. /**
  18057. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  18058. * If this is false, manual `progress` events will be triggered instead.
  18059. *
  18060. * @type {boolean}
  18061. * @default
  18062. */
  18063. Html5.prototype.featuresProgressEvents = true;
  18064. /**
  18065. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  18066. * If this is false, manual `timeupdate` events will be triggered instead.
  18067. *
  18068. * @default
  18069. */
  18070. Html5.prototype.featuresTimeupdateEvents = true;
  18071. /**
  18072. * Whether the HTML5 el supports `requestVideoFrameCallback`
  18073. *
  18074. * @type {boolean}
  18075. */
  18076. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback); // HTML5 Feature detection and Device Fixes --------------------------------- //
  18077. var canPlayType;
  18078. Html5.patchCanPlayType = function () {
  18079. // Android 4.0 and above can play HLS to some extent but it reports being unable to do so
  18080. // Firefox and Chrome report correctly
  18081. if (ANDROID_VERSION >= 4.0 && !IS_FIREFOX && !IS_CHROME) {
  18082. canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
  18083. Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
  18084. var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
  18085. if (type && mpegurlRE.test(type)) {
  18086. return 'maybe';
  18087. }
  18088. return canPlayType.call(this, type);
  18089. };
  18090. }
  18091. };
  18092. Html5.unpatchCanPlayType = function () {
  18093. var r = Html5.TEST_VID.constructor.prototype.canPlayType;
  18094. if (canPlayType) {
  18095. Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
  18096. }
  18097. return r;
  18098. }; // by default, patch the media element
  18099. Html5.patchCanPlayType();
  18100. Html5.disposeMediaElement = function (el) {
  18101. if (!el) {
  18102. return;
  18103. }
  18104. if (el.parentNode) {
  18105. el.parentNode.removeChild(el);
  18106. } // remove any child track or source nodes to prevent their loading
  18107. while (el.hasChildNodes()) {
  18108. el.removeChild(el.firstChild);
  18109. } // remove any src reference. not setting `src=''` because that causes a warning
  18110. // in firefox
  18111. el.removeAttribute('src'); // force the media element to update its loading state by calling load()
  18112. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  18113. if (typeof el.load === 'function') {
  18114. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18115. (function () {
  18116. try {
  18117. el.load();
  18118. } catch (e) {// not supported
  18119. }
  18120. })();
  18121. }
  18122. };
  18123. Html5.resetMediaElement = function (el) {
  18124. if (!el) {
  18125. return;
  18126. }
  18127. var sources = el.querySelectorAll('source');
  18128. var i = sources.length;
  18129. while (i--) {
  18130. el.removeChild(sources[i]);
  18131. } // remove any src reference.
  18132. // not setting `src=''` because that throws an error
  18133. el.removeAttribute('src');
  18134. if (typeof el.load === 'function') {
  18135. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18136. (function () {
  18137. try {
  18138. el.load();
  18139. } catch (e) {// satisfy linter
  18140. }
  18141. })();
  18142. }
  18143. };
  18144. /* Native HTML5 element property wrapping ----------------------------------- */
  18145. // Wrap native boolean attributes with getters that check both property and attribute
  18146. // The list is as followed:
  18147. // muted, defaultMuted, autoplay, controls, loop, playsinline
  18148. [
  18149. /**
  18150. * Get the value of `muted` from the media element. `muted` indicates
  18151. * that the volume for the media should be set to silent. This does not actually change
  18152. * the `volume` attribute.
  18153. *
  18154. * @method Html5#muted
  18155. * @return {boolean}
  18156. * - True if the value of `volume` should be ignored and the audio set to silent.
  18157. * - False if the value of `volume` should be used.
  18158. *
  18159. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18160. */
  18161. 'muted',
  18162. /**
  18163. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  18164. * whether the media should start muted or not. Only changes the default state of the
  18165. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  18166. * current state.
  18167. *
  18168. * @method Html5#defaultMuted
  18169. * @return {boolean}
  18170. * - The value of `defaultMuted` from the media element.
  18171. * - True indicates that the media should start muted.
  18172. * - False indicates that the media should not start muted
  18173. *
  18174. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18175. */
  18176. 'defaultMuted',
  18177. /**
  18178. * Get the value of `autoplay` from the media element. `autoplay` indicates
  18179. * that the media should start to play as soon as the page is ready.
  18180. *
  18181. * @method Html5#autoplay
  18182. * @return {boolean}
  18183. * - The value of `autoplay` from the media element.
  18184. * - True indicates that the media should start as soon as the page loads.
  18185. * - False indicates that the media should not start as soon as the page loads.
  18186. *
  18187. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18188. */
  18189. 'autoplay',
  18190. /**
  18191. * Get the value of `controls` from the media element. `controls` indicates
  18192. * whether the native media controls should be shown or hidden.
  18193. *
  18194. * @method Html5#controls
  18195. * @return {boolean}
  18196. * - The value of `controls` from the media element.
  18197. * - True indicates that native controls should be showing.
  18198. * - False indicates that native controls should be hidden.
  18199. *
  18200. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  18201. */
  18202. 'controls',
  18203. /**
  18204. * Get the value of `loop` from the media element. `loop` indicates
  18205. * that the media should return to the start of the media and continue playing once
  18206. * it reaches the end.
  18207. *
  18208. * @method Html5#loop
  18209. * @return {boolean}
  18210. * - The value of `loop` from the media element.
  18211. * - True indicates that playback should seek back to start once
  18212. * the end of a media is reached.
  18213. * - False indicates that playback should not loop back to the start when the
  18214. * end of the media is reached.
  18215. *
  18216. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18217. */
  18218. 'loop',
  18219. /**
  18220. * Get the value of `playsinline` from the media element. `playsinline` indicates
  18221. * to the browser that non-fullscreen playback is preferred when fullscreen
  18222. * playback is the native default, such as in iOS Safari.
  18223. *
  18224. * @method Html5#playsinline
  18225. * @return {boolean}
  18226. * - The value of `playsinline` from the media element.
  18227. * - True indicates that the media should play inline.
  18228. * - False indicates that the media should not play inline.
  18229. *
  18230. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18231. */
  18232. 'playsinline'].forEach(function (prop) {
  18233. Html5.prototype[prop] = function () {
  18234. return this.el_[prop] || this.el_.hasAttribute(prop);
  18235. };
  18236. }); // Wrap native boolean attributes with setters that set both property and attribute
  18237. // The list is as followed:
  18238. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  18239. // setControls is special-cased above
  18240. [
  18241. /**
  18242. * Set the value of `muted` on the media element. `muted` indicates that the current
  18243. * audio level should be silent.
  18244. *
  18245. * @method Html5#setMuted
  18246. * @param {boolean} muted
  18247. * - True if the audio should be set to silent
  18248. * - False otherwise
  18249. *
  18250. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18251. */
  18252. 'muted',
  18253. /**
  18254. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  18255. * audio level should be silent, but will only effect the muted level on initial playback..
  18256. *
  18257. * @method Html5.prototype.setDefaultMuted
  18258. * @param {boolean} defaultMuted
  18259. * - True if the audio should be set to silent
  18260. * - False otherwise
  18261. *
  18262. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18263. */
  18264. 'defaultMuted',
  18265. /**
  18266. * Set the value of `autoplay` on the media element. `autoplay` indicates
  18267. * that the media should start to play as soon as the page is ready.
  18268. *
  18269. * @method Html5#setAutoplay
  18270. * @param {boolean} autoplay
  18271. * - True indicates that the media should start as soon as the page loads.
  18272. * - False indicates that the media should not start as soon as the page loads.
  18273. *
  18274. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18275. */
  18276. 'autoplay',
  18277. /**
  18278. * Set the value of `loop` on the media element. `loop` indicates
  18279. * that the media should return to the start of the media and continue playing once
  18280. * it reaches the end.
  18281. *
  18282. * @method Html5#setLoop
  18283. * @param {boolean} loop
  18284. * - True indicates that playback should seek back to start once
  18285. * the end of a media is reached.
  18286. * - False indicates that playback should not loop back to the start when the
  18287. * end of the media is reached.
  18288. *
  18289. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18290. */
  18291. 'loop',
  18292. /**
  18293. * Set the value of `playsinline` from the media element. `playsinline` indicates
  18294. * to the browser that non-fullscreen playback is preferred when fullscreen
  18295. * playback is the native default, such as in iOS Safari.
  18296. *
  18297. * @method Html5#setPlaysinline
  18298. * @param {boolean} playsinline
  18299. * - True indicates that the media should play inline.
  18300. * - False indicates that the media should not play inline.
  18301. *
  18302. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18303. */
  18304. 'playsinline'].forEach(function (prop) {
  18305. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18306. this.el_[prop] = v;
  18307. if (v) {
  18308. this.el_.setAttribute(prop, prop);
  18309. } else {
  18310. this.el_.removeAttribute(prop);
  18311. }
  18312. };
  18313. }); // Wrap native properties with a getter
  18314. // The list is as followed
  18315. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  18316. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  18317. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  18318. [
  18319. /**
  18320. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  18321. * is currently paused or not.
  18322. *
  18323. * @method Html5#paused
  18324. * @return {boolean}
  18325. * The value of `paused` from the media element.
  18326. *
  18327. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  18328. */
  18329. 'paused',
  18330. /**
  18331. * Get the value of `currentTime` from the media element. `currentTime` indicates
  18332. * the current second that the media is at in playback.
  18333. *
  18334. * @method Html5#currentTime
  18335. * @return {number}
  18336. * The value of `currentTime` from the media element.
  18337. *
  18338. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  18339. */
  18340. 'currentTime',
  18341. /**
  18342. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  18343. * object that represents the parts of the media that are already downloaded and
  18344. * available for playback.
  18345. *
  18346. * @method Html5#buffered
  18347. * @return {TimeRange}
  18348. * The value of `buffered` from the media element.
  18349. *
  18350. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  18351. */
  18352. 'buffered',
  18353. /**
  18354. * Get the value of `volume` from the media element. `volume` indicates
  18355. * the current playback volume of audio for a media. `volume` will be a value from 0
  18356. * (silent) to 1 (loudest and default).
  18357. *
  18358. * @method Html5#volume
  18359. * @return {number}
  18360. * The value of `volume` from the media element. Value will be between 0-1.
  18361. *
  18362. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18363. */
  18364. 'volume',
  18365. /**
  18366. * Get the value of `poster` from the media element. `poster` indicates
  18367. * that the url of an image file that can/will be shown when no media data is available.
  18368. *
  18369. * @method Html5#poster
  18370. * @return {string}
  18371. * The value of `poster` from the media element. Value will be a url to an
  18372. * image.
  18373. *
  18374. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  18375. */
  18376. 'poster',
  18377. /**
  18378. * Get the value of `preload` from the media element. `preload` indicates
  18379. * what should download before the media is interacted with. It can have the following
  18380. * values:
  18381. * - none: nothing should be downloaded
  18382. * - metadata: poster and the first few frames of the media may be downloaded to get
  18383. * media dimensions and other metadata
  18384. * - auto: allow the media and metadata for the media to be downloaded before
  18385. * interaction
  18386. *
  18387. * @method Html5#preload
  18388. * @return {string}
  18389. * The value of `preload` from the media element. Will be 'none', 'metadata',
  18390. * or 'auto'.
  18391. *
  18392. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18393. */
  18394. 'preload',
  18395. /**
  18396. * Get the value of the `error` from the media element. `error` indicates any
  18397. * MediaError that may have occurred during playback. If error returns null there is no
  18398. * current error.
  18399. *
  18400. * @method Html5#error
  18401. * @return {MediaError|null}
  18402. * The value of `error` from the media element. Will be `MediaError` if there
  18403. * is a current error and null otherwise.
  18404. *
  18405. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  18406. */
  18407. 'error',
  18408. /**
  18409. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  18410. * media is currently seeking to a new position or not.
  18411. *
  18412. * @method Html5#seeking
  18413. * @return {boolean}
  18414. * - The value of `seeking` from the media element.
  18415. * - True indicates that the media is currently seeking to a new position.
  18416. * - False indicates that the media is not seeking to a new position at this time.
  18417. *
  18418. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  18419. */
  18420. 'seeking',
  18421. /**
  18422. * Get the value of `seekable` from the media element. `seekable` returns a
  18423. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  18424. *
  18425. * @method Html5#seekable
  18426. * @return {TimeRange}
  18427. * The value of `seekable` from the media element. A `TimeRange` object
  18428. * indicating the current ranges of time that can be seeked to.
  18429. *
  18430. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  18431. */
  18432. 'seekable',
  18433. /**
  18434. * Get the value of `ended` from the media element. `ended` indicates whether
  18435. * the media has reached the end or not.
  18436. *
  18437. * @method Html5#ended
  18438. * @return {boolean}
  18439. * - The value of `ended` from the media element.
  18440. * - True indicates that the media has ended.
  18441. * - False indicates that the media has not ended.
  18442. *
  18443. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  18444. */
  18445. 'ended',
  18446. /**
  18447. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  18448. * the rate at which the media is currently playing back. Examples:
  18449. * - if playbackRate is set to 2, media will play twice as fast.
  18450. * - if playbackRate is set to 0.5, media will play half as fast.
  18451. *
  18452. * @method Html5#playbackRate
  18453. * @return {number}
  18454. * The value of `playbackRate` from the media element. A number indicating
  18455. * the current playback speed of the media, where 1 is normal speed.
  18456. *
  18457. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18458. */
  18459. 'playbackRate',
  18460. /**
  18461. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18462. * the rate at which the media is currently playing back. This value will not indicate the current
  18463. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18464. *
  18465. * Examples:
  18466. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18467. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18468. *
  18469. * @method Html5.prototype.defaultPlaybackRate
  18470. * @return {number}
  18471. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18472. * the current playback speed of the media, where 1 is normal speed.
  18473. *
  18474. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18475. */
  18476. 'defaultPlaybackRate',
  18477. /**
  18478. * Get the value of 'disablePictureInPicture' from the video element.
  18479. *
  18480. * @method Html5#disablePictureInPicture
  18481. * @return {boolean} value
  18482. * - The value of `disablePictureInPicture` from the video element.
  18483. * - True indicates that the video can't be played in Picture-In-Picture mode
  18484. * - False indicates that the video can be played in Picture-In-Picture mode
  18485. *
  18486. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18487. */
  18488. 'disablePictureInPicture',
  18489. /**
  18490. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18491. * object representing points in the media timeline that have been played.
  18492. *
  18493. * @method Html5#played
  18494. * @return {TimeRange}
  18495. * The value of `played` from the media element. A `TimeRange` object indicating
  18496. * the ranges of time that have been played.
  18497. *
  18498. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18499. */
  18500. 'played',
  18501. /**
  18502. * Get the value of `networkState` from the media element. `networkState` indicates
  18503. * the current network state. It returns an enumeration from the following list:
  18504. * - 0: NETWORK_EMPTY
  18505. * - 1: NETWORK_IDLE
  18506. * - 2: NETWORK_LOADING
  18507. * - 3: NETWORK_NO_SOURCE
  18508. *
  18509. * @method Html5#networkState
  18510. * @return {number}
  18511. * The value of `networkState` from the media element. This will be a number
  18512. * from the list in the description.
  18513. *
  18514. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18515. */
  18516. 'networkState',
  18517. /**
  18518. * Get the value of `readyState` from the media element. `readyState` indicates
  18519. * the current state of the media element. It returns an enumeration from the
  18520. * following list:
  18521. * - 0: HAVE_NOTHING
  18522. * - 1: HAVE_METADATA
  18523. * - 2: HAVE_CURRENT_DATA
  18524. * - 3: HAVE_FUTURE_DATA
  18525. * - 4: HAVE_ENOUGH_DATA
  18526. *
  18527. * @method Html5#readyState
  18528. * @return {number}
  18529. * The value of `readyState` from the media element. This will be a number
  18530. * from the list in the description.
  18531. *
  18532. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  18533. */
  18534. 'readyState',
  18535. /**
  18536. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  18537. * the current width of the video in css pixels.
  18538. *
  18539. * @method Html5#videoWidth
  18540. * @return {number}
  18541. * The value of `videoWidth` from the video element. This will be a number
  18542. * in css pixels.
  18543. *
  18544. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18545. */
  18546. 'videoWidth',
  18547. /**
  18548. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  18549. * the current height of the video in css pixels.
  18550. *
  18551. * @method Html5#videoHeight
  18552. * @return {number}
  18553. * The value of `videoHeight` from the video element. This will be a number
  18554. * in css pixels.
  18555. *
  18556. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  18557. */
  18558. 'videoHeight',
  18559. /**
  18560. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18561. * to the browser that should sent the cookies along with the requests for the
  18562. * different assets/playlists
  18563. *
  18564. * @method Html5#crossOrigin
  18565. * @return {string}
  18566. * - anonymous indicates that the media should not sent cookies.
  18567. * - use-credentials indicates that the media should sent cookies along the requests.
  18568. *
  18569. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18570. */
  18571. 'crossOrigin'].forEach(function (prop) {
  18572. Html5.prototype[prop] = function () {
  18573. return this.el_[prop];
  18574. };
  18575. }); // Wrap native properties with a setter in this format:
  18576. // set + toTitleCase(name)
  18577. // The list is as follows:
  18578. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  18579. // setDisablePictureInPicture, setCrossOrigin
  18580. [
  18581. /**
  18582. * Set the value of `volume` on the media element. `volume` indicates the current
  18583. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  18584. * so on.
  18585. *
  18586. * @method Html5#setVolume
  18587. * @param {number} percentAsDecimal
  18588. * The volume percent as a decimal. Valid range is from 0-1.
  18589. *
  18590. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18591. */
  18592. 'volume',
  18593. /**
  18594. * Set the value of `src` on the media element. `src` indicates the current
  18595. * {@link Tech~SourceObject} for the media.
  18596. *
  18597. * @method Html5#setSrc
  18598. * @param {Tech~SourceObject} src
  18599. * The source object to set as the current source.
  18600. *
  18601. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  18602. */
  18603. 'src',
  18604. /**
  18605. * Set the value of `poster` on the media element. `poster` is the url to
  18606. * an image file that can/will be shown when no media data is available.
  18607. *
  18608. * @method Html5#setPoster
  18609. * @param {string} poster
  18610. * The url to an image that should be used as the `poster` for the media
  18611. * element.
  18612. *
  18613. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  18614. */
  18615. 'poster',
  18616. /**
  18617. * Set the value of `preload` on the media element. `preload` indicates
  18618. * what should download before the media is interacted with. It can have the following
  18619. * values:
  18620. * - none: nothing should be downloaded
  18621. * - metadata: poster and the first few frames of the media may be downloaded to get
  18622. * media dimensions and other metadata
  18623. * - auto: allow the media and metadata for the media to be downloaded before
  18624. * interaction
  18625. *
  18626. * @method Html5#setPreload
  18627. * @param {string} preload
  18628. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  18629. * or 'auto'.
  18630. *
  18631. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18632. */
  18633. 'preload',
  18634. /**
  18635. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  18636. * the rate at which the media should play back. Examples:
  18637. * - if playbackRate is set to 2, media will play twice as fast.
  18638. * - if playbackRate is set to 0.5, media will play half as fast.
  18639. *
  18640. * @method Html5#setPlaybackRate
  18641. * @return {number}
  18642. * The value of `playbackRate` from the media element. A number indicating
  18643. * the current playback speed of the media, where 1 is normal speed.
  18644. *
  18645. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18646. */
  18647. 'playbackRate',
  18648. /**
  18649. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  18650. * the rate at which the media should play back upon initial startup. Changing this value
  18651. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  18652. *
  18653. * Example Values:
  18654. * - if playbackRate is set to 2, media will play twice as fast.
  18655. * - if playbackRate is set to 0.5, media will play half as fast.
  18656. *
  18657. * @method Html5.prototype.setDefaultPlaybackRate
  18658. * @return {number}
  18659. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18660. * the current playback speed of the media, where 1 is normal speed.
  18661. *
  18662. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  18663. */
  18664. 'defaultPlaybackRate',
  18665. /**
  18666. * Prevents the browser from suggesting a Picture-in-Picture context menu
  18667. * or to request Picture-in-Picture automatically in some cases.
  18668. *
  18669. * @method Html5#setDisablePictureInPicture
  18670. * @param {boolean} value
  18671. * The true value will disable Picture-in-Picture mode.
  18672. *
  18673. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18674. */
  18675. 'disablePictureInPicture',
  18676. /**
  18677. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  18678. * to the browser that should sent the cookies along with the requests for the
  18679. * different assets/playlists
  18680. *
  18681. * @method Html5#setCrossOrigin
  18682. * @param {string} crossOrigin
  18683. * - anonymous indicates that the media should not sent cookies.
  18684. * - use-credentials indicates that the media should sent cookies along the requests.
  18685. *
  18686. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  18687. */
  18688. 'crossOrigin'].forEach(function (prop) {
  18689. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18690. this.el_[prop] = v;
  18691. };
  18692. }); // wrap native functions with a function
  18693. // The list is as follows:
  18694. // pause, load, play
  18695. [
  18696. /**
  18697. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  18698. * media elements `pause` function.
  18699. *
  18700. * @method Html5#pause
  18701. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  18702. */
  18703. 'pause',
  18704. /**
  18705. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  18706. * media element `load` function.
  18707. *
  18708. * @method Html5#load
  18709. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  18710. */
  18711. 'load',
  18712. /**
  18713. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  18714. * media element `play` function.
  18715. *
  18716. * @method Html5#play
  18717. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  18718. */
  18719. 'play'].forEach(function (prop) {
  18720. Html5.prototype[prop] = function () {
  18721. return this.el_[prop]();
  18722. };
  18723. });
  18724. Tech.withSourceHandlers(Html5);
  18725. /**
  18726. * Native source handler for Html5, simply passes the source to the media element.
  18727. *
  18728. * @property {Tech~SourceObject} source
  18729. * The source object
  18730. *
  18731. * @property {Html5} tech
  18732. * The instance of the HTML5 tech.
  18733. */
  18734. Html5.nativeSourceHandler = {};
  18735. /**
  18736. * Check if the media element can play the given mime type.
  18737. *
  18738. * @param {string} type
  18739. * The mimetype to check
  18740. *
  18741. * @return {string}
  18742. * 'probably', 'maybe', or '' (empty string)
  18743. */
  18744. Html5.nativeSourceHandler.canPlayType = function (type) {
  18745. // IE without MediaPlayer throws an error (#519)
  18746. try {
  18747. return Html5.TEST_VID.canPlayType(type);
  18748. } catch (e) {
  18749. return '';
  18750. }
  18751. };
  18752. /**
  18753. * Check if the media element can handle a source natively.
  18754. *
  18755. * @param {Tech~SourceObject} source
  18756. * The source object
  18757. *
  18758. * @param {Object} [options]
  18759. * Options to be passed to the tech.
  18760. *
  18761. * @return {string}
  18762. * 'probably', 'maybe', or '' (empty string).
  18763. */
  18764. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  18765. // If a type was provided we should rely on that
  18766. if (source.type) {
  18767. return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]'
  18768. } else if (source.src) {
  18769. var ext = getFileExtension(source.src);
  18770. return Html5.nativeSourceHandler.canPlayType("video/" + ext);
  18771. }
  18772. return '';
  18773. };
  18774. /**
  18775. * Pass the source to the native media element.
  18776. *
  18777. * @param {Tech~SourceObject} source
  18778. * The source object
  18779. *
  18780. * @param {Html5} tech
  18781. * The instance of the Html5 tech
  18782. *
  18783. * @param {Object} [options]
  18784. * The options to pass to the source
  18785. */
  18786. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  18787. tech.setSrc(source.src);
  18788. };
  18789. /**
  18790. * A noop for the native dispose function, as cleanup is not needed.
  18791. */
  18792. Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler
  18793. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  18794. Tech.registerTech('Html5', Html5);
  18795. // on the player when they happen
  18796. var TECH_EVENTS_RETRIGGER = [
  18797. /**
  18798. * Fired while the user agent is downloading media data.
  18799. *
  18800. * @event Player#progress
  18801. * @type {EventTarget~Event}
  18802. */
  18803. /**
  18804. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  18805. *
  18806. * @private
  18807. * @method Player#handleTechProgress_
  18808. * @fires Player#progress
  18809. * @listens Tech#progress
  18810. */
  18811. 'progress',
  18812. /**
  18813. * Fires when the loading of an audio/video is aborted.
  18814. *
  18815. * @event Player#abort
  18816. * @type {EventTarget~Event}
  18817. */
  18818. /**
  18819. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  18820. *
  18821. * @private
  18822. * @method Player#handleTechAbort_
  18823. * @fires Player#abort
  18824. * @listens Tech#abort
  18825. */
  18826. 'abort',
  18827. /**
  18828. * Fires when the browser is intentionally not getting media data.
  18829. *
  18830. * @event Player#suspend
  18831. * @type {EventTarget~Event}
  18832. */
  18833. /**
  18834. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  18835. *
  18836. * @private
  18837. * @method Player#handleTechSuspend_
  18838. * @fires Player#suspend
  18839. * @listens Tech#suspend
  18840. */
  18841. 'suspend',
  18842. /**
  18843. * Fires when the current playlist is empty.
  18844. *
  18845. * @event Player#emptied
  18846. * @type {EventTarget~Event}
  18847. */
  18848. /**
  18849. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  18850. *
  18851. * @private
  18852. * @method Player#handleTechEmptied_
  18853. * @fires Player#emptied
  18854. * @listens Tech#emptied
  18855. */
  18856. 'emptied',
  18857. /**
  18858. * Fires when the browser is trying to get media data, but data is not available.
  18859. *
  18860. * @event Player#stalled
  18861. * @type {EventTarget~Event}
  18862. */
  18863. /**
  18864. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  18865. *
  18866. * @private
  18867. * @method Player#handleTechStalled_
  18868. * @fires Player#stalled
  18869. * @listens Tech#stalled
  18870. */
  18871. 'stalled',
  18872. /**
  18873. * Fires when the browser has loaded meta data for the audio/video.
  18874. *
  18875. * @event Player#loadedmetadata
  18876. * @type {EventTarget~Event}
  18877. */
  18878. /**
  18879. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  18880. *
  18881. * @private
  18882. * @method Player#handleTechLoadedmetadata_
  18883. * @fires Player#loadedmetadata
  18884. * @listens Tech#loadedmetadata
  18885. */
  18886. 'loadedmetadata',
  18887. /**
  18888. * Fires when the browser has loaded the current frame of the audio/video.
  18889. *
  18890. * @event Player#loadeddata
  18891. * @type {event}
  18892. */
  18893. /**
  18894. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  18895. *
  18896. * @private
  18897. * @method Player#handleTechLoaddeddata_
  18898. * @fires Player#loadeddata
  18899. * @listens Tech#loadeddata
  18900. */
  18901. 'loadeddata',
  18902. /**
  18903. * Fires when the current playback position has changed.
  18904. *
  18905. * @event Player#timeupdate
  18906. * @type {event}
  18907. */
  18908. /**
  18909. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  18910. *
  18911. * @private
  18912. * @method Player#handleTechTimeUpdate_
  18913. * @fires Player#timeupdate
  18914. * @listens Tech#timeupdate
  18915. */
  18916. 'timeupdate',
  18917. /**
  18918. * Fires when the video's intrinsic dimensions change
  18919. *
  18920. * @event Player#resize
  18921. * @type {event}
  18922. */
  18923. /**
  18924. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  18925. *
  18926. * @private
  18927. * @method Player#handleTechResize_
  18928. * @fires Player#resize
  18929. * @listens Tech#resize
  18930. */
  18931. 'resize',
  18932. /**
  18933. * Fires when the volume has been changed
  18934. *
  18935. * @event Player#volumechange
  18936. * @type {event}
  18937. */
  18938. /**
  18939. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  18940. *
  18941. * @private
  18942. * @method Player#handleTechVolumechange_
  18943. * @fires Player#volumechange
  18944. * @listens Tech#volumechange
  18945. */
  18946. 'volumechange',
  18947. /**
  18948. * Fires when the text track has been changed
  18949. *
  18950. * @event Player#texttrackchange
  18951. * @type {event}
  18952. */
  18953. /**
  18954. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  18955. *
  18956. * @private
  18957. * @method Player#handleTechTexttrackchange_
  18958. * @fires Player#texttrackchange
  18959. * @listens Tech#texttrackchange
  18960. */
  18961. 'texttrackchange']; // events to queue when playback rate is zero
  18962. // this is a hash for the sole purpose of mapping non-camel-cased event names
  18963. // to camel-cased function names
  18964. var TECH_EVENTS_QUEUE = {
  18965. canplay: 'CanPlay',
  18966. canplaythrough: 'CanPlayThrough',
  18967. playing: 'Playing',
  18968. seeked: 'Seeked'
  18969. };
  18970. var BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  18971. var BREAKPOINT_CLASSES = {}; // grep: vjs-layout-tiny
  18972. // grep: vjs-layout-x-small
  18973. // grep: vjs-layout-small
  18974. // grep: vjs-layout-medium
  18975. // grep: vjs-layout-large
  18976. // grep: vjs-layout-x-large
  18977. // grep: vjs-layout-huge
  18978. BREAKPOINT_ORDER.forEach(function (k) {
  18979. var v = k.charAt(0) === 'x' ? "x-" + k.substring(1) : k;
  18980. BREAKPOINT_CLASSES[k] = "vjs-layout-" + v;
  18981. });
  18982. var DEFAULT_BREAKPOINTS = {
  18983. tiny: 210,
  18984. xsmall: 320,
  18985. small: 425,
  18986. medium: 768,
  18987. large: 1440,
  18988. xlarge: 2560,
  18989. huge: Infinity
  18990. };
  18991. /**
  18992. * An instance of the `Player` class is created when any of the Video.js setup methods
  18993. * are used to initialize a video.
  18994. *
  18995. * After an instance has been created it can be accessed globally in two ways:
  18996. * 1. By calling `videojs('example_video_1');`
  18997. * 2. By using it directly via `videojs.players.example_video_1;`
  18998. *
  18999. * @extends Component
  19000. */
  19001. var Player = /*#__PURE__*/function (_Component) {
  19002. _inheritsLoose__default['default'](Player, _Component);
  19003. /**
  19004. * Create an instance of this class.
  19005. *
  19006. * @param {Element} tag
  19007. * The original video DOM element used for configuring options.
  19008. *
  19009. * @param {Object} [options]
  19010. * Object of option names and values.
  19011. *
  19012. * @param {Component~ReadyCallback} [ready]
  19013. * Ready callback function.
  19014. */
  19015. function Player(tag, options, ready) {
  19016. var _this;
  19017. // Make sure tag ID exists
  19018. tag.id = tag.id || options.id || "vjs_video_" + newGUID(); // Set Options
  19019. // The options argument overrides options set in the video tag
  19020. // which overrides globally set options.
  19021. // This latter part coincides with the load order
  19022. // (tag must exist before Player)
  19023. options = assign(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up
  19024. // player properties first, and can't use `this` before `super()`
  19025. options.initChildren = false; // Same with creating the element
  19026. options.createEl = false; // don't auto mixin the evented mixin
  19027. options.evented = false; // we don't want the player to report touch activity on itself
  19028. // see enableTouchActivity in Component
  19029. options.reportTouchActivity = false; // If language is not set, get the closest lang attribute
  19030. if (!options.language) {
  19031. if (typeof tag.closest === 'function') {
  19032. var closest = tag.closest('[lang]');
  19033. if (closest && closest.getAttribute) {
  19034. options.language = closest.getAttribute('lang');
  19035. }
  19036. } else {
  19037. var element = tag;
  19038. while (element && element.nodeType === 1) {
  19039. if (getAttributes(element).hasOwnProperty('lang')) {
  19040. options.language = element.getAttribute('lang');
  19041. break;
  19042. }
  19043. element = element.parentNode;
  19044. }
  19045. }
  19046. } // Run base component initializing with new options
  19047. _this = _Component.call(this, null, options, ready) || this; // Create bound methods for document listeners.
  19048. _this.boundDocumentFullscreenChange_ = function (e) {
  19049. return _this.documentFullscreenChange_(e);
  19050. };
  19051. _this.boundFullWindowOnEscKey_ = function (e) {
  19052. return _this.fullWindowOnEscKey(e);
  19053. };
  19054. _this.boundUpdateStyleEl_ = function (e) {
  19055. return _this.updateStyleEl_(e);
  19056. };
  19057. _this.boundApplyInitTime_ = function (e) {
  19058. return _this.applyInitTime_(e);
  19059. };
  19060. _this.boundUpdateCurrentBreakpoint_ = function (e) {
  19061. return _this.updateCurrentBreakpoint_(e);
  19062. };
  19063. _this.boundHandleTechClick_ = function (e) {
  19064. return _this.handleTechClick_(e);
  19065. };
  19066. _this.boundHandleTechDoubleClick_ = function (e) {
  19067. return _this.handleTechDoubleClick_(e);
  19068. };
  19069. _this.boundHandleTechTouchStart_ = function (e) {
  19070. return _this.handleTechTouchStart_(e);
  19071. };
  19072. _this.boundHandleTechTouchMove_ = function (e) {
  19073. return _this.handleTechTouchMove_(e);
  19074. };
  19075. _this.boundHandleTechTouchEnd_ = function (e) {
  19076. return _this.handleTechTouchEnd_(e);
  19077. };
  19078. _this.boundHandleTechTap_ = function (e) {
  19079. return _this.handleTechTap_(e);
  19080. }; // default isFullscreen_ to false
  19081. _this.isFullscreen_ = false; // create logger
  19082. _this.log = createLogger(_this.id_); // Hold our own reference to fullscreen api so it can be mocked in tests
  19083. _this.fsApi_ = FullscreenApi; // Tracks when a tech changes the poster
  19084. _this.isPosterFromTech_ = false; // Holds callback info that gets queued when playback rate is zero
  19085. // and a seek is happening
  19086. _this.queuedCallbacks_ = []; // Turn off API access because we're loading a new tech that might load asynchronously
  19087. _this.isReady_ = false; // Init state hasStarted_
  19088. _this.hasStarted_ = false; // Init state userActive_
  19089. _this.userActive_ = false; // Init debugEnabled_
  19090. _this.debugEnabled_ = false; // Init state audioOnlyMode_
  19091. _this.audioOnlyMode_ = false; // Init state audioPosterMode_
  19092. _this.audioPosterMode_ = false; // Init state audioOnlyCache_
  19093. _this.audioOnlyCache_ = {
  19094. playerHeight: null,
  19095. hiddenChildren: []
  19096. }; // if the global option object was accidentally blown away by
  19097. // someone, bail early with an informative error
  19098. if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) {
  19099. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  19100. } // Store the original tag used to set options
  19101. _this.tag = tag; // Store the tag attributes used to restore html5 element
  19102. _this.tagAttributes = tag && getAttributes(tag); // Update current language
  19103. _this.language(_this.options_.language); // Update Supported Languages
  19104. if (options.languages) {
  19105. // Normalise player option languages to lowercase
  19106. var languagesToLower = {};
  19107. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  19108. languagesToLower[name.toLowerCase()] = options.languages[name];
  19109. });
  19110. _this.languages_ = languagesToLower;
  19111. } else {
  19112. _this.languages_ = Player.prototype.options_.languages;
  19113. }
  19114. _this.resetCache_(); // Set poster
  19115. _this.poster_ = options.poster || ''; // Set controls
  19116. _this.controls_ = !!options.controls; // Original tag settings stored in options
  19117. // now remove immediately so native controls don't flash.
  19118. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  19119. tag.controls = false;
  19120. tag.removeAttribute('controls');
  19121. _this.changingSrc_ = false;
  19122. _this.playCallbacks_ = [];
  19123. _this.playTerminatedQueue_ = []; // the attribute overrides the option
  19124. if (tag.hasAttribute('autoplay')) {
  19125. _this.autoplay(true);
  19126. } else {
  19127. // otherwise use the setter to validate and
  19128. // set the correct value.
  19129. _this.autoplay(_this.options_.autoplay);
  19130. } // check plugins
  19131. if (options.plugins) {
  19132. Object.keys(options.plugins).forEach(function (name) {
  19133. if (typeof _this[name] !== 'function') {
  19134. throw new Error("plugin \"" + name + "\" does not exist");
  19135. }
  19136. });
  19137. }
  19138. /*
  19139. * Store the internal state of scrubbing
  19140. *
  19141. * @private
  19142. * @return {Boolean} True if the user is scrubbing
  19143. */
  19144. _this.scrubbing_ = false;
  19145. _this.el_ = _this.createEl(); // Make this an evented object and use `el_` as its event bus.
  19146. evented(_assertThisInitialized__default['default'](_this), {
  19147. eventBusKey: 'el_'
  19148. }); // listen to document and player fullscreenchange handlers so we receive those events
  19149. // before a user can receive them so we can update isFullscreen appropriately.
  19150. // make sure that we listen to fullscreenchange events before everything else to make sure that
  19151. // our isFullscreen method is updated properly for internal components as well as external.
  19152. if (_this.fsApi_.requestFullscreen) {
  19153. on(document__default['default'], _this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  19154. _this.on(_this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  19155. }
  19156. if (_this.fluid_) {
  19157. _this.on(['playerreset', 'resize'], _this.boundUpdateStyleEl_);
  19158. } // We also want to pass the original player options to each component and plugin
  19159. // as well so they don't need to reach back into the player for options later.
  19160. // We also need to do another copy of this.options_ so we don't end up with
  19161. // an infinite loop.
  19162. var playerOptionsCopy = mergeOptions$3(_this.options_); // Load plugins
  19163. if (options.plugins) {
  19164. Object.keys(options.plugins).forEach(function (name) {
  19165. _this[name](options.plugins[name]);
  19166. });
  19167. } // Enable debug mode to fire debugon event for all plugins.
  19168. if (options.debug) {
  19169. _this.debug(true);
  19170. }
  19171. _this.options_.playerOptions = playerOptionsCopy;
  19172. _this.middleware_ = [];
  19173. _this.playbackRates(options.playbackRates);
  19174. _this.initChildren(); // Set isAudio based on whether or not an audio tag was used
  19175. _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially
  19176. // set because the element doesn't exist yet.
  19177. if (_this.controls()) {
  19178. _this.addClass('vjs-controls-enabled');
  19179. } else {
  19180. _this.addClass('vjs-controls-disabled');
  19181. } // Set ARIA label and region role depending on player type
  19182. _this.el_.setAttribute('role', 'region');
  19183. if (_this.isAudio()) {
  19184. _this.el_.setAttribute('aria-label', _this.localize('Audio Player'));
  19185. } else {
  19186. _this.el_.setAttribute('aria-label', _this.localize('Video Player'));
  19187. }
  19188. if (_this.isAudio()) {
  19189. _this.addClass('vjs-audio');
  19190. }
  19191. if (_this.flexNotSupported_()) {
  19192. _this.addClass('vjs-no-flex');
  19193. } // TODO: Make this smarter. Toggle user state between touching/mousing
  19194. // using events, since devices can have both touch and mouse events.
  19195. // TODO: Make this check be performed again when the window switches between monitors
  19196. // (See https://github.com/videojs/video.js/issues/5683)
  19197. if (TOUCH_ENABLED) {
  19198. _this.addClass('vjs-touch-enabled');
  19199. } // iOS Safari has broken hover handling
  19200. if (!IS_IOS) {
  19201. _this.addClass('vjs-workinghover');
  19202. } // Make player easily findable by ID
  19203. Player.players[_this.id_] = _assertThisInitialized__default['default'](_this); // Add a major version class to aid css in plugins
  19204. var majorVersion = version$5.split('.')[0];
  19205. _this.addClass("vjs-v" + majorVersion); // When the player is first initialized, trigger activity so components
  19206. // like the control bar show themselves if needed
  19207. _this.userActive(true);
  19208. _this.reportUserActivity();
  19209. _this.one('play', function (e) {
  19210. return _this.listenForUserActivity_(e);
  19211. });
  19212. _this.on('stageclick', function (e) {
  19213. return _this.handleStageClick_(e);
  19214. });
  19215. _this.on('keydown', function (e) {
  19216. return _this.handleKeyDown(e);
  19217. });
  19218. _this.on('languagechange', function (e) {
  19219. return _this.handleLanguagechange(e);
  19220. });
  19221. _this.breakpoints(_this.options_.breakpoints);
  19222. _this.responsive(_this.options_.responsive); // Calling both the audio mode methods after the player is fully
  19223. // setup to be able to listen to the events triggered by them
  19224. _this.on('ready', function () {
  19225. // Calling the audioPosterMode method first so that
  19226. // the audioOnlyMode can take precedence when both options are set to true
  19227. _this.audioPosterMode(_this.options_.audioPosterMode);
  19228. _this.audioOnlyMode(_this.options_.audioOnlyMode);
  19229. });
  19230. return _this;
  19231. }
  19232. /**
  19233. * Destroys the video player and does any necessary cleanup.
  19234. *
  19235. * This is especially helpful if you are dynamically adding and removing videos
  19236. * to/from the DOM.
  19237. *
  19238. * @fires Player#dispose
  19239. */
  19240. var _proto = Player.prototype;
  19241. _proto.dispose = function dispose() {
  19242. var _this2 = this;
  19243. /**
  19244. * Called when the player is being disposed of.
  19245. *
  19246. * @event Player#dispose
  19247. * @type {EventTarget~Event}
  19248. */
  19249. this.trigger('dispose'); // prevent dispose from being called twice
  19250. this.off('dispose'); // Make sure all player-specific document listeners are unbound. This is
  19251. off(document__default['default'], this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  19252. off(document__default['default'], 'keydown', this.boundFullWindowOnEscKey_);
  19253. if (this.styleEl_ && this.styleEl_.parentNode) {
  19254. this.styleEl_.parentNode.removeChild(this.styleEl_);
  19255. this.styleEl_ = null;
  19256. } // Kill reference to this player
  19257. Player.players[this.id_] = null;
  19258. if (this.tag && this.tag.player) {
  19259. this.tag.player = null;
  19260. }
  19261. if (this.el_ && this.el_.player) {
  19262. this.el_.player = null;
  19263. }
  19264. if (this.tech_) {
  19265. this.tech_.dispose();
  19266. this.isPosterFromTech_ = false;
  19267. this.poster_ = '';
  19268. }
  19269. if (this.playerElIngest_) {
  19270. this.playerElIngest_ = null;
  19271. }
  19272. if (this.tag) {
  19273. this.tag = null;
  19274. }
  19275. clearCacheForPlayer(this); // remove all event handlers for track lists
  19276. // all tracks and track listeners are removed on
  19277. // tech dispose
  19278. ALL.names.forEach(function (name) {
  19279. var props = ALL[name];
  19280. var list = _this2[props.getterName](); // if it is not a native list
  19281. // we have to manually remove event listeners
  19282. if (list && list.off) {
  19283. list.off();
  19284. }
  19285. }); // the actual .el_ is removed here, or replaced if
  19286. _Component.prototype.dispose.call(this, {
  19287. restoreEl: this.options_.restoreEl
  19288. });
  19289. }
  19290. /**
  19291. * Create the `Player`'s DOM element.
  19292. *
  19293. * @return {Element}
  19294. * The DOM element that gets created.
  19295. */
  19296. ;
  19297. _proto.createEl = function createEl() {
  19298. var tag = this.tag;
  19299. var el;
  19300. var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  19301. var divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  19302. if (playerElIngest) {
  19303. el = this.el_ = tag.parentNode;
  19304. } else if (!divEmbed) {
  19305. el = this.el_ = _Component.prototype.createEl.call(this, 'div');
  19306. } // Copy over all the attributes from the tag, including ID and class
  19307. // ID will now reference player box, not the video tag
  19308. var attrs = getAttributes(tag);
  19309. if (divEmbed) {
  19310. el = this.el_ = tag;
  19311. tag = this.tag = document__default['default'].createElement('video');
  19312. while (el.children.length) {
  19313. tag.appendChild(el.firstChild);
  19314. }
  19315. if (!hasClass(el, 'video-js')) {
  19316. addClass(el, 'video-js');
  19317. }
  19318. el.appendChild(tag);
  19319. playerElIngest = this.playerElIngest_ = el; // move properties over from our custom `video-js` element
  19320. // to our new `video` element. This will move things like
  19321. // `src` or `controls` that were set via js before the player
  19322. // was initialized.
  19323. Object.keys(el).forEach(function (k) {
  19324. try {
  19325. tag[k] = el[k];
  19326. } catch (e) {// we got a a property like outerHTML which we can't actually copy, ignore it
  19327. }
  19328. });
  19329. } // set tabindex to -1 to remove the video element from the focus order
  19330. tag.setAttribute('tabindex', '-1');
  19331. attrs.tabindex = '-1'; // Workaround for #4583 (JAWS+IE doesn't announce BPB or play button), and
  19332. // for the same issue with Chrome (on Windows) with JAWS.
  19333. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  19334. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  19335. // doesn't change behavior of IE11 or Chrome if JAWS is not being used
  19336. if (IE_VERSION || IS_CHROME && IS_WINDOWS) {
  19337. tag.setAttribute('role', 'application');
  19338. attrs.role = 'application';
  19339. } // Remove width/height attrs from tag so CSS can make it 100% width/height
  19340. tag.removeAttribute('width');
  19341. tag.removeAttribute('height');
  19342. if ('width' in attrs) {
  19343. delete attrs.width;
  19344. }
  19345. if ('height' in attrs) {
  19346. delete attrs.height;
  19347. }
  19348. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  19349. // don't copy over the class attribute to the player element when we're in a div embed
  19350. // the class is already set up properly in the divEmbed case
  19351. // and we want to make sure that the `video-js` class doesn't get lost
  19352. if (!(divEmbed && attr === 'class')) {
  19353. el.setAttribute(attr, attrs[attr]);
  19354. }
  19355. if (divEmbed) {
  19356. tag.setAttribute(attr, attrs[attr]);
  19357. }
  19358. }); // Update tag id/class for use as HTML5 playback tech
  19359. // Might think we should do this after embedding in container so .vjs-tech class
  19360. // doesn't flash 100% width/height, but class only applies with .video-js parent
  19361. tag.playerId = tag.id;
  19362. tag.id += '_html5_api';
  19363. tag.className = 'vjs-tech'; // Make player findable on elements
  19364. tag.player = el.player = this; // Default state of video is paused
  19365. this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height
  19366. // of the player in a way that's still overrideable by CSS, just like the
  19367. // video element
  19368. if (window__default['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  19369. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  19370. var defaultsStyleEl = $('.vjs-styles-defaults');
  19371. var head = $('head');
  19372. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  19373. }
  19374. this.fill_ = false;
  19375. this.fluid_ = false; // Pass in the width/height/aspectRatio options which will update the style el
  19376. this.width(this.options_.width);
  19377. this.height(this.options_.height);
  19378. this.fill(this.options_.fill);
  19379. this.fluid(this.options_.fluid);
  19380. this.aspectRatio(this.options_.aspectRatio); // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  19381. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin); // Hide any links within the video/audio tag,
  19382. // because IE doesn't hide them completely from screen readers.
  19383. var links = tag.getElementsByTagName('a');
  19384. for (var i = 0; i < links.length; i++) {
  19385. var linkEl = links.item(i);
  19386. addClass(linkEl, 'vjs-hidden');
  19387. linkEl.setAttribute('hidden', 'hidden');
  19388. } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  19389. // keep track of the original for later so we can know if the source originally failed
  19390. tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container
  19391. if (tag.parentNode && !playerElIngest) {
  19392. tag.parentNode.insertBefore(el, tag);
  19393. } // insert the tag as the first child of the player element
  19394. // then manually add it to the children array so that this.addChild
  19395. // will work properly for other components
  19396. //
  19397. // Breaks iPhone, fixed in HTML5 setup.
  19398. prependTo(tag, el);
  19399. this.children_.unshift(tag); // Set lang attr on player to ensure CSS :lang() in consistent with player
  19400. // if it's been set to something different to the doc
  19401. this.el_.setAttribute('lang', this.language_);
  19402. this.el_.setAttribute('translate', 'no');
  19403. this.el_ = el;
  19404. return el;
  19405. }
  19406. /**
  19407. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  19408. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  19409. * behavior.
  19410. *
  19411. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  19412. *
  19413. * @param {string} [value]
  19414. * The value to set the `Player`'s crossOrigin to. If an argument is
  19415. * given, must be one of `anonymous` or `use-credentials`.
  19416. *
  19417. * @return {string|undefined}
  19418. * - The current crossOrigin value of the `Player` when getting.
  19419. * - undefined when setting
  19420. */
  19421. ;
  19422. _proto.crossOrigin = function crossOrigin(value) {
  19423. if (!value) {
  19424. return this.techGet_('crossOrigin');
  19425. }
  19426. if (value !== 'anonymous' && value !== 'use-credentials') {
  19427. log$1.warn("crossOrigin must be \"anonymous\" or \"use-credentials\", given \"" + value + "\"");
  19428. return;
  19429. }
  19430. this.techCall_('setCrossOrigin', value);
  19431. return;
  19432. }
  19433. /**
  19434. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19435. * To get the current width use `currentWidth()`.
  19436. *
  19437. * @param {number} [value]
  19438. * The value to set the `Player`'s width to.
  19439. *
  19440. * @return {number}
  19441. * The current width of the `Player` when getting.
  19442. */
  19443. ;
  19444. _proto.width = function width(value) {
  19445. return this.dimension('width', value);
  19446. }
  19447. /**
  19448. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19449. * To get the current height use `currentheight()`.
  19450. *
  19451. * @param {number} [value]
  19452. * The value to set the `Player`'s heigth to.
  19453. *
  19454. * @return {number}
  19455. * The current height of the `Player` when getting.
  19456. */
  19457. ;
  19458. _proto.height = function height(value) {
  19459. return this.dimension('height', value);
  19460. }
  19461. /**
  19462. * A getter/setter for the `Player`'s width & height.
  19463. *
  19464. * @param {string} dimension
  19465. * This string can be:
  19466. * - 'width'
  19467. * - 'height'
  19468. *
  19469. * @param {number} [value]
  19470. * Value for dimension specified in the first argument.
  19471. *
  19472. * @return {number}
  19473. * The dimension arguments value when getting (width/height).
  19474. */
  19475. ;
  19476. _proto.dimension = function dimension(_dimension, value) {
  19477. var privDimension = _dimension + '_';
  19478. if (value === undefined) {
  19479. return this[privDimension] || 0;
  19480. }
  19481. if (value === '' || value === 'auto') {
  19482. // If an empty string is given, reset the dimension to be automatic
  19483. this[privDimension] = undefined;
  19484. this.updateStyleEl_();
  19485. return;
  19486. }
  19487. var parsedVal = parseFloat(value);
  19488. if (isNaN(parsedVal)) {
  19489. log$1.error("Improper value \"" + value + "\" supplied for for " + _dimension);
  19490. return;
  19491. }
  19492. this[privDimension] = parsedVal;
  19493. this.updateStyleEl_();
  19494. }
  19495. /**
  19496. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19497. *
  19498. * Turning this on will turn off fill mode.
  19499. *
  19500. * @param {boolean} [bool]
  19501. * - A value of true adds the class.
  19502. * - A value of false removes the class.
  19503. * - No value will be a getter.
  19504. *
  19505. * @return {boolean|undefined}
  19506. * - The value of fluid when getting.
  19507. * - `undefined` when setting.
  19508. */
  19509. ;
  19510. _proto.fluid = function fluid(bool) {
  19511. var _this3 = this;
  19512. if (bool === undefined) {
  19513. return !!this.fluid_;
  19514. }
  19515. this.fluid_ = !!bool;
  19516. if (isEvented(this)) {
  19517. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19518. }
  19519. if (bool) {
  19520. this.addClass('vjs-fluid');
  19521. this.fill(false);
  19522. addEventedCallback(this, function () {
  19523. _this3.on(['playerreset', 'resize'], _this3.boundUpdateStyleEl_);
  19524. });
  19525. } else {
  19526. this.removeClass('vjs-fluid');
  19527. }
  19528. this.updateStyleEl_();
  19529. }
  19530. /**
  19531. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  19532. *
  19533. * Turning this on will turn off fluid mode.
  19534. *
  19535. * @param {boolean} [bool]
  19536. * - A value of true adds the class.
  19537. * - A value of false removes the class.
  19538. * - No value will be a getter.
  19539. *
  19540. * @return {boolean|undefined}
  19541. * - The value of fluid when getting.
  19542. * - `undefined` when setting.
  19543. */
  19544. ;
  19545. _proto.fill = function fill(bool) {
  19546. if (bool === undefined) {
  19547. return !!this.fill_;
  19548. }
  19549. this.fill_ = !!bool;
  19550. if (bool) {
  19551. this.addClass('vjs-fill');
  19552. this.fluid(false);
  19553. } else {
  19554. this.removeClass('vjs-fill');
  19555. }
  19556. }
  19557. /**
  19558. * Get/Set the aspect ratio
  19559. *
  19560. * @param {string} [ratio]
  19561. * Aspect ratio for player
  19562. *
  19563. * @return {string|undefined}
  19564. * returns the current aspect ratio when getting
  19565. */
  19566. /**
  19567. * A getter/setter for the `Player`'s aspect ratio.
  19568. *
  19569. * @param {string} [ratio]
  19570. * The value to set the `Player`'s aspect ratio to.
  19571. *
  19572. * @return {string|undefined}
  19573. * - The current aspect ratio of the `Player` when getting.
  19574. * - undefined when setting
  19575. */
  19576. ;
  19577. _proto.aspectRatio = function aspectRatio(ratio) {
  19578. if (ratio === undefined) {
  19579. return this.aspectRatio_;
  19580. } // Check for width:height format
  19581. if (!/^\d+\:\d+$/.test(ratio)) {
  19582. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  19583. }
  19584. this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode,
  19585. // because in fixed mode you could calculate width and height yourself.
  19586. this.fluid(true);
  19587. this.updateStyleEl_();
  19588. }
  19589. /**
  19590. * Update styles of the `Player` element (height, width and aspect ratio).
  19591. *
  19592. * @private
  19593. * @listens Tech#loadedmetadata
  19594. */
  19595. ;
  19596. _proto.updateStyleEl_ = function updateStyleEl_() {
  19597. if (window__default['default'].VIDEOJS_NO_DYNAMIC_STYLE === true) {
  19598. var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  19599. var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  19600. var techEl = this.tech_ && this.tech_.el();
  19601. if (techEl) {
  19602. if (_width >= 0) {
  19603. techEl.width = _width;
  19604. }
  19605. if (_height >= 0) {
  19606. techEl.height = _height;
  19607. }
  19608. }
  19609. return;
  19610. }
  19611. var width;
  19612. var height;
  19613. var aspectRatio;
  19614. var idClass; // The aspect ratio is either used directly or to calculate width and height.
  19615. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  19616. // Use any aspectRatio that's been specifically set
  19617. aspectRatio = this.aspectRatio_;
  19618. } else if (this.videoWidth() > 0) {
  19619. // Otherwise try to get the aspect ratio from the video metadata
  19620. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  19621. } else {
  19622. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  19623. aspectRatio = '16:9';
  19624. } // Get the ratio as a decimal we can use to calculate dimensions
  19625. var ratioParts = aspectRatio.split(':');
  19626. var ratioMultiplier = ratioParts[1] / ratioParts[0];
  19627. if (this.width_ !== undefined) {
  19628. // Use any width that's been specifically set
  19629. width = this.width_;
  19630. } else if (this.height_ !== undefined) {
  19631. // Or calulate the width from the aspect ratio if a height has been set
  19632. width = this.height_ / ratioMultiplier;
  19633. } else {
  19634. // Or use the video's metadata, or use the video el's default of 300
  19635. width = this.videoWidth() || 300;
  19636. }
  19637. if (this.height_ !== undefined) {
  19638. // Use any height that's been specifically set
  19639. height = this.height_;
  19640. } else {
  19641. // Otherwise calculate the height from the ratio and the width
  19642. height = width * ratioMultiplier;
  19643. } // Ensure the CSS class is valid by starting with an alpha character
  19644. if (/^[^a-zA-Z]/.test(this.id())) {
  19645. idClass = 'dimensions-' + this.id();
  19646. } else {
  19647. idClass = this.id() + '-dimensions';
  19648. } // Ensure the right class is still on the player for the style element
  19649. this.addClass(idClass);
  19650. setTextContent(this.styleEl_, "\n ." + idClass + " {\n width: " + width + "px;\n height: " + height + "px;\n }\n\n ." + idClass + ".vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: " + ratioMultiplier * 100 + "%;\n }\n ");
  19651. }
  19652. /**
  19653. * Load/Create an instance of playback {@link Tech} including element
  19654. * and API methods. Then append the `Tech` element in `Player` as a child.
  19655. *
  19656. * @param {string} techName
  19657. * name of the playback technology
  19658. *
  19659. * @param {string} source
  19660. * video source
  19661. *
  19662. * @private
  19663. */
  19664. ;
  19665. _proto.loadTech_ = function loadTech_(techName, source) {
  19666. var _this4 = this;
  19667. // Pause and remove current playback technology
  19668. if (this.tech_) {
  19669. this.unloadTech_();
  19670. }
  19671. var titleTechName = toTitleCase$1(techName);
  19672. var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1); // get rid of the HTML5 video tag as soon as we are using another tech
  19673. if (titleTechName !== 'Html5' && this.tag) {
  19674. Tech.getTech('Html5').disposeMediaElement(this.tag);
  19675. this.tag.player = null;
  19676. this.tag = null;
  19677. }
  19678. this.techName_ = titleTechName; // Turn off API access because we're loading a new tech that might load asynchronously
  19679. this.isReady_ = false;
  19680. var autoplay = this.autoplay(); // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  19681. // because the player is going to handle autoplay on `loadstart`
  19682. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  19683. autoplay = false;
  19684. } // Grab tech-specific options from player options and add source and parent element to use.
  19685. var techOptions = {
  19686. source: source,
  19687. autoplay: autoplay,
  19688. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  19689. 'playerId': this.id(),
  19690. 'techId': this.id() + "_" + camelTechName + "_api",
  19691. 'playsinline': this.options_.playsinline,
  19692. 'preload': this.options_.preload,
  19693. 'loop': this.options_.loop,
  19694. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  19695. 'muted': this.options_.muted,
  19696. 'poster': this.poster(),
  19697. 'language': this.language(),
  19698. 'playerElIngest': this.playerElIngest_ || false,
  19699. 'vtt.js': this.options_['vtt.js'],
  19700. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  19701. 'enableSourceset': this.options_.enableSourceset,
  19702. 'Promise': this.options_.Promise
  19703. };
  19704. ALL.names.forEach(function (name) {
  19705. var props = ALL[name];
  19706. techOptions[props.getterName] = _this4[props.privateName];
  19707. });
  19708. assign(techOptions, this.options_[titleTechName]);
  19709. assign(techOptions, this.options_[camelTechName]);
  19710. assign(techOptions, this.options_[techName.toLowerCase()]);
  19711. if (this.tag) {
  19712. techOptions.tag = this.tag;
  19713. }
  19714. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  19715. techOptions.startTime = this.cache_.currentTime;
  19716. } // Initialize tech instance
  19717. var TechClass = Tech.getTech(techName);
  19718. if (!TechClass) {
  19719. throw new Error("No Tech named '" + titleTechName + "' exists! '" + titleTechName + "' should be registered using videojs.registerTech()'");
  19720. }
  19721. this.tech_ = new TechClass(techOptions); // player.triggerReady is always async, so don't need this to be async
  19722. this.tech_.ready(bind(this, this.handleTechReady_), true);
  19723. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player
  19724. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  19725. _this4.on(_this4.tech_, event, function (e) {
  19726. return _this4["handleTech" + toTitleCase$1(event) + "_"](e);
  19727. });
  19728. });
  19729. Object.keys(TECH_EVENTS_QUEUE).forEach(function (event) {
  19730. _this4.on(_this4.tech_, event, function (eventObj) {
  19731. if (_this4.tech_.playbackRate() === 0 && _this4.tech_.seeking()) {
  19732. _this4.queuedCallbacks_.push({
  19733. callback: _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"].bind(_this4),
  19734. event: eventObj
  19735. });
  19736. return;
  19737. }
  19738. _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"](eventObj);
  19739. });
  19740. });
  19741. this.on(this.tech_, 'loadstart', function (e) {
  19742. return _this4.handleTechLoadStart_(e);
  19743. });
  19744. this.on(this.tech_, 'sourceset', function (e) {
  19745. return _this4.handleTechSourceset_(e);
  19746. });
  19747. this.on(this.tech_, 'waiting', function (e) {
  19748. return _this4.handleTechWaiting_(e);
  19749. });
  19750. this.on(this.tech_, 'ended', function (e) {
  19751. return _this4.handleTechEnded_(e);
  19752. });
  19753. this.on(this.tech_, 'seeking', function (e) {
  19754. return _this4.handleTechSeeking_(e);
  19755. });
  19756. this.on(this.tech_, 'play', function (e) {
  19757. return _this4.handleTechPlay_(e);
  19758. });
  19759. this.on(this.tech_, 'firstplay', function (e) {
  19760. return _this4.handleTechFirstPlay_(e);
  19761. });
  19762. this.on(this.tech_, 'pause', function (e) {
  19763. return _this4.handleTechPause_(e);
  19764. });
  19765. this.on(this.tech_, 'durationchange', function (e) {
  19766. return _this4.handleTechDurationChange_(e);
  19767. });
  19768. this.on(this.tech_, 'fullscreenchange', function (e, data) {
  19769. return _this4.handleTechFullscreenChange_(e, data);
  19770. });
  19771. this.on(this.tech_, 'fullscreenerror', function (e, err) {
  19772. return _this4.handleTechFullscreenError_(e, err);
  19773. });
  19774. this.on(this.tech_, 'enterpictureinpicture', function (e) {
  19775. return _this4.handleTechEnterPictureInPicture_(e);
  19776. });
  19777. this.on(this.tech_, 'leavepictureinpicture', function (e) {
  19778. return _this4.handleTechLeavePictureInPicture_(e);
  19779. });
  19780. this.on(this.tech_, 'error', function (e) {
  19781. return _this4.handleTechError_(e);
  19782. });
  19783. this.on(this.tech_, 'posterchange', function (e) {
  19784. return _this4.handleTechPosterChange_(e);
  19785. });
  19786. this.on(this.tech_, 'textdata', function (e) {
  19787. return _this4.handleTechTextData_(e);
  19788. });
  19789. this.on(this.tech_, 'ratechange', function (e) {
  19790. return _this4.handleTechRateChange_(e);
  19791. });
  19792. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  19793. this.usingNativeControls(this.techGet_('controls'));
  19794. if (this.controls() && !this.usingNativeControls()) {
  19795. this.addTechControlsListeners_();
  19796. } // Add the tech element in the DOM if it was not already there
  19797. // Make sure to not insert the original video element if using Html5
  19798. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  19799. prependTo(this.tech_.el(), this.el());
  19800. } // Get rid of the original video tag reference after the first tech is loaded
  19801. if (this.tag) {
  19802. this.tag.player = null;
  19803. this.tag = null;
  19804. }
  19805. }
  19806. /**
  19807. * Unload and dispose of the current playback {@link Tech}.
  19808. *
  19809. * @private
  19810. */
  19811. ;
  19812. _proto.unloadTech_ = function unloadTech_() {
  19813. var _this5 = this;
  19814. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  19815. ALL.names.forEach(function (name) {
  19816. var props = ALL[name];
  19817. _this5[props.privateName] = _this5[props.getterName]();
  19818. });
  19819. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  19820. this.isReady_ = false;
  19821. this.tech_.dispose();
  19822. this.tech_ = false;
  19823. if (this.isPosterFromTech_) {
  19824. this.poster_ = '';
  19825. this.trigger('posterchange');
  19826. }
  19827. this.isPosterFromTech_ = false;
  19828. }
  19829. /**
  19830. * Return a reference to the current {@link Tech}.
  19831. * It will print a warning by default about the danger of using the tech directly
  19832. * but any argument that is passed in will silence the warning.
  19833. *
  19834. * @param {*} [safety]
  19835. * Anything passed in to silence the warning
  19836. *
  19837. * @return {Tech}
  19838. * The Tech
  19839. */
  19840. ;
  19841. _proto.tech = function tech(safety) {
  19842. if (safety === undefined) {
  19843. 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');
  19844. }
  19845. return this.tech_;
  19846. }
  19847. /**
  19848. * Set up click and touch listeners for the playback element
  19849. *
  19850. * - On desktops: a click on the video itself will toggle playback
  19851. * - On mobile devices: a click on the video toggles controls
  19852. * which is done by toggling the user state between active and
  19853. * inactive
  19854. * - A tap can signal that a user has become active or has become inactive
  19855. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  19856. * quick tap should hide them again (signaling the user is in an inactive
  19857. * viewing state)
  19858. * - In addition to this, we still want the user to be considered inactive after
  19859. * a few seconds of inactivity.
  19860. *
  19861. * > Note: the only part of iOS interaction we can't mimic with this setup
  19862. * is a touch and hold on the video element counting as activity in order to
  19863. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  19864. * on any controls will still keep the user active
  19865. *
  19866. * @private
  19867. */
  19868. ;
  19869. _proto.addTechControlsListeners_ = function addTechControlsListeners_() {
  19870. // Make sure to remove all the previous listeners in case we are called multiple times.
  19871. this.removeTechControlsListeners_();
  19872. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  19873. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_); // If the controls were hidden we don't want that to change without a tap event
  19874. // so we'll check if the controls were already showing before reporting user
  19875. // activity
  19876. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19877. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19878. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap
  19879. // listener cancels out any reportedUserActivity when setting userActive(false)
  19880. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  19881. }
  19882. /**
  19883. * Remove the listeners used for click and tap controls. This is needed for
  19884. * toggling to controls disabled, where a tap/touch should do nothing.
  19885. *
  19886. * @private
  19887. */
  19888. ;
  19889. _proto.removeTechControlsListeners_ = function removeTechControlsListeners_() {
  19890. // We don't want to just use `this.off()` because there might be other needed
  19891. // listeners added by techs that extend this.
  19892. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  19893. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  19894. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  19895. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  19896. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  19897. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  19898. }
  19899. /**
  19900. * Player waits for the tech to be ready
  19901. *
  19902. * @private
  19903. */
  19904. ;
  19905. _proto.handleTechReady_ = function handleTechReady_() {
  19906. this.triggerReady(); // Keep the same volume as before
  19907. if (this.cache_.volume) {
  19908. this.techCall_('setVolume', this.cache_.volume);
  19909. } // Look if the tech found a higher resolution poster while loading
  19910. this.handleTechPosterChange_(); // Update the duration if available
  19911. this.handleTechDurationChange_();
  19912. }
  19913. /**
  19914. * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This
  19915. * function will also trigger {@link Player#firstplay} if it is the first loadstart
  19916. * for a video.
  19917. *
  19918. * @fires Player#loadstart
  19919. * @fires Player#firstplay
  19920. * @listens Tech#loadstart
  19921. * @private
  19922. */
  19923. ;
  19924. _proto.handleTechLoadStart_ = function handleTechLoadStart_() {
  19925. // TODO: Update to use `emptied` event instead. See #1277.
  19926. this.removeClass('vjs-ended');
  19927. this.removeClass('vjs-seeking'); // reset the error state
  19928. this.error(null); // Update the duration
  19929. this.handleTechDurationChange_(); // If it's already playing we want to trigger a firstplay event now.
  19930. // The firstplay event relies on both the play and loadstart events
  19931. // which can happen in any order for a new source
  19932. if (!this.paused()) {
  19933. /**
  19934. * Fired when the user agent begins looking for media data
  19935. *
  19936. * @event Player#loadstart
  19937. * @type {EventTarget~Event}
  19938. */
  19939. this.trigger('loadstart');
  19940. this.trigger('firstplay');
  19941. } else {
  19942. // reset the hasStarted state
  19943. this.hasStarted(false);
  19944. this.trigger('loadstart');
  19945. } // autoplay happens after loadstart for the browser,
  19946. // so we mimic that behavior
  19947. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  19948. }
  19949. /**
  19950. * Handle autoplay string values, rather than the typical boolean
  19951. * values that should be handled by the tech. Note that this is not
  19952. * part of any specification. Valid values and what they do can be
  19953. * found on the autoplay getter at Player#autoplay()
  19954. */
  19955. ;
  19956. _proto.manualAutoplay_ = function manualAutoplay_(type) {
  19957. var _this6 = this;
  19958. if (!this.tech_ || typeof type !== 'string') {
  19959. return;
  19960. } // Save original muted() value, set muted to true, and attempt to play().
  19961. // On promise rejection, restore muted from saved value
  19962. var resolveMuted = function resolveMuted() {
  19963. var previouslyMuted = _this6.muted();
  19964. _this6.muted(true);
  19965. var restoreMuted = function restoreMuted() {
  19966. _this6.muted(previouslyMuted);
  19967. }; // restore muted on play terminatation
  19968. _this6.playTerminatedQueue_.push(restoreMuted);
  19969. var mutedPromise = _this6.play();
  19970. if (!isPromise(mutedPromise)) {
  19971. return;
  19972. }
  19973. return mutedPromise["catch"](function (err) {
  19974. restoreMuted();
  19975. throw new Error("Rejection at manualAutoplay. Restoring muted value. " + (err ? err : ''));
  19976. });
  19977. };
  19978. var promise; // if muted defaults to true
  19979. // the only thing we can do is call play
  19980. if (type === 'any' && !this.muted()) {
  19981. promise = this.play();
  19982. if (isPromise(promise)) {
  19983. promise = promise["catch"](resolveMuted);
  19984. }
  19985. } else if (type === 'muted' && !this.muted()) {
  19986. promise = resolveMuted();
  19987. } else {
  19988. promise = this.play();
  19989. }
  19990. if (!isPromise(promise)) {
  19991. return;
  19992. }
  19993. return promise.then(function () {
  19994. _this6.trigger({
  19995. type: 'autoplay-success',
  19996. autoplay: type
  19997. });
  19998. })["catch"](function () {
  19999. _this6.trigger({
  20000. type: 'autoplay-failure',
  20001. autoplay: type
  20002. });
  20003. });
  20004. }
  20005. /**
  20006. * Update the internal source caches so that we return the correct source from
  20007. * `src()`, `currentSource()`, and `currentSources()`.
  20008. *
  20009. * > Note: `currentSources` will not be updated if the source that is passed in exists
  20010. * in the current `currentSources` cache.
  20011. *
  20012. *
  20013. * @param {Tech~SourceObject} srcObj
  20014. * A string or object source to update our caches to.
  20015. */
  20016. ;
  20017. _proto.updateSourceCaches_ = function updateSourceCaches_(srcObj) {
  20018. if (srcObj === void 0) {
  20019. srcObj = '';
  20020. }
  20021. var src = srcObj;
  20022. var type = '';
  20023. if (typeof src !== 'string') {
  20024. src = srcObj.src;
  20025. type = srcObj.type;
  20026. } // make sure all the caches are set to default values
  20027. // to prevent null checking
  20028. this.cache_.source = this.cache_.source || {};
  20029. this.cache_.sources = this.cache_.sources || []; // try to get the type of the src that was passed in
  20030. if (src && !type) {
  20031. type = findMimetype(this, src);
  20032. } // update `currentSource` cache always
  20033. this.cache_.source = mergeOptions$3({}, srcObj, {
  20034. src: src,
  20035. type: type
  20036. });
  20037. var matchingSources = this.cache_.sources.filter(function (s) {
  20038. return s.src && s.src === src;
  20039. });
  20040. var sourceElSources = [];
  20041. var sourceEls = this.$$('source');
  20042. var matchingSourceEls = [];
  20043. for (var i = 0; i < sourceEls.length; i++) {
  20044. var sourceObj = getAttributes(sourceEls[i]);
  20045. sourceElSources.push(sourceObj);
  20046. if (sourceObj.src && sourceObj.src === src) {
  20047. matchingSourceEls.push(sourceObj.src);
  20048. }
  20049. } // if we have matching source els but not matching sources
  20050. // the current source cache is not up to date
  20051. if (matchingSourceEls.length && !matchingSources.length) {
  20052. this.cache_.sources = sourceElSources; // if we don't have matching source or source els set the
  20053. // sources cache to the `currentSource` cache
  20054. } else if (!matchingSources.length) {
  20055. this.cache_.sources = [this.cache_.source];
  20056. } // update the tech `src` cache
  20057. this.cache_.src = src;
  20058. }
  20059. /**
  20060. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  20061. * causing the media element to reload.
  20062. *
  20063. * It will fire for the initial source and each subsequent source.
  20064. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  20065. *
  20066. * The event object for this event contains a `src` property that will contain the source
  20067. * that was available when the event was triggered. This is generally only necessary if Video.js
  20068. * is switching techs while the source was being changed.
  20069. *
  20070. * It is also fired when `load` is called on the player (or media element)
  20071. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  20072. * says that the resource selection algorithm needs to be aborted and restarted.
  20073. * In this case, it is very likely that the `src` property will be set to the
  20074. * empty string `""` to indicate we do not know what the source will be but
  20075. * that it is changing.
  20076. *
  20077. * *This event is currently still experimental and may change in minor releases.*
  20078. * __To use this, pass `enableSourceset` option to the player.__
  20079. *
  20080. * @event Player#sourceset
  20081. * @type {EventTarget~Event}
  20082. * @prop {string} src
  20083. * The source url available when the `sourceset` was triggered.
  20084. * It will be an empty string if we cannot know what the source is
  20085. * but know that the source will change.
  20086. */
  20087. /**
  20088. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  20089. *
  20090. * @fires Player#sourceset
  20091. * @listens Tech#sourceset
  20092. * @private
  20093. */
  20094. ;
  20095. _proto.handleTechSourceset_ = function handleTechSourceset_(event) {
  20096. var _this7 = this;
  20097. // only update the source cache when the source
  20098. // was not updated using the player api
  20099. if (!this.changingSrc_) {
  20100. var updateSourceCaches = function updateSourceCaches(src) {
  20101. return _this7.updateSourceCaches_(src);
  20102. };
  20103. var playerSrc = this.currentSource().src;
  20104. var eventSrc = event.src; // if we have a playerSrc that is not a blob, and a tech src that is a blob
  20105. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  20106. // if both the tech source and the player source were updated we assume
  20107. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  20108. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  20109. updateSourceCaches = function updateSourceCaches() {};
  20110. }
  20111. } // update the source to the initial source right away
  20112. // in some cases this will be empty string
  20113. updateSourceCaches(eventSrc); // if the `sourceset` `src` was an empty string
  20114. // wait for a `loadstart` to update the cache to `currentSrc`.
  20115. // If a sourceset happens before a `loadstart`, we reset the state
  20116. if (!event.src) {
  20117. this.tech_.any(['sourceset', 'loadstart'], function (e) {
  20118. // if a sourceset happens before a `loadstart` there
  20119. // is nothing to do as this `handleTechSourceset_`
  20120. // will be called again and this will be handled there.
  20121. if (e.type === 'sourceset') {
  20122. return;
  20123. }
  20124. var techSrc = _this7.techGet('currentSrc');
  20125. _this7.lastSource_.tech = techSrc;
  20126. _this7.updateSourceCaches_(techSrc);
  20127. });
  20128. }
  20129. }
  20130. this.lastSource_ = {
  20131. player: this.currentSource().src,
  20132. tech: event.src
  20133. };
  20134. this.trigger({
  20135. src: event.src,
  20136. type: 'sourceset'
  20137. });
  20138. }
  20139. /**
  20140. * Add/remove the vjs-has-started class
  20141. *
  20142. * @fires Player#firstplay
  20143. *
  20144. * @param {boolean} request
  20145. * - true: adds the class
  20146. * - false: remove the class
  20147. *
  20148. * @return {boolean}
  20149. * the boolean value of hasStarted_
  20150. */
  20151. ;
  20152. _proto.hasStarted = function hasStarted(request) {
  20153. if (request === undefined) {
  20154. // act as getter, if we have no request to change
  20155. return this.hasStarted_;
  20156. }
  20157. if (request === this.hasStarted_) {
  20158. return;
  20159. }
  20160. this.hasStarted_ = request;
  20161. if (this.hasStarted_) {
  20162. this.addClass('vjs-has-started');
  20163. this.trigger('firstplay');
  20164. } else {
  20165. this.removeClass('vjs-has-started');
  20166. }
  20167. }
  20168. /**
  20169. * Fired whenever the media begins or resumes playback
  20170. *
  20171. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  20172. * @fires Player#play
  20173. * @listens Tech#play
  20174. * @private
  20175. */
  20176. ;
  20177. _proto.handleTechPlay_ = function handleTechPlay_() {
  20178. this.removeClass('vjs-ended');
  20179. this.removeClass('vjs-paused');
  20180. this.addClass('vjs-playing'); // hide the poster when the user hits play
  20181. this.hasStarted(true);
  20182. /**
  20183. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  20184. * playback has started or resumed.
  20185. *
  20186. * @event Player#play
  20187. * @type {EventTarget~Event}
  20188. */
  20189. this.trigger('play');
  20190. }
  20191. /**
  20192. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  20193. *
  20194. * If there were any events queued while the playback rate was zero, fire
  20195. * those events now.
  20196. *
  20197. * @private
  20198. * @method Player#handleTechRateChange_
  20199. * @fires Player#ratechange
  20200. * @listens Tech#ratechange
  20201. */
  20202. ;
  20203. _proto.handleTechRateChange_ = function handleTechRateChange_() {
  20204. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  20205. this.queuedCallbacks_.forEach(function (queued) {
  20206. return queued.callback(queued.event);
  20207. });
  20208. this.queuedCallbacks_ = [];
  20209. }
  20210. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  20211. /**
  20212. * Fires when the playing speed of the audio/video is changed
  20213. *
  20214. * @event Player#ratechange
  20215. * @type {event}
  20216. */
  20217. this.trigger('ratechange');
  20218. }
  20219. /**
  20220. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  20221. *
  20222. * @fires Player#waiting
  20223. * @listens Tech#waiting
  20224. * @private
  20225. */
  20226. ;
  20227. _proto.handleTechWaiting_ = function handleTechWaiting_() {
  20228. var _this8 = this;
  20229. this.addClass('vjs-waiting');
  20230. /**
  20231. * A readyState change on the DOM element has caused playback to stop.
  20232. *
  20233. * @event Player#waiting
  20234. * @type {EventTarget~Event}
  20235. */
  20236. this.trigger('waiting'); // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  20237. // premature removal of the waiting class, wait for the time to change.
  20238. var timeWhenWaiting = this.currentTime();
  20239. var timeUpdateListener = function timeUpdateListener() {
  20240. if (timeWhenWaiting !== _this8.currentTime()) {
  20241. _this8.removeClass('vjs-waiting');
  20242. _this8.off('timeupdate', timeUpdateListener);
  20243. }
  20244. };
  20245. this.on('timeupdate', timeUpdateListener);
  20246. }
  20247. /**
  20248. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  20249. * > Note: This is not consistent between browsers. See #1351
  20250. *
  20251. * @fires Player#canplay
  20252. * @listens Tech#canplay
  20253. * @private
  20254. */
  20255. ;
  20256. _proto.handleTechCanPlay_ = function handleTechCanPlay_() {
  20257. this.removeClass('vjs-waiting');
  20258. /**
  20259. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  20260. *
  20261. * @event Player#canplay
  20262. * @type {EventTarget~Event}
  20263. */
  20264. this.trigger('canplay');
  20265. }
  20266. /**
  20267. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  20268. *
  20269. * @fires Player#canplaythrough
  20270. * @listens Tech#canplaythrough
  20271. * @private
  20272. */
  20273. ;
  20274. _proto.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
  20275. this.removeClass('vjs-waiting');
  20276. /**
  20277. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  20278. * entire media file can be played without buffering.
  20279. *
  20280. * @event Player#canplaythrough
  20281. * @type {EventTarget~Event}
  20282. */
  20283. this.trigger('canplaythrough');
  20284. }
  20285. /**
  20286. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  20287. *
  20288. * @fires Player#playing
  20289. * @listens Tech#playing
  20290. * @private
  20291. */
  20292. ;
  20293. _proto.handleTechPlaying_ = function handleTechPlaying_() {
  20294. this.removeClass('vjs-waiting');
  20295. /**
  20296. * The media is no longer blocked from playback, and has started playing.
  20297. *
  20298. * @event Player#playing
  20299. * @type {EventTarget~Event}
  20300. */
  20301. this.trigger('playing');
  20302. }
  20303. /**
  20304. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  20305. *
  20306. * @fires Player#seeking
  20307. * @listens Tech#seeking
  20308. * @private
  20309. */
  20310. ;
  20311. _proto.handleTechSeeking_ = function handleTechSeeking_() {
  20312. this.addClass('vjs-seeking');
  20313. /**
  20314. * Fired whenever the player is jumping to a new time
  20315. *
  20316. * @event Player#seeking
  20317. * @type {EventTarget~Event}
  20318. */
  20319. this.trigger('seeking');
  20320. }
  20321. /**
  20322. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  20323. *
  20324. * @fires Player#seeked
  20325. * @listens Tech#seeked
  20326. * @private
  20327. */
  20328. ;
  20329. _proto.handleTechSeeked_ = function handleTechSeeked_() {
  20330. this.removeClass('vjs-seeking');
  20331. this.removeClass('vjs-ended');
  20332. /**
  20333. * Fired when the player has finished jumping to a new time
  20334. *
  20335. * @event Player#seeked
  20336. * @type {EventTarget~Event}
  20337. */
  20338. this.trigger('seeked');
  20339. }
  20340. /**
  20341. * Retrigger the `firstplay` event that was triggered by the {@link Tech}.
  20342. *
  20343. * @fires Player#firstplay
  20344. * @listens Tech#firstplay
  20345. * @deprecated As of 6.0 firstplay event is deprecated.
  20346. * As of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated.
  20347. * @private
  20348. */
  20349. ;
  20350. _proto.handleTechFirstPlay_ = function handleTechFirstPlay_() {
  20351. // If the first starttime attribute is specified
  20352. // then we will start at the given offset in seconds
  20353. if (this.options_.starttime) {
  20354. log$1.warn('Passing the `starttime` option to the player will be deprecated in 6.0');
  20355. this.currentTime(this.options_.starttime);
  20356. }
  20357. this.addClass('vjs-has-started');
  20358. /**
  20359. * Fired the first time a video is played. Not part of the HLS spec, and this is
  20360. * probably not the best implementation yet, so use sparingly. If you don't have a
  20361. * reason to prevent playback, use `myPlayer.one('play');` instead.
  20362. *
  20363. * @event Player#firstplay
  20364. * @deprecated As of 6.0 firstplay event is deprecated.
  20365. * @type {EventTarget~Event}
  20366. */
  20367. this.trigger('firstplay');
  20368. }
  20369. /**
  20370. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  20371. *
  20372. * @fires Player#pause
  20373. * @listens Tech#pause
  20374. * @private
  20375. */
  20376. ;
  20377. _proto.handleTechPause_ = function handleTechPause_() {
  20378. this.removeClass('vjs-playing');
  20379. this.addClass('vjs-paused');
  20380. /**
  20381. * Fired whenever the media has been paused
  20382. *
  20383. * @event Player#pause
  20384. * @type {EventTarget~Event}
  20385. */
  20386. this.trigger('pause');
  20387. }
  20388. /**
  20389. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  20390. *
  20391. * @fires Player#ended
  20392. * @listens Tech#ended
  20393. * @private
  20394. */
  20395. ;
  20396. _proto.handleTechEnded_ = function handleTechEnded_() {
  20397. this.addClass('vjs-ended');
  20398. this.removeClass('vjs-waiting');
  20399. if (this.options_.loop) {
  20400. this.currentTime(0);
  20401. this.play();
  20402. } else if (!this.paused()) {
  20403. this.pause();
  20404. }
  20405. /**
  20406. * Fired when the end of the media resource is reached (currentTime == duration)
  20407. *
  20408. * @event Player#ended
  20409. * @type {EventTarget~Event}
  20410. */
  20411. this.trigger('ended');
  20412. }
  20413. /**
  20414. * Fired when the duration of the media resource is first known or changed
  20415. *
  20416. * @listens Tech#durationchange
  20417. * @private
  20418. */
  20419. ;
  20420. _proto.handleTechDurationChange_ = function handleTechDurationChange_() {
  20421. this.duration(this.techGet_('duration'));
  20422. }
  20423. /**
  20424. * Handle a click on the media element to play/pause
  20425. *
  20426. * @param {EventTarget~Event} event
  20427. * the event that caused this function to trigger
  20428. *
  20429. * @listens Tech#click
  20430. * @private
  20431. */
  20432. ;
  20433. _proto.handleTechClick_ = function handleTechClick_(event) {
  20434. // When controls are disabled a click should not toggle playback because
  20435. // the click is considered a control
  20436. if (!this.controls_) {
  20437. return;
  20438. }
  20439. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  20440. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  20441. this.options_.userActions.click.call(this, event);
  20442. } else if (this.paused()) {
  20443. silencePromise(this.play());
  20444. } else {
  20445. this.pause();
  20446. }
  20447. }
  20448. }
  20449. /**
  20450. * Handle a double-click on the media element to enter/exit fullscreen
  20451. *
  20452. * @param {EventTarget~Event} event
  20453. * the event that caused this function to trigger
  20454. *
  20455. * @listens Tech#dblclick
  20456. * @private
  20457. */
  20458. ;
  20459. _proto.handleTechDoubleClick_ = function handleTechDoubleClick_(event) {
  20460. if (!this.controls_) {
  20461. return;
  20462. } // we do not want to toggle fullscreen state
  20463. // when double-clicking inside a control bar or a modal
  20464. var inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), function (el) {
  20465. return el.contains(event.target);
  20466. });
  20467. if (!inAllowedEls) {
  20468. /*
  20469. * options.userActions.doubleClick
  20470. *
  20471. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  20472. * Set to `false` to disable double-click handling
  20473. * Set to a function to substitute an external double-click handler
  20474. */
  20475. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  20476. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  20477. this.options_.userActions.doubleClick.call(this, event);
  20478. } else if (this.isFullscreen()) {
  20479. this.exitFullscreen();
  20480. } else {
  20481. this.requestFullscreen();
  20482. }
  20483. }
  20484. }
  20485. }
  20486. /**
  20487. * Handle a tap on the media element. It will toggle the user
  20488. * activity state, which hides and shows the controls.
  20489. *
  20490. * @listens Tech#tap
  20491. * @private
  20492. */
  20493. ;
  20494. _proto.handleTechTap_ = function handleTechTap_() {
  20495. this.userActive(!this.userActive());
  20496. }
  20497. /**
  20498. * Handle touch to start
  20499. *
  20500. * @listens Tech#touchstart
  20501. * @private
  20502. */
  20503. ;
  20504. _proto.handleTechTouchStart_ = function handleTechTouchStart_() {
  20505. this.userWasActive = this.userActive();
  20506. }
  20507. /**
  20508. * Handle touch to move
  20509. *
  20510. * @listens Tech#touchmove
  20511. * @private
  20512. */
  20513. ;
  20514. _proto.handleTechTouchMove_ = function handleTechTouchMove_() {
  20515. if (this.userWasActive) {
  20516. this.reportUserActivity();
  20517. }
  20518. }
  20519. /**
  20520. * Handle touch to end
  20521. *
  20522. * @param {EventTarget~Event} event
  20523. * the touchend event that triggered
  20524. * this function
  20525. *
  20526. * @listens Tech#touchend
  20527. * @private
  20528. */
  20529. ;
  20530. _proto.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
  20531. // Stop the mouse events from also happening
  20532. if (event.cancelable) {
  20533. event.preventDefault();
  20534. }
  20535. }
  20536. /**
  20537. * native click events on the SWF aren't triggered on IE11, Win8.1RT
  20538. * use stageclick events triggered from inside the SWF instead
  20539. *
  20540. * @private
  20541. * @listens stageclick
  20542. */
  20543. ;
  20544. _proto.handleStageClick_ = function handleStageClick_() {
  20545. this.reportUserActivity();
  20546. }
  20547. /**
  20548. * @private
  20549. */
  20550. ;
  20551. _proto.toggleFullscreenClass_ = function toggleFullscreenClass_() {
  20552. if (this.isFullscreen()) {
  20553. this.addClass('vjs-fullscreen');
  20554. } else {
  20555. this.removeClass('vjs-fullscreen');
  20556. }
  20557. }
  20558. /**
  20559. * when the document fschange event triggers it calls this
  20560. */
  20561. ;
  20562. _proto.documentFullscreenChange_ = function documentFullscreenChange_(e) {
  20563. var targetPlayer = e.target.player; // if another player was fullscreen
  20564. // do a null check for targetPlayer because older firefox's would put document as e.target
  20565. if (targetPlayer && targetPlayer !== this) {
  20566. return;
  20567. }
  20568. var el = this.el();
  20569. var isFs = document__default['default'][this.fsApi_.fullscreenElement] === el;
  20570. if (!isFs && el.matches) {
  20571. isFs = el.matches(':' + this.fsApi_.fullscreen);
  20572. } else if (!isFs && el.msMatchesSelector) {
  20573. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  20574. }
  20575. this.isFullscreen(isFs);
  20576. }
  20577. /**
  20578. * Handle Tech Fullscreen Change
  20579. *
  20580. * @param {EventTarget~Event} event
  20581. * the fullscreenchange event that triggered this function
  20582. *
  20583. * @param {Object} data
  20584. * the data that was sent with the event
  20585. *
  20586. * @private
  20587. * @listens Tech#fullscreenchange
  20588. * @fires Player#fullscreenchange
  20589. */
  20590. ;
  20591. _proto.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
  20592. var _this9 = this;
  20593. if (data) {
  20594. if (data.nativeIOSFullscreen) {
  20595. this.addClass('vjs-ios-native-fs');
  20596. this.tech_.one('webkitendfullscreen', function () {
  20597. _this9.removeClass('vjs-ios-native-fs');
  20598. });
  20599. }
  20600. this.isFullscreen(data.isFullscreen);
  20601. }
  20602. };
  20603. _proto.handleTechFullscreenError_ = function handleTechFullscreenError_(event, err) {
  20604. this.trigger('fullscreenerror', err);
  20605. }
  20606. /**
  20607. * @private
  20608. */
  20609. ;
  20610. _proto.togglePictureInPictureClass_ = function togglePictureInPictureClass_() {
  20611. if (this.isInPictureInPicture()) {
  20612. this.addClass('vjs-picture-in-picture');
  20613. } else {
  20614. this.removeClass('vjs-picture-in-picture');
  20615. }
  20616. }
  20617. /**
  20618. * Handle Tech Enter Picture-in-Picture.
  20619. *
  20620. * @param {EventTarget~Event} event
  20621. * the enterpictureinpicture event that triggered this function
  20622. *
  20623. * @private
  20624. * @listens Tech#enterpictureinpicture
  20625. */
  20626. ;
  20627. _proto.handleTechEnterPictureInPicture_ = function handleTechEnterPictureInPicture_(event) {
  20628. this.isInPictureInPicture(true);
  20629. }
  20630. /**
  20631. * Handle Tech Leave Picture-in-Picture.
  20632. *
  20633. * @param {EventTarget~Event} event
  20634. * the leavepictureinpicture event that triggered this function
  20635. *
  20636. * @private
  20637. * @listens Tech#leavepictureinpicture
  20638. */
  20639. ;
  20640. _proto.handleTechLeavePictureInPicture_ = function handleTechLeavePictureInPicture_(event) {
  20641. this.isInPictureInPicture(false);
  20642. }
  20643. /**
  20644. * Fires when an error occurred during the loading of an audio/video.
  20645. *
  20646. * @private
  20647. * @listens Tech#error
  20648. */
  20649. ;
  20650. _proto.handleTechError_ = function handleTechError_() {
  20651. var error = this.tech_.error();
  20652. this.error(error);
  20653. }
  20654. /**
  20655. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  20656. *
  20657. * @fires Player#textdata
  20658. * @listens Tech#textdata
  20659. * @private
  20660. */
  20661. ;
  20662. _proto.handleTechTextData_ = function handleTechTextData_() {
  20663. var data = null;
  20664. if (arguments.length > 1) {
  20665. data = arguments[1];
  20666. }
  20667. /**
  20668. * Fires when we get a textdata event from tech
  20669. *
  20670. * @event Player#textdata
  20671. * @type {EventTarget~Event}
  20672. */
  20673. this.trigger('textdata', data);
  20674. }
  20675. /**
  20676. * Get object for cached values.
  20677. *
  20678. * @return {Object}
  20679. * get the current object cache
  20680. */
  20681. ;
  20682. _proto.getCache = function getCache() {
  20683. return this.cache_;
  20684. }
  20685. /**
  20686. * Resets the internal cache object.
  20687. *
  20688. * Using this function outside the player constructor or reset method may
  20689. * have unintended side-effects.
  20690. *
  20691. * @private
  20692. */
  20693. ;
  20694. _proto.resetCache_ = function resetCache_() {
  20695. this.cache_ = {
  20696. // Right now, the currentTime is not _really_ cached because it is always
  20697. // retrieved from the tech (see: currentTime). However, for completeness,
  20698. // we set it to zero here to ensure that if we do start actually caching
  20699. // it, we reset it along with everything else.
  20700. currentTime: 0,
  20701. initTime: 0,
  20702. inactivityTimeout: this.options_.inactivityTimeout,
  20703. duration: NaN,
  20704. lastVolume: 1,
  20705. lastPlaybackRate: this.defaultPlaybackRate(),
  20706. media: null,
  20707. src: '',
  20708. source: {},
  20709. sources: [],
  20710. playbackRates: [],
  20711. volume: 1
  20712. };
  20713. }
  20714. /**
  20715. * Pass values to the playback tech
  20716. *
  20717. * @param {string} [method]
  20718. * the method to call
  20719. *
  20720. * @param {Object} arg
  20721. * the argument to pass
  20722. *
  20723. * @private
  20724. */
  20725. ;
  20726. _proto.techCall_ = function techCall_(method, arg) {
  20727. // If it's not ready yet, call method when it is
  20728. this.ready(function () {
  20729. if (method in allowedSetters) {
  20730. return set(this.middleware_, this.tech_, method, arg);
  20731. } else if (method in allowedMediators) {
  20732. return mediate(this.middleware_, this.tech_, method, arg);
  20733. }
  20734. try {
  20735. if (this.tech_) {
  20736. this.tech_[method](arg);
  20737. }
  20738. } catch (e) {
  20739. log$1(e);
  20740. throw e;
  20741. }
  20742. }, true);
  20743. }
  20744. /**
  20745. * Get calls can't wait for the tech, and sometimes don't need to.
  20746. *
  20747. * @param {string} method
  20748. * Tech method
  20749. *
  20750. * @return {Function|undefined}
  20751. * the method or undefined
  20752. *
  20753. * @private
  20754. */
  20755. ;
  20756. _proto.techGet_ = function techGet_(method) {
  20757. if (!this.tech_ || !this.tech_.isReady_) {
  20758. return;
  20759. }
  20760. if (method in allowedGetters) {
  20761. return get(this.middleware_, this.tech_, method);
  20762. } else if (method in allowedMediators) {
  20763. return mediate(this.middleware_, this.tech_, method);
  20764. } // Flash likes to die and reload when you hide or reposition it.
  20765. // In these cases the object methods go away and we get errors.
  20766. // TODO: Is this needed for techs other than Flash?
  20767. // When that happens we'll catch the errors and inform tech that it's not ready any more.
  20768. try {
  20769. return this.tech_[method]();
  20770. } catch (e) {
  20771. // When building additional tech libs, an expected method may not be defined yet
  20772. if (this.tech_[method] === undefined) {
  20773. log$1("Video.js: " + method + " method not defined for " + this.techName_ + " playback technology.", e);
  20774. throw e;
  20775. } // When a method isn't available on the object it throws a TypeError
  20776. if (e.name === 'TypeError') {
  20777. log$1("Video.js: " + method + " unavailable on " + this.techName_ + " playback technology element.", e);
  20778. this.tech_.isReady_ = false;
  20779. throw e;
  20780. } // If error unknown, just log and throw
  20781. log$1(e);
  20782. throw e;
  20783. }
  20784. }
  20785. /**
  20786. * Attempt to begin playback at the first opportunity.
  20787. *
  20788. * @return {Promise|undefined}
  20789. * Returns a promise if the browser supports Promises (or one
  20790. * was passed in as an option). This promise will be resolved on
  20791. * the return value of play. If this is undefined it will fulfill the
  20792. * promise chain otherwise the promise chain will be fulfilled when
  20793. * the promise from play is fulfilled.
  20794. */
  20795. ;
  20796. _proto.play = function play() {
  20797. var _this10 = this;
  20798. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  20799. if (PromiseClass) {
  20800. return new PromiseClass(function (resolve) {
  20801. _this10.play_(resolve);
  20802. });
  20803. }
  20804. return this.play_();
  20805. }
  20806. /**
  20807. * The actual logic for play, takes a callback that will be resolved on the
  20808. * return value of play. This allows us to resolve to the play promise if there
  20809. * is one on modern browsers.
  20810. *
  20811. * @private
  20812. * @param {Function} [callback]
  20813. * The callback that should be called when the techs play is actually called
  20814. */
  20815. ;
  20816. _proto.play_ = function play_(callback) {
  20817. var _this11 = this;
  20818. if (callback === void 0) {
  20819. callback = silencePromise;
  20820. }
  20821. this.playCallbacks_.push(callback);
  20822. var isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  20823. var isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS); // treat calls to play_ somewhat like the `one` event function
  20824. if (this.waitToPlay_) {
  20825. this.off(['ready', 'loadstart'], this.waitToPlay_);
  20826. this.waitToPlay_ = null;
  20827. } // if the player/tech is not ready or the src itself is not ready
  20828. // queue up a call to play on `ready` or `loadstart`
  20829. if (!this.isReady_ || !isSrcReady) {
  20830. this.waitToPlay_ = function (e) {
  20831. _this11.play_();
  20832. };
  20833. this.one(['ready', 'loadstart'], this.waitToPlay_); // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  20834. // in that case, we need to prime the video element by calling load so it'll be ready in time
  20835. if (!isSrcReady && isSafariOrIOS) {
  20836. this.load();
  20837. }
  20838. return;
  20839. } // If the player/tech is ready and we have a source, we can attempt playback.
  20840. var val = this.techGet_('play'); // For native playback, reset the progress bar if we get a play call from a replay.
  20841. var isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  20842. if (isNativeReplay) {
  20843. this.resetProgressBar_();
  20844. } // play was terminated if the returned value is null
  20845. if (val === null) {
  20846. this.runPlayTerminatedQueue_();
  20847. } else {
  20848. this.runPlayCallbacks_(val);
  20849. }
  20850. }
  20851. /**
  20852. * These functions will be run when if play is terminated. If play
  20853. * runPlayCallbacks_ is run these function will not be run. This allows us
  20854. * to differenciate between a terminated play and an actual call to play.
  20855. */
  20856. ;
  20857. _proto.runPlayTerminatedQueue_ = function runPlayTerminatedQueue_() {
  20858. var queue = this.playTerminatedQueue_.slice(0);
  20859. this.playTerminatedQueue_ = [];
  20860. queue.forEach(function (q) {
  20861. q();
  20862. });
  20863. }
  20864. /**
  20865. * When a callback to play is delayed we have to run these
  20866. * callbacks when play is actually called on the tech. This function
  20867. * runs the callbacks that were delayed and accepts the return value
  20868. * from the tech.
  20869. *
  20870. * @param {undefined|Promise} val
  20871. * The return value from the tech.
  20872. */
  20873. ;
  20874. _proto.runPlayCallbacks_ = function runPlayCallbacks_(val) {
  20875. var callbacks = this.playCallbacks_.slice(0);
  20876. this.playCallbacks_ = []; // clear play terminatedQueue since we finished a real play
  20877. this.playTerminatedQueue_ = [];
  20878. callbacks.forEach(function (cb) {
  20879. cb(val);
  20880. });
  20881. }
  20882. /**
  20883. * Pause the video playback
  20884. *
  20885. * @return {Player}
  20886. * A reference to the player object this function was called on
  20887. */
  20888. ;
  20889. _proto.pause = function pause() {
  20890. this.techCall_('pause');
  20891. }
  20892. /**
  20893. * Check if the player is paused or has yet to play
  20894. *
  20895. * @return {boolean}
  20896. * - false: if the media is currently playing
  20897. * - true: if media is not currently playing
  20898. */
  20899. ;
  20900. _proto.paused = function paused() {
  20901. // The initial state of paused should be true (in Safari it's actually false)
  20902. return this.techGet_('paused') === false ? false : true;
  20903. }
  20904. /**
  20905. * Get a TimeRange object representing the current ranges of time that the user
  20906. * has played.
  20907. *
  20908. * @return {TimeRange}
  20909. * A time range object that represents all the increments of time that have
  20910. * been played.
  20911. */
  20912. ;
  20913. _proto.played = function played() {
  20914. return this.techGet_('played') || createTimeRanges(0, 0);
  20915. }
  20916. /**
  20917. * Returns whether or not the user is "scrubbing". Scrubbing is
  20918. * when the user has clicked the progress bar handle and is
  20919. * dragging it along the progress bar.
  20920. *
  20921. * @param {boolean} [isScrubbing]
  20922. * whether the user is or is not scrubbing
  20923. *
  20924. * @return {boolean}
  20925. * The value of scrubbing when getting
  20926. */
  20927. ;
  20928. _proto.scrubbing = function scrubbing(isScrubbing) {
  20929. if (typeof isScrubbing === 'undefined') {
  20930. return this.scrubbing_;
  20931. }
  20932. this.scrubbing_ = !!isScrubbing;
  20933. this.techCall_('setScrubbing', this.scrubbing_);
  20934. if (isScrubbing) {
  20935. this.addClass('vjs-scrubbing');
  20936. } else {
  20937. this.removeClass('vjs-scrubbing');
  20938. }
  20939. }
  20940. /**
  20941. * Get or set the current time (in seconds)
  20942. *
  20943. * @param {number|string} [seconds]
  20944. * The time to seek to in seconds
  20945. *
  20946. * @return {number}
  20947. * - the current time in seconds when getting
  20948. */
  20949. ;
  20950. _proto.currentTime = function currentTime(seconds) {
  20951. if (typeof seconds !== 'undefined') {
  20952. if (seconds < 0) {
  20953. seconds = 0;
  20954. }
  20955. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  20956. this.cache_.initTime = seconds;
  20957. this.off('canplay', this.boundApplyInitTime_);
  20958. this.one('canplay', this.boundApplyInitTime_);
  20959. return;
  20960. }
  20961. this.techCall_('setCurrentTime', seconds);
  20962. this.cache_.initTime = 0;
  20963. return;
  20964. } // cache last currentTime and return. default to 0 seconds
  20965. //
  20966. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  20967. // currentTime when scrubbing, but may not provide much performance benefit afterall.
  20968. // Should be tested. Also something has to read the actual current time or the cache will
  20969. // never get updated.
  20970. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  20971. return this.cache_.currentTime;
  20972. }
  20973. /**
  20974. * Apply the value of initTime stored in cache as currentTime.
  20975. *
  20976. * @private
  20977. */
  20978. ;
  20979. _proto.applyInitTime_ = function applyInitTime_() {
  20980. this.currentTime(this.cache_.initTime);
  20981. }
  20982. /**
  20983. * Normally gets the length in time of the video in seconds;
  20984. * in all but the rarest use cases an argument will NOT be passed to the method
  20985. *
  20986. * > **NOTE**: The video must have started loading before the duration can be
  20987. * known, and depending on preload behaviour may not be known until the video starts
  20988. * playing.
  20989. *
  20990. * @fires Player#durationchange
  20991. *
  20992. * @param {number} [seconds]
  20993. * The duration of the video to set in seconds
  20994. *
  20995. * @return {number}
  20996. * - The duration of the video in seconds when getting
  20997. */
  20998. ;
  20999. _proto.duration = function duration(seconds) {
  21000. if (seconds === undefined) {
  21001. // return NaN if the duration is not known
  21002. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  21003. }
  21004. seconds = parseFloat(seconds); // Standardize on Infinity for signaling video is live
  21005. if (seconds < 0) {
  21006. seconds = Infinity;
  21007. }
  21008. if (seconds !== this.cache_.duration) {
  21009. // Cache the last set value for optimized scrubbing (esp. Flash)
  21010. // TODO: Required for techs other than Flash?
  21011. this.cache_.duration = seconds;
  21012. if (seconds === Infinity) {
  21013. this.addClass('vjs-live');
  21014. } else {
  21015. this.removeClass('vjs-live');
  21016. }
  21017. if (!isNaN(seconds)) {
  21018. // Do not fire durationchange unless the duration value is known.
  21019. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  21020. /**
  21021. * @event Player#durationchange
  21022. * @type {EventTarget~Event}
  21023. */
  21024. this.trigger('durationchange');
  21025. }
  21026. }
  21027. }
  21028. /**
  21029. * Calculates how much time is left in the video. Not part
  21030. * of the native video API.
  21031. *
  21032. * @return {number}
  21033. * The time remaining in seconds
  21034. */
  21035. ;
  21036. _proto.remainingTime = function remainingTime() {
  21037. return this.duration() - this.currentTime();
  21038. }
  21039. /**
  21040. * A remaining time function that is intented to be used when
  21041. * the time is to be displayed directly to the user.
  21042. *
  21043. * @return {number}
  21044. * The rounded time remaining in seconds
  21045. */
  21046. ;
  21047. _proto.remainingTimeDisplay = function remainingTimeDisplay() {
  21048. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  21049. } //
  21050. // Kind of like an array of portions of the video that have been downloaded.
  21051. /**
  21052. * Get a TimeRange object with an array of the times of the video
  21053. * that have been downloaded. If you just want the percent of the
  21054. * video that's been downloaded, use bufferedPercent.
  21055. *
  21056. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  21057. *
  21058. * @return {TimeRange}
  21059. * A mock TimeRange object (following HTML spec)
  21060. */
  21061. ;
  21062. _proto.buffered = function buffered() {
  21063. var buffered = this.techGet_('buffered');
  21064. if (!buffered || !buffered.length) {
  21065. buffered = createTimeRanges(0, 0);
  21066. }
  21067. return buffered;
  21068. }
  21069. /**
  21070. * Get the percent (as a decimal) of the video that's been downloaded.
  21071. * This method is not a part of the native HTML video API.
  21072. *
  21073. * @return {number}
  21074. * A decimal between 0 and 1 representing the percent
  21075. * that is buffered 0 being 0% and 1 being 100%
  21076. */
  21077. ;
  21078. _proto.bufferedPercent = function bufferedPercent$1() {
  21079. return bufferedPercent(this.buffered(), this.duration());
  21080. }
  21081. /**
  21082. * Get the ending time of the last buffered time range
  21083. * This is used in the progress bar to encapsulate all time ranges.
  21084. *
  21085. * @return {number}
  21086. * The end of the last buffered time range
  21087. */
  21088. ;
  21089. _proto.bufferedEnd = function bufferedEnd() {
  21090. var buffered = this.buffered();
  21091. var duration = this.duration();
  21092. var end = buffered.end(buffered.length - 1);
  21093. if (end > duration) {
  21094. end = duration;
  21095. }
  21096. return end;
  21097. }
  21098. /**
  21099. * Get or set the current volume of the media
  21100. *
  21101. * @param {number} [percentAsDecimal]
  21102. * The new volume as a decimal percent:
  21103. * - 0 is muted/0%/off
  21104. * - 1.0 is 100%/full
  21105. * - 0.5 is half volume or 50%
  21106. *
  21107. * @return {number}
  21108. * The current volume as a percent when getting
  21109. */
  21110. ;
  21111. _proto.volume = function volume(percentAsDecimal) {
  21112. var vol;
  21113. if (percentAsDecimal !== undefined) {
  21114. // Force value to between 0 and 1
  21115. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  21116. this.cache_.volume = vol;
  21117. this.techCall_('setVolume', vol);
  21118. if (vol > 0) {
  21119. this.lastVolume_(vol);
  21120. }
  21121. return;
  21122. } // Default to 1 when returning current volume.
  21123. vol = parseFloat(this.techGet_('volume'));
  21124. return isNaN(vol) ? 1 : vol;
  21125. }
  21126. /**
  21127. * Get the current muted state, or turn mute on or off
  21128. *
  21129. * @param {boolean} [muted]
  21130. * - true to mute
  21131. * - false to unmute
  21132. *
  21133. * @return {boolean}
  21134. * - true if mute is on and getting
  21135. * - false if mute is off and getting
  21136. */
  21137. ;
  21138. _proto.muted = function muted(_muted) {
  21139. if (_muted !== undefined) {
  21140. this.techCall_('setMuted', _muted);
  21141. return;
  21142. }
  21143. return this.techGet_('muted') || false;
  21144. }
  21145. /**
  21146. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  21147. * indicates the state of muted on initial playback.
  21148. *
  21149. * ```js
  21150. * var myPlayer = videojs('some-player-id');
  21151. *
  21152. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  21153. *
  21154. * // get, should be false
  21155. * console.log(myPlayer.defaultMuted());
  21156. * // set to true
  21157. * myPlayer.defaultMuted(true);
  21158. * // get should be true
  21159. * console.log(myPlayer.defaultMuted());
  21160. * ```
  21161. *
  21162. * @param {boolean} [defaultMuted]
  21163. * - true to mute
  21164. * - false to unmute
  21165. *
  21166. * @return {boolean|Player}
  21167. * - true if defaultMuted is on and getting
  21168. * - false if defaultMuted is off and getting
  21169. * - A reference to the current player when setting
  21170. */
  21171. ;
  21172. _proto.defaultMuted = function defaultMuted(_defaultMuted) {
  21173. if (_defaultMuted !== undefined) {
  21174. return this.techCall_('setDefaultMuted', _defaultMuted);
  21175. }
  21176. return this.techGet_('defaultMuted') || false;
  21177. }
  21178. /**
  21179. * Get the last volume, or set it
  21180. *
  21181. * @param {number} [percentAsDecimal]
  21182. * The new last volume as a decimal percent:
  21183. * - 0 is muted/0%/off
  21184. * - 1.0 is 100%/full
  21185. * - 0.5 is half volume or 50%
  21186. *
  21187. * @return {number}
  21188. * the current value of lastVolume as a percent when getting
  21189. *
  21190. * @private
  21191. */
  21192. ;
  21193. _proto.lastVolume_ = function lastVolume_(percentAsDecimal) {
  21194. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  21195. this.cache_.lastVolume = percentAsDecimal;
  21196. return;
  21197. }
  21198. return this.cache_.lastVolume;
  21199. }
  21200. /**
  21201. * Check if current tech can support native fullscreen
  21202. * (e.g. with built in controls like iOS)
  21203. *
  21204. * @return {boolean}
  21205. * if native fullscreen is supported
  21206. */
  21207. ;
  21208. _proto.supportsFullScreen = function supportsFullScreen() {
  21209. return this.techGet_('supportsFullScreen') || false;
  21210. }
  21211. /**
  21212. * Check if the player is in fullscreen mode or tell the player that it
  21213. * is or is not in fullscreen mode.
  21214. *
  21215. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  21216. * property and instead document.fullscreenElement is used. But isFullscreen is
  21217. * still a valuable property for internal player workings.
  21218. *
  21219. * @param {boolean} [isFS]
  21220. * Set the players current fullscreen state
  21221. *
  21222. * @return {boolean}
  21223. * - true if fullscreen is on and getting
  21224. * - false if fullscreen is off and getting
  21225. */
  21226. ;
  21227. _proto.isFullscreen = function isFullscreen(isFS) {
  21228. if (isFS !== undefined) {
  21229. var oldValue = this.isFullscreen_;
  21230. this.isFullscreen_ = Boolean(isFS); // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  21231. // this is the only place where we trigger fullscreenchange events for older browsers
  21232. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  21233. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  21234. /**
  21235. * @event Player#fullscreenchange
  21236. * @type {EventTarget~Event}
  21237. */
  21238. this.trigger('fullscreenchange');
  21239. }
  21240. this.toggleFullscreenClass_();
  21241. return;
  21242. }
  21243. return this.isFullscreen_;
  21244. }
  21245. /**
  21246. * Increase the size of the video to full screen
  21247. * In some browsers, full screen is not supported natively, so it enters
  21248. * "full window mode", where the video fills the browser window.
  21249. * In browsers and devices that support native full screen, sometimes the
  21250. * browser's default controls will be shown, and not the Video.js custom skin.
  21251. * This includes most mobile devices (iOS, Android) and older versions of
  21252. * Safari.
  21253. *
  21254. * @param {Object} [fullscreenOptions]
  21255. * Override the player fullscreen options
  21256. *
  21257. * @fires Player#fullscreenchange
  21258. */
  21259. ;
  21260. _proto.requestFullscreen = function requestFullscreen(fullscreenOptions) {
  21261. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  21262. if (PromiseClass) {
  21263. var self = this;
  21264. return new PromiseClass(function (resolve, reject) {
  21265. function offHandler() {
  21266. self.off('fullscreenerror', errorHandler);
  21267. self.off('fullscreenchange', changeHandler);
  21268. }
  21269. function changeHandler() {
  21270. offHandler();
  21271. resolve();
  21272. }
  21273. function errorHandler(e, err) {
  21274. offHandler();
  21275. reject(err);
  21276. }
  21277. self.one('fullscreenchange', changeHandler);
  21278. self.one('fullscreenerror', errorHandler);
  21279. var promise = self.requestFullscreenHelper_(fullscreenOptions);
  21280. if (promise) {
  21281. promise.then(offHandler, offHandler);
  21282. promise.then(resolve, reject);
  21283. }
  21284. });
  21285. }
  21286. return this.requestFullscreenHelper_();
  21287. };
  21288. _proto.requestFullscreenHelper_ = function requestFullscreenHelper_(fullscreenOptions) {
  21289. var _this12 = this;
  21290. var fsOptions; // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  21291. // Use defaults or player configured option unless passed directly to this method.
  21292. if (!this.fsApi_.prefixed) {
  21293. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  21294. if (fullscreenOptions !== undefined) {
  21295. fsOptions = fullscreenOptions;
  21296. }
  21297. } // This method works as follows:
  21298. // 1. if a fullscreen api is available, use it
  21299. // 1. call requestFullscreen with potential options
  21300. // 2. if we got a promise from above, use it to update isFullscreen()
  21301. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  21302. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  21303. // 3. otherwise, use "fullWindow" mode
  21304. if (this.fsApi_.requestFullscreen) {
  21305. var promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  21306. if (promise) {
  21307. promise.then(function () {
  21308. return _this12.isFullscreen(true);
  21309. }, function () {
  21310. return _this12.isFullscreen(false);
  21311. });
  21312. }
  21313. return promise;
  21314. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21315. // we can't take the video.js controls fullscreen but we can go fullscreen
  21316. // with native controls
  21317. this.techCall_('enterFullScreen');
  21318. } else {
  21319. // fullscreen isn't supported so we'll just stretch the video element to
  21320. // fill the viewport
  21321. this.enterFullWindow();
  21322. }
  21323. }
  21324. /**
  21325. * Return the video to its normal size after having been in full screen mode
  21326. *
  21327. * @fires Player#fullscreenchange
  21328. */
  21329. ;
  21330. _proto.exitFullscreen = function exitFullscreen() {
  21331. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  21332. if (PromiseClass) {
  21333. var self = this;
  21334. return new PromiseClass(function (resolve, reject) {
  21335. function offHandler() {
  21336. self.off('fullscreenerror', errorHandler);
  21337. self.off('fullscreenchange', changeHandler);
  21338. }
  21339. function changeHandler() {
  21340. offHandler();
  21341. resolve();
  21342. }
  21343. function errorHandler(e, err) {
  21344. offHandler();
  21345. reject(err);
  21346. }
  21347. self.one('fullscreenchange', changeHandler);
  21348. self.one('fullscreenerror', errorHandler);
  21349. var promise = self.exitFullscreenHelper_();
  21350. if (promise) {
  21351. promise.then(offHandler, offHandler); // map the promise to our resolve/reject methods
  21352. promise.then(resolve, reject);
  21353. }
  21354. });
  21355. }
  21356. return this.exitFullscreenHelper_();
  21357. };
  21358. _proto.exitFullscreenHelper_ = function exitFullscreenHelper_() {
  21359. var _this13 = this;
  21360. if (this.fsApi_.requestFullscreen) {
  21361. var promise = document__default['default'][this.fsApi_.exitFullscreen]();
  21362. if (promise) {
  21363. // we're splitting the promise here, so, we want to catch the
  21364. // potential error so that this chain doesn't have unhandled errors
  21365. silencePromise(promise.then(function () {
  21366. return _this13.isFullscreen(false);
  21367. }));
  21368. }
  21369. return promise;
  21370. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21371. this.techCall_('exitFullScreen');
  21372. } else {
  21373. this.exitFullWindow();
  21374. }
  21375. }
  21376. /**
  21377. * When fullscreen isn't supported we can stretch the
  21378. * video container to as wide as the browser will let us.
  21379. *
  21380. * @fires Player#enterFullWindow
  21381. */
  21382. ;
  21383. _proto.enterFullWindow = function enterFullWindow() {
  21384. this.isFullscreen(true);
  21385. this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off
  21386. this.docOrigOverflow = document__default['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen
  21387. on(document__default['default'], 'keydown', this.boundFullWindowOnEscKey_); // Hide any scroll bars
  21388. document__default['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles
  21389. addClass(document__default['default'].body, 'vjs-full-window');
  21390. /**
  21391. * @event Player#enterFullWindow
  21392. * @type {EventTarget~Event}
  21393. */
  21394. this.trigger('enterFullWindow');
  21395. }
  21396. /**
  21397. * Check for call to either exit full window or
  21398. * full screen on ESC key
  21399. *
  21400. * @param {string} event
  21401. * Event to check for key press
  21402. */
  21403. ;
  21404. _proto.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
  21405. if (keycode__default['default'].isEventKey(event, 'Esc')) {
  21406. if (this.isFullscreen() === true) {
  21407. if (!this.isFullWindow) {
  21408. this.exitFullscreen();
  21409. } else {
  21410. this.exitFullWindow();
  21411. }
  21412. }
  21413. }
  21414. }
  21415. /**
  21416. * Exit full window
  21417. *
  21418. * @fires Player#exitFullWindow
  21419. */
  21420. ;
  21421. _proto.exitFullWindow = function exitFullWindow() {
  21422. this.isFullscreen(false);
  21423. this.isFullWindow = false;
  21424. off(document__default['default'], 'keydown', this.boundFullWindowOnEscKey_); // Unhide scroll bars.
  21425. document__default['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles
  21426. removeClass(document__default['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes
  21427. // this.positionAll();
  21428. /**
  21429. * @event Player#exitFullWindow
  21430. * @type {EventTarget~Event}
  21431. */
  21432. this.trigger('exitFullWindow');
  21433. }
  21434. /**
  21435. * Disable Picture-in-Picture mode.
  21436. *
  21437. * @param {boolean} value
  21438. * - true will disable Picture-in-Picture mode
  21439. * - false will enable Picture-in-Picture mode
  21440. */
  21441. ;
  21442. _proto.disablePictureInPicture = function disablePictureInPicture(value) {
  21443. if (value === undefined) {
  21444. return this.techGet_('disablePictureInPicture');
  21445. }
  21446. this.techCall_('setDisablePictureInPicture', value);
  21447. this.options_.disablePictureInPicture = value;
  21448. this.trigger('disablepictureinpicturechanged');
  21449. }
  21450. /**
  21451. * Check if the player is in Picture-in-Picture mode or tell the player that it
  21452. * is or is not in Picture-in-Picture mode.
  21453. *
  21454. * @param {boolean} [isPiP]
  21455. * Set the players current Picture-in-Picture state
  21456. *
  21457. * @return {boolean}
  21458. * - true if Picture-in-Picture is on and getting
  21459. * - false if Picture-in-Picture is off and getting
  21460. */
  21461. ;
  21462. _proto.isInPictureInPicture = function isInPictureInPicture(isPiP) {
  21463. if (isPiP !== undefined) {
  21464. this.isInPictureInPicture_ = !!isPiP;
  21465. this.togglePictureInPictureClass_();
  21466. return;
  21467. }
  21468. return !!this.isInPictureInPicture_;
  21469. }
  21470. /**
  21471. * Create a floating video window always on top of other windows so that users may
  21472. * continue consuming media while they interact with other content sites, or
  21473. * applications on their device.
  21474. *
  21475. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21476. *
  21477. * @fires Player#enterpictureinpicture
  21478. *
  21479. * @return {Promise}
  21480. * A promise with a Picture-in-Picture window.
  21481. */
  21482. ;
  21483. _proto.requestPictureInPicture = function requestPictureInPicture() {
  21484. if ('pictureInPictureEnabled' in document__default['default'] && this.disablePictureInPicture() === false) {
  21485. /**
  21486. * This event fires when the player enters picture in picture mode
  21487. *
  21488. * @event Player#enterpictureinpicture
  21489. * @type {EventTarget~Event}
  21490. */
  21491. return this.techGet_('requestPictureInPicture');
  21492. }
  21493. }
  21494. /**
  21495. * Exit Picture-in-Picture mode.
  21496. *
  21497. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21498. *
  21499. * @fires Player#leavepictureinpicture
  21500. *
  21501. * @return {Promise}
  21502. * A promise.
  21503. */
  21504. ;
  21505. _proto.exitPictureInPicture = function exitPictureInPicture() {
  21506. if ('pictureInPictureEnabled' in document__default['default']) {
  21507. /**
  21508. * This event fires when the player leaves picture in picture mode
  21509. *
  21510. * @event Player#leavepictureinpicture
  21511. * @type {EventTarget~Event}
  21512. */
  21513. return document__default['default'].exitPictureInPicture();
  21514. }
  21515. }
  21516. /**
  21517. * Called when this Player has focus and a key gets pressed down, or when
  21518. * any Component of this player receives a key press that it doesn't handle.
  21519. * This allows player-wide hotkeys (either as defined below, or optionally
  21520. * by an external function).
  21521. *
  21522. * @param {EventTarget~Event} event
  21523. * The `keydown` event that caused this function to be called.
  21524. *
  21525. * @listens keydown
  21526. */
  21527. ;
  21528. _proto.handleKeyDown = function handleKeyDown(event) {
  21529. var userActions = this.options_.userActions; // Bail out if hotkeys are not configured.
  21530. if (!userActions || !userActions.hotkeys) {
  21531. return;
  21532. } // Function that determines whether or not to exclude an element from
  21533. // hotkeys handling.
  21534. var excludeElement = function excludeElement(el) {
  21535. var tagName = el.tagName.toLowerCase(); // The first and easiest test is for `contenteditable` elements.
  21536. if (el.isContentEditable) {
  21537. return true;
  21538. } // Inputs matching these types will still trigger hotkey handling as
  21539. // they are not text inputs.
  21540. var allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  21541. if (tagName === 'input') {
  21542. return allowedInputTypes.indexOf(el.type) === -1;
  21543. } // The final test is by tag name. These tags will be excluded entirely.
  21544. var excludedTags = ['textarea'];
  21545. return excludedTags.indexOf(tagName) !== -1;
  21546. }; // Bail out if the user is focused on an interactive form element.
  21547. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  21548. return;
  21549. }
  21550. if (typeof userActions.hotkeys === 'function') {
  21551. userActions.hotkeys.call(this, event);
  21552. } else {
  21553. this.handleHotkeys(event);
  21554. }
  21555. }
  21556. /**
  21557. * Called when this Player receives a hotkey keydown event.
  21558. * Supported player-wide hotkeys are:
  21559. *
  21560. * f - toggle fullscreen
  21561. * m - toggle mute
  21562. * k or Space - toggle play/pause
  21563. *
  21564. * @param {EventTarget~Event} event
  21565. * The `keydown` event that caused this function to be called.
  21566. */
  21567. ;
  21568. _proto.handleHotkeys = function handleHotkeys(event) {
  21569. var hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {}; // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  21570. var _hotkeys$fullscreenKe = hotkeys.fullscreenKey,
  21571. fullscreenKey = _hotkeys$fullscreenKe === void 0 ? function (keydownEvent) {
  21572. return keycode__default['default'].isEventKey(keydownEvent, 'f');
  21573. } : _hotkeys$fullscreenKe,
  21574. _hotkeys$muteKey = hotkeys.muteKey,
  21575. muteKey = _hotkeys$muteKey === void 0 ? function (keydownEvent) {
  21576. return keycode__default['default'].isEventKey(keydownEvent, 'm');
  21577. } : _hotkeys$muteKey,
  21578. _hotkeys$playPauseKey = hotkeys.playPauseKey,
  21579. playPauseKey = _hotkeys$playPauseKey === void 0 ? function (keydownEvent) {
  21580. return keycode__default['default'].isEventKey(keydownEvent, 'k') || keycode__default['default'].isEventKey(keydownEvent, 'Space');
  21581. } : _hotkeys$playPauseKey;
  21582. if (fullscreenKey.call(this, event)) {
  21583. event.preventDefault();
  21584. event.stopPropagation();
  21585. var FSToggle = Component$1.getComponent('FullscreenToggle');
  21586. if (document__default['default'][this.fsApi_.fullscreenEnabled] !== false) {
  21587. FSToggle.prototype.handleClick.call(this, event);
  21588. }
  21589. } else if (muteKey.call(this, event)) {
  21590. event.preventDefault();
  21591. event.stopPropagation();
  21592. var MuteToggle = Component$1.getComponent('MuteToggle');
  21593. MuteToggle.prototype.handleClick.call(this, event);
  21594. } else if (playPauseKey.call(this, event)) {
  21595. event.preventDefault();
  21596. event.stopPropagation();
  21597. var PlayToggle = Component$1.getComponent('PlayToggle');
  21598. PlayToggle.prototype.handleClick.call(this, event);
  21599. }
  21600. }
  21601. /**
  21602. * Check whether the player can play a given mimetype
  21603. *
  21604. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  21605. *
  21606. * @param {string} type
  21607. * The mimetype to check
  21608. *
  21609. * @return {string}
  21610. * 'probably', 'maybe', or '' (empty string)
  21611. */
  21612. ;
  21613. _proto.canPlayType = function canPlayType(type) {
  21614. var can; // Loop through each playback technology in the options order
  21615. for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
  21616. var techName = j[i];
  21617. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  21618. // Remove once that deprecated behavior is removed.
  21619. if (!tech) {
  21620. tech = Component$1.getComponent(techName);
  21621. } // Check if the current tech is defined before continuing
  21622. if (!tech) {
  21623. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  21624. continue;
  21625. } // Check if the browser supports this technology
  21626. if (tech.isSupported()) {
  21627. can = tech.canPlayType(type);
  21628. if (can) {
  21629. return can;
  21630. }
  21631. }
  21632. }
  21633. return '';
  21634. }
  21635. /**
  21636. * Select source based on tech-order or source-order
  21637. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  21638. * defaults to tech-order selection
  21639. *
  21640. * @param {Array} sources
  21641. * The sources for a media asset
  21642. *
  21643. * @return {Object|boolean}
  21644. * Object of source and tech order or false
  21645. */
  21646. ;
  21647. _proto.selectSource = function selectSource(sources) {
  21648. var _this14 = this;
  21649. // Get only the techs specified in `techOrder` that exist and are supported by the
  21650. // current platform
  21651. var techs = this.options_.techOrder.map(function (techName) {
  21652. return [techName, Tech.getTech(techName)];
  21653. }).filter(function (_ref) {
  21654. var techName = _ref[0],
  21655. tech = _ref[1];
  21656. // Check if the current tech is defined before continuing
  21657. if (tech) {
  21658. // Check if the browser supports this technology
  21659. return tech.isSupported();
  21660. }
  21661. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  21662. return false;
  21663. }); // Iterate over each `innerArray` element once per `outerArray` element and execute
  21664. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  21665. // that value.
  21666. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) {
  21667. var found;
  21668. outerArray.some(function (outerChoice) {
  21669. return innerArray.some(function (innerChoice) {
  21670. found = tester(outerChoice, innerChoice);
  21671. if (found) {
  21672. return true;
  21673. }
  21674. });
  21675. });
  21676. return found;
  21677. };
  21678. var foundSourceAndTech;
  21679. var flip = function flip(fn) {
  21680. return function (a, b) {
  21681. return fn(b, a);
  21682. };
  21683. };
  21684. var finder = function finder(_ref2, source) {
  21685. var techName = _ref2[0],
  21686. tech = _ref2[1];
  21687. if (tech.canPlaySource(source, _this14.options_[techName.toLowerCase()])) {
  21688. return {
  21689. source: source,
  21690. tech: techName
  21691. };
  21692. }
  21693. }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  21694. // to select from them based on their priority.
  21695. if (this.options_.sourceOrder) {
  21696. // Source-first ordering
  21697. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  21698. } else {
  21699. // Tech-first ordering
  21700. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  21701. }
  21702. return foundSourceAndTech || false;
  21703. }
  21704. /**
  21705. * Executes source setting and getting logic
  21706. *
  21707. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21708. * A SourceObject, an array of SourceObjects, or a string referencing
  21709. * a URL to a media source. It is _highly recommended_ that an object
  21710. * or array of objects is used here, so that source selection
  21711. * algorithms can take the `type` into account.
  21712. *
  21713. * If not provided, this method acts as a getter.
  21714. * @param {boolean} isRetry
  21715. * Indicates whether this is being called internally as a result of a retry
  21716. *
  21717. * @return {string|undefined}
  21718. * If the `source` argument is missing, returns the current source
  21719. * URL. Otherwise, returns nothing/undefined.
  21720. */
  21721. ;
  21722. _proto.handleSrc_ = function handleSrc_(source, isRetry) {
  21723. var _this15 = this;
  21724. // getter usage
  21725. if (typeof source === 'undefined') {
  21726. return this.cache_.src || '';
  21727. } // Reset retry behavior for new source
  21728. if (this.resetRetryOnError_) {
  21729. this.resetRetryOnError_();
  21730. } // filter out invalid sources and turn our source into
  21731. // an array of source objects
  21732. var sources = filterSource(source); // if a source was passed in then it is invalid because
  21733. // it was filtered to a zero length Array. So we have to
  21734. // show an error
  21735. if (!sources.length) {
  21736. this.setTimeout(function () {
  21737. this.error({
  21738. code: 4,
  21739. message: this.options_.notSupportedMessage
  21740. });
  21741. }, 0);
  21742. return;
  21743. } // initial sources
  21744. this.changingSrc_ = true; // Only update the cached source list if we are not retrying a new source after error,
  21745. // since in that case we want to include the failed source(s) in the cache
  21746. if (!isRetry) {
  21747. this.cache_.sources = sources;
  21748. }
  21749. this.updateSourceCaches_(sources[0]); // middlewareSource is the source after it has been changed by middleware
  21750. setSource(this, sources[0], function (middlewareSource, mws) {
  21751. _this15.middleware_ = mws; // since sourceSet is async we have to update the cache again after we select a source since
  21752. // the source that is selected could be out of order from the cache update above this callback.
  21753. if (!isRetry) {
  21754. _this15.cache_.sources = sources;
  21755. }
  21756. _this15.updateSourceCaches_(middlewareSource);
  21757. var err = _this15.src_(middlewareSource);
  21758. if (err) {
  21759. if (sources.length > 1) {
  21760. return _this15.handleSrc_(sources.slice(1));
  21761. }
  21762. _this15.changingSrc_ = false; // We need to wrap this in a timeout to give folks a chance to add error event handlers
  21763. _this15.setTimeout(function () {
  21764. this.error({
  21765. code: 4,
  21766. message: this.options_.notSupportedMessage
  21767. });
  21768. }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it
  21769. // this needs a better comment about why this is needed
  21770. _this15.triggerReady();
  21771. return;
  21772. }
  21773. setTech(mws, _this15.tech_);
  21774. }); // Try another available source if this one fails before playback.
  21775. if (this.options_.retryOnError && sources.length > 1) {
  21776. var retry = function retry() {
  21777. // Remove the error modal
  21778. _this15.error(null);
  21779. _this15.handleSrc_(sources.slice(1), true);
  21780. };
  21781. var stopListeningForErrors = function stopListeningForErrors() {
  21782. _this15.off('error', retry);
  21783. };
  21784. this.one('error', retry);
  21785. this.one('playing', stopListeningForErrors);
  21786. this.resetRetryOnError_ = function () {
  21787. _this15.off('error', retry);
  21788. _this15.off('playing', stopListeningForErrors);
  21789. };
  21790. }
  21791. }
  21792. /**
  21793. * Get or set the video source.
  21794. *
  21795. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  21796. * A SourceObject, an array of SourceObjects, or a string referencing
  21797. * a URL to a media source. It is _highly recommended_ that an object
  21798. * or array of objects is used here, so that source selection
  21799. * algorithms can take the `type` into account.
  21800. *
  21801. * If not provided, this method acts as a getter.
  21802. *
  21803. * @return {string|undefined}
  21804. * If the `source` argument is missing, returns the current source
  21805. * URL. Otherwise, returns nothing/undefined.
  21806. */
  21807. ;
  21808. _proto.src = function src(source) {
  21809. return this.handleSrc_(source, false);
  21810. }
  21811. /**
  21812. * Set the source object on the tech, returns a boolean that indicates whether
  21813. * there is a tech that can play the source or not
  21814. *
  21815. * @param {Tech~SourceObject} source
  21816. * The source object to set on the Tech
  21817. *
  21818. * @return {boolean}
  21819. * - True if there is no Tech to playback this source
  21820. * - False otherwise
  21821. *
  21822. * @private
  21823. */
  21824. ;
  21825. _proto.src_ = function src_(source) {
  21826. var _this16 = this;
  21827. var sourceTech = this.selectSource([source]);
  21828. if (!sourceTech) {
  21829. return true;
  21830. }
  21831. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  21832. this.changingSrc_ = true; // load this technology with the chosen source
  21833. this.loadTech_(sourceTech.tech, sourceTech.source);
  21834. this.tech_.ready(function () {
  21835. _this16.changingSrc_ = false;
  21836. });
  21837. return false;
  21838. } // wait until the tech is ready to set the source
  21839. // and set it synchronously if possible (#2326)
  21840. this.ready(function () {
  21841. // The setSource tech method was added with source handlers
  21842. // so older techs won't support it
  21843. // We need to check the direct prototype for the case where subclasses
  21844. // of the tech do not support source handlers
  21845. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  21846. this.techCall_('setSource', source);
  21847. } else {
  21848. this.techCall_('src', source.src);
  21849. }
  21850. this.changingSrc_ = false;
  21851. }, true);
  21852. return false;
  21853. }
  21854. /**
  21855. * Begin loading the src data.
  21856. */
  21857. ;
  21858. _proto.load = function load() {
  21859. this.techCall_('load');
  21860. }
  21861. /**
  21862. * Reset the player. Loads the first tech in the techOrder,
  21863. * removes all the text tracks in the existing `tech`,
  21864. * and calls `reset` on the `tech`.
  21865. */
  21866. ;
  21867. _proto.reset = function reset() {
  21868. var _this17 = this;
  21869. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  21870. if (this.paused() || !PromiseClass) {
  21871. this.doReset_();
  21872. } else {
  21873. var playPromise = this.play();
  21874. silencePromise(playPromise.then(function () {
  21875. return _this17.doReset_();
  21876. }));
  21877. }
  21878. };
  21879. _proto.doReset_ = function doReset_() {
  21880. if (this.tech_) {
  21881. this.tech_.clearTracks('text');
  21882. }
  21883. this.resetCache_();
  21884. this.poster('');
  21885. this.loadTech_(this.options_.techOrder[0], null);
  21886. this.techCall_('reset');
  21887. this.resetControlBarUI_();
  21888. if (isEvented(this)) {
  21889. this.trigger('playerreset');
  21890. }
  21891. }
  21892. /**
  21893. * Reset Control Bar's UI by calling sub-methods that reset
  21894. * all of Control Bar's components
  21895. */
  21896. ;
  21897. _proto.resetControlBarUI_ = function resetControlBarUI_() {
  21898. this.resetProgressBar_();
  21899. this.resetPlaybackRate_();
  21900. this.resetVolumeBar_();
  21901. }
  21902. /**
  21903. * Reset tech's progress so progress bar is reset in the UI
  21904. */
  21905. ;
  21906. _proto.resetProgressBar_ = function resetProgressBar_() {
  21907. this.currentTime(0);
  21908. var _ref3 = this.controlBar || {},
  21909. durationDisplay = _ref3.durationDisplay,
  21910. remainingTimeDisplay = _ref3.remainingTimeDisplay;
  21911. if (durationDisplay) {
  21912. durationDisplay.updateContent();
  21913. }
  21914. if (remainingTimeDisplay) {
  21915. remainingTimeDisplay.updateContent();
  21916. }
  21917. }
  21918. /**
  21919. * Reset Playback ratio
  21920. */
  21921. ;
  21922. _proto.resetPlaybackRate_ = function resetPlaybackRate_() {
  21923. this.playbackRate(this.defaultPlaybackRate());
  21924. this.handleTechRateChange_();
  21925. }
  21926. /**
  21927. * Reset Volume bar
  21928. */
  21929. ;
  21930. _proto.resetVolumeBar_ = function resetVolumeBar_() {
  21931. this.volume(1.0);
  21932. this.trigger('volumechange');
  21933. }
  21934. /**
  21935. * Returns all of the current source objects.
  21936. *
  21937. * @return {Tech~SourceObject[]}
  21938. * The current source objects
  21939. */
  21940. ;
  21941. _proto.currentSources = function currentSources() {
  21942. var source = this.currentSource();
  21943. var sources = []; // assume `{}` or `{ src }`
  21944. if (Object.keys(source).length !== 0) {
  21945. sources.push(source);
  21946. }
  21947. return this.cache_.sources || sources;
  21948. }
  21949. /**
  21950. * Returns the current source object.
  21951. *
  21952. * @return {Tech~SourceObject}
  21953. * The current source object
  21954. */
  21955. ;
  21956. _proto.currentSource = function currentSource() {
  21957. return this.cache_.source || {};
  21958. }
  21959. /**
  21960. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  21961. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  21962. *
  21963. * @return {string}
  21964. * The current source
  21965. */
  21966. ;
  21967. _proto.currentSrc = function currentSrc() {
  21968. return this.currentSource() && this.currentSource().src || '';
  21969. }
  21970. /**
  21971. * Get the current source type e.g. video/mp4
  21972. * This can allow you rebuild the current source object so that you could load the same
  21973. * source and tech later
  21974. *
  21975. * @return {string}
  21976. * The source MIME type
  21977. */
  21978. ;
  21979. _proto.currentType = function currentType() {
  21980. return this.currentSource() && this.currentSource().type || '';
  21981. }
  21982. /**
  21983. * Get or set the preload attribute
  21984. *
  21985. * @param {boolean} [value]
  21986. * - true means that we should preload
  21987. * - false means that we should not preload
  21988. *
  21989. * @return {string}
  21990. * The preload attribute value when getting
  21991. */
  21992. ;
  21993. _proto.preload = function preload(value) {
  21994. if (value !== undefined) {
  21995. this.techCall_('setPreload', value);
  21996. this.options_.preload = value;
  21997. return;
  21998. }
  21999. return this.techGet_('preload');
  22000. }
  22001. /**
  22002. * Get or set the autoplay option. When this is a boolean it will
  22003. * modify the attribute on the tech. When this is a string the attribute on
  22004. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  22005. *
  22006. * @param {boolean|string} [value]
  22007. * - true: autoplay using the browser behavior
  22008. * - false: do not autoplay
  22009. * - 'play': call play() on every loadstart
  22010. * - 'muted': call muted() then play() on every loadstart
  22011. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  22012. * - *: values other than those listed here will be set `autoplay` to true
  22013. *
  22014. * @return {boolean|string}
  22015. * The current value of autoplay when getting
  22016. */
  22017. ;
  22018. _proto.autoplay = function autoplay(value) {
  22019. // getter usage
  22020. if (value === undefined) {
  22021. return this.options_.autoplay || false;
  22022. }
  22023. var techAutoplay; // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  22024. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  22025. this.options_.autoplay = value;
  22026. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  22027. techAutoplay = false; // any falsy value sets autoplay to false in the browser,
  22028. // lets do the same
  22029. } else if (!value) {
  22030. this.options_.autoplay = false; // any other value (ie truthy) sets autoplay to true
  22031. } else {
  22032. this.options_.autoplay = true;
  22033. }
  22034. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay; // if we don't have a tech then we do not queue up
  22035. // a setAutoplay call on tech ready. We do this because the
  22036. // autoplay option will be passed in the constructor and we
  22037. // do not need to set it twice
  22038. if (this.tech_) {
  22039. this.techCall_('setAutoplay', techAutoplay);
  22040. }
  22041. }
  22042. /**
  22043. * Set or unset the playsinline attribute.
  22044. * Playsinline tells the browser that non-fullscreen playback is preferred.
  22045. *
  22046. * @param {boolean} [value]
  22047. * - true means that we should try to play inline by default
  22048. * - false means that we should use the browser's default playback mode,
  22049. * which in most cases is inline. iOS Safari is a notable exception
  22050. * and plays fullscreen by default.
  22051. *
  22052. * @return {string|Player}
  22053. * - the current value of playsinline
  22054. * - the player when setting
  22055. *
  22056. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  22057. */
  22058. ;
  22059. _proto.playsinline = function playsinline(value) {
  22060. if (value !== undefined) {
  22061. this.techCall_('setPlaysinline', value);
  22062. this.options_.playsinline = value;
  22063. return this;
  22064. }
  22065. return this.techGet_('playsinline');
  22066. }
  22067. /**
  22068. * Get or set the loop attribute on the video element.
  22069. *
  22070. * @param {boolean} [value]
  22071. * - true means that we should loop the video
  22072. * - false means that we should not loop the video
  22073. *
  22074. * @return {boolean}
  22075. * The current value of loop when getting
  22076. */
  22077. ;
  22078. _proto.loop = function loop(value) {
  22079. if (value !== undefined) {
  22080. this.techCall_('setLoop', value);
  22081. this.options_.loop = value;
  22082. return;
  22083. }
  22084. return this.techGet_('loop');
  22085. }
  22086. /**
  22087. * Get or set the poster image source url
  22088. *
  22089. * @fires Player#posterchange
  22090. *
  22091. * @param {string} [src]
  22092. * Poster image source URL
  22093. *
  22094. * @return {string}
  22095. * The current value of poster when getting
  22096. */
  22097. ;
  22098. _proto.poster = function poster(src) {
  22099. if (src === undefined) {
  22100. return this.poster_;
  22101. } // The correct way to remove a poster is to set as an empty string
  22102. // other falsey values will throw errors
  22103. if (!src) {
  22104. src = '';
  22105. }
  22106. if (src === this.poster_) {
  22107. return;
  22108. } // update the internal poster variable
  22109. this.poster_ = src; // update the tech's poster
  22110. this.techCall_('setPoster', src);
  22111. this.isPosterFromTech_ = false; // alert components that the poster has been set
  22112. /**
  22113. * This event fires when the poster image is changed on the player.
  22114. *
  22115. * @event Player#posterchange
  22116. * @type {EventTarget~Event}
  22117. */
  22118. this.trigger('posterchange');
  22119. }
  22120. /**
  22121. * Some techs (e.g. YouTube) can provide a poster source in an
  22122. * asynchronous way. We want the poster component to use this
  22123. * poster source so that it covers up the tech's controls.
  22124. * (YouTube's play button). However we only want to use this
  22125. * source if the player user hasn't set a poster through
  22126. * the normal APIs.
  22127. *
  22128. * @fires Player#posterchange
  22129. * @listens Tech#posterchange
  22130. * @private
  22131. */
  22132. ;
  22133. _proto.handleTechPosterChange_ = function handleTechPosterChange_() {
  22134. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  22135. var newPoster = this.tech_.poster() || '';
  22136. if (newPoster !== this.poster_) {
  22137. this.poster_ = newPoster;
  22138. this.isPosterFromTech_ = true; // Let components know the poster has changed
  22139. this.trigger('posterchange');
  22140. }
  22141. }
  22142. }
  22143. /**
  22144. * Get or set whether or not the controls are showing.
  22145. *
  22146. * @fires Player#controlsenabled
  22147. *
  22148. * @param {boolean} [bool]
  22149. * - true to turn controls on
  22150. * - false to turn controls off
  22151. *
  22152. * @return {boolean}
  22153. * The current value of controls when getting
  22154. */
  22155. ;
  22156. _proto.controls = function controls(bool) {
  22157. if (bool === undefined) {
  22158. return !!this.controls_;
  22159. }
  22160. bool = !!bool; // Don't trigger a change event unless it actually changed
  22161. if (this.controls_ === bool) {
  22162. return;
  22163. }
  22164. this.controls_ = bool;
  22165. if (this.usingNativeControls()) {
  22166. this.techCall_('setControls', bool);
  22167. }
  22168. if (this.controls_) {
  22169. this.removeClass('vjs-controls-disabled');
  22170. this.addClass('vjs-controls-enabled');
  22171. /**
  22172. * @event Player#controlsenabled
  22173. * @type {EventTarget~Event}
  22174. */
  22175. this.trigger('controlsenabled');
  22176. if (!this.usingNativeControls()) {
  22177. this.addTechControlsListeners_();
  22178. }
  22179. } else {
  22180. this.removeClass('vjs-controls-enabled');
  22181. this.addClass('vjs-controls-disabled');
  22182. /**
  22183. * @event Player#controlsdisabled
  22184. * @type {EventTarget~Event}
  22185. */
  22186. this.trigger('controlsdisabled');
  22187. if (!this.usingNativeControls()) {
  22188. this.removeTechControlsListeners_();
  22189. }
  22190. }
  22191. }
  22192. /**
  22193. * Toggle native controls on/off. Native controls are the controls built into
  22194. * devices (e.g. default iPhone controls) or other techs
  22195. * (e.g. Vimeo Controls)
  22196. * **This should only be set by the current tech, because only the tech knows
  22197. * if it can support native controls**
  22198. *
  22199. * @fires Player#usingnativecontrols
  22200. * @fires Player#usingcustomcontrols
  22201. *
  22202. * @param {boolean} [bool]
  22203. * - true to turn native controls on
  22204. * - false to turn native controls off
  22205. *
  22206. * @return {boolean}
  22207. * The current value of native controls when getting
  22208. */
  22209. ;
  22210. _proto.usingNativeControls = function usingNativeControls(bool) {
  22211. if (bool === undefined) {
  22212. return !!this.usingNativeControls_;
  22213. }
  22214. bool = !!bool; // Don't trigger a change event unless it actually changed
  22215. if (this.usingNativeControls_ === bool) {
  22216. return;
  22217. }
  22218. this.usingNativeControls_ = bool;
  22219. if (this.usingNativeControls_) {
  22220. this.addClass('vjs-using-native-controls');
  22221. /**
  22222. * player is using the native device controls
  22223. *
  22224. * @event Player#usingnativecontrols
  22225. * @type {EventTarget~Event}
  22226. */
  22227. this.trigger('usingnativecontrols');
  22228. } else {
  22229. this.removeClass('vjs-using-native-controls');
  22230. /**
  22231. * player is using the custom HTML controls
  22232. *
  22233. * @event Player#usingcustomcontrols
  22234. * @type {EventTarget~Event}
  22235. */
  22236. this.trigger('usingcustomcontrols');
  22237. }
  22238. }
  22239. /**
  22240. * Set or get the current MediaError
  22241. *
  22242. * @fires Player#error
  22243. *
  22244. * @param {MediaError|string|number} [err]
  22245. * A MediaError or a string/number to be turned
  22246. * into a MediaError
  22247. *
  22248. * @return {MediaError|null}
  22249. * The current MediaError when getting (or null)
  22250. */
  22251. ;
  22252. _proto.error = function error(err) {
  22253. var _this18 = this;
  22254. if (err === undefined) {
  22255. return this.error_ || null;
  22256. } // allow hooks to modify error object
  22257. hooks('beforeerror').forEach(function (hookFunction) {
  22258. var newErr = hookFunction(_this18, err);
  22259. if (!(isObject(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  22260. _this18.log.error('please return a value that MediaError expects in beforeerror hooks');
  22261. return;
  22262. }
  22263. err = newErr;
  22264. }); // Suppress the first error message for no compatible source until
  22265. // user interaction
  22266. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  22267. var triggerSuppressedError = function triggerSuppressedError() {
  22268. this.error(err);
  22269. };
  22270. this.options_.suppressNotSupportedError = false;
  22271. this.any(['click', 'touchstart'], triggerSuppressedError);
  22272. this.one('loadstart', function () {
  22273. this.off(['click', 'touchstart'], triggerSuppressedError);
  22274. });
  22275. return;
  22276. } // restoring to default
  22277. if (err === null) {
  22278. this.error_ = err;
  22279. this.removeClass('vjs-error');
  22280. if (this.errorDisplay) {
  22281. this.errorDisplay.close();
  22282. }
  22283. return;
  22284. }
  22285. this.error_ = new MediaError(err); // add the vjs-error classname to the player
  22286. this.addClass('vjs-error'); // log the name of the error type and any message
  22287. // IE11 logs "[object object]" and required you to expand message to see error object
  22288. log$1.error("(CODE:" + this.error_.code + " " + MediaError.errorTypes[this.error_.code] + ")", this.error_.message, this.error_);
  22289. /**
  22290. * @event Player#error
  22291. * @type {EventTarget~Event}
  22292. */
  22293. this.trigger('error'); // notify hooks of the per player error
  22294. hooks('error').forEach(function (hookFunction) {
  22295. return hookFunction(_this18, _this18.error_);
  22296. });
  22297. return;
  22298. }
  22299. /**
  22300. * Report user activity
  22301. *
  22302. * @param {Object} event
  22303. * Event object
  22304. */
  22305. ;
  22306. _proto.reportUserActivity = function reportUserActivity(event) {
  22307. this.userActivity_ = true;
  22308. }
  22309. /**
  22310. * Get/set if user is active
  22311. *
  22312. * @fires Player#useractive
  22313. * @fires Player#userinactive
  22314. *
  22315. * @param {boolean} [bool]
  22316. * - true if the user is active
  22317. * - false if the user is inactive
  22318. *
  22319. * @return {boolean}
  22320. * The current value of userActive when getting
  22321. */
  22322. ;
  22323. _proto.userActive = function userActive(bool) {
  22324. if (bool === undefined) {
  22325. return this.userActive_;
  22326. }
  22327. bool = !!bool;
  22328. if (bool === this.userActive_) {
  22329. return;
  22330. }
  22331. this.userActive_ = bool;
  22332. if (this.userActive_) {
  22333. this.userActivity_ = true;
  22334. this.removeClass('vjs-user-inactive');
  22335. this.addClass('vjs-user-active');
  22336. /**
  22337. * @event Player#useractive
  22338. * @type {EventTarget~Event}
  22339. */
  22340. this.trigger('useractive');
  22341. return;
  22342. } // Chrome/Safari/IE have bugs where when you change the cursor it can
  22343. // trigger a mousemove event. This causes an issue when you're hiding
  22344. // the cursor when the user is inactive, and a mousemove signals user
  22345. // activity. Making it impossible to go into inactive mode. Specifically
  22346. // this happens in fullscreen when we really need to hide the cursor.
  22347. //
  22348. // When this gets resolved in ALL browsers it can be removed
  22349. // https://code.google.com/p/chromium/issues/detail?id=103041
  22350. if (this.tech_) {
  22351. this.tech_.one('mousemove', function (e) {
  22352. e.stopPropagation();
  22353. e.preventDefault();
  22354. });
  22355. }
  22356. this.userActivity_ = false;
  22357. this.removeClass('vjs-user-active');
  22358. this.addClass('vjs-user-inactive');
  22359. /**
  22360. * @event Player#userinactive
  22361. * @type {EventTarget~Event}
  22362. */
  22363. this.trigger('userinactive');
  22364. }
  22365. /**
  22366. * Listen for user activity based on timeout value
  22367. *
  22368. * @private
  22369. */
  22370. ;
  22371. _proto.listenForUserActivity_ = function listenForUserActivity_() {
  22372. var mouseInProgress;
  22373. var lastMoveX;
  22374. var lastMoveY;
  22375. var handleActivity = bind(this, this.reportUserActivity);
  22376. var handleMouseMove = function handleMouseMove(e) {
  22377. // #1068 - Prevent mousemove spamming
  22378. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  22379. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  22380. lastMoveX = e.screenX;
  22381. lastMoveY = e.screenY;
  22382. handleActivity();
  22383. }
  22384. };
  22385. var handleMouseDown = function handleMouseDown() {
  22386. handleActivity(); // For as long as the they are touching the device or have their mouse down,
  22387. // we consider them active even if they're not moving their finger or mouse.
  22388. // So we want to continue to update that they are active
  22389. this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time
  22390. // as the activityCheck interval (250) should ensure we never miss the
  22391. // next activityCheck
  22392. mouseInProgress = this.setInterval(handleActivity, 250);
  22393. };
  22394. var handleMouseUpAndMouseLeave = function handleMouseUpAndMouseLeave(event) {
  22395. handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down
  22396. this.clearInterval(mouseInProgress);
  22397. }; // Any mouse movement will be considered user activity
  22398. this.on('mousedown', handleMouseDown);
  22399. this.on('mousemove', handleMouseMove);
  22400. this.on('mouseup', handleMouseUpAndMouseLeave);
  22401. this.on('mouseleave', handleMouseUpAndMouseLeave);
  22402. var controlBar = this.getChild('controlBar'); // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  22403. // controlBar would no longer be hidden by default timeout.
  22404. if (controlBar && !IS_IOS && !IS_ANDROID) {
  22405. controlBar.on('mouseenter', function (event) {
  22406. if (this.player().options_.inactivityTimeout !== 0) {
  22407. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  22408. }
  22409. this.player().options_.inactivityTimeout = 0;
  22410. });
  22411. controlBar.on('mouseleave', function (event) {
  22412. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  22413. });
  22414. } // Listen for keyboard navigation
  22415. // Shouldn't need to use inProgress interval because of key repeat
  22416. this.on('keydown', handleActivity);
  22417. this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into
  22418. // the mousemove/touchmove function itself, to prevent performance degradation.
  22419. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  22420. // then gets picked up by this loop
  22421. // http://ejohn.org/blog/learning-from-twitter/
  22422. var inactivityTimeout;
  22423. this.setInterval(function () {
  22424. // Check to see if mouse/touch activity has happened
  22425. if (!this.userActivity_) {
  22426. return;
  22427. } // Reset the activity tracker
  22428. this.userActivity_ = false; // If the user state was inactive, set the state to active
  22429. this.userActive(true); // Clear any existing inactivity timeout to start the timer over
  22430. this.clearTimeout(inactivityTimeout);
  22431. var timeout = this.options_.inactivityTimeout;
  22432. if (timeout <= 0) {
  22433. return;
  22434. } // In <timeout> milliseconds, if no more activity has occurred the
  22435. // user will be considered inactive
  22436. inactivityTimeout = this.setTimeout(function () {
  22437. // Protect against the case where the inactivityTimeout can trigger just
  22438. // before the next user activity is picked up by the activity check loop
  22439. // causing a flicker
  22440. if (!this.userActivity_) {
  22441. this.userActive(false);
  22442. }
  22443. }, timeout);
  22444. }, 250);
  22445. }
  22446. /**
  22447. * Gets or sets the current playback rate. A playback rate of
  22448. * 1.0 represents normal speed and 0.5 would indicate half-speed
  22449. * playback, for instance.
  22450. *
  22451. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  22452. *
  22453. * @param {number} [rate]
  22454. * New playback rate to set.
  22455. *
  22456. * @return {number}
  22457. * The current playback rate when getting or 1.0
  22458. */
  22459. ;
  22460. _proto.playbackRate = function playbackRate(rate) {
  22461. if (rate !== undefined) {
  22462. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  22463. // that is registered above
  22464. this.techCall_('setPlaybackRate', rate);
  22465. return;
  22466. }
  22467. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22468. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  22469. }
  22470. return 1.0;
  22471. }
  22472. /**
  22473. * Gets or sets the current default playback rate. A default playback rate of
  22474. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  22475. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  22476. * not the current playbackRate.
  22477. *
  22478. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  22479. *
  22480. * @param {number} [rate]
  22481. * New default playback rate to set.
  22482. *
  22483. * @return {number|Player}
  22484. * - The default playback rate when getting or 1.0
  22485. * - the player when setting
  22486. */
  22487. ;
  22488. _proto.defaultPlaybackRate = function defaultPlaybackRate(rate) {
  22489. if (rate !== undefined) {
  22490. return this.techCall_('setDefaultPlaybackRate', rate);
  22491. }
  22492. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22493. return this.techGet_('defaultPlaybackRate');
  22494. }
  22495. return 1.0;
  22496. }
  22497. /**
  22498. * Gets or sets the audio flag
  22499. *
  22500. * @param {boolean} bool
  22501. * - true signals that this is an audio player
  22502. * - false signals that this is not an audio player
  22503. *
  22504. * @return {boolean}
  22505. * The current value of isAudio when getting
  22506. */
  22507. ;
  22508. _proto.isAudio = function isAudio(bool) {
  22509. if (bool !== undefined) {
  22510. this.isAudio_ = !!bool;
  22511. return;
  22512. }
  22513. return !!this.isAudio_;
  22514. };
  22515. _proto.enableAudioOnlyUI_ = function enableAudioOnlyUI_() {
  22516. var _this19 = this;
  22517. // Update styling immediately to show the control bar so we can get its height
  22518. this.addClass('vjs-audio-only-mode');
  22519. var playerChildren = this.children();
  22520. var controlBar = this.getChild('ControlBar');
  22521. var controlBarHeight = controlBar && controlBar.currentHeight(); // Hide all player components except the control bar. Control bar components
  22522. // needed only for video are hidden with CSS
  22523. playerChildren.forEach(function (child) {
  22524. if (child === controlBar) {
  22525. return;
  22526. }
  22527. if (child.el_ && !child.hasClass('vjs-hidden')) {
  22528. child.hide();
  22529. _this19.audioOnlyCache_.hiddenChildren.push(child);
  22530. }
  22531. });
  22532. this.audioOnlyCache_.playerHeight = this.currentHeight(); // Set the player height the same as the control bar
  22533. this.height(controlBarHeight);
  22534. this.trigger('audioonlymodechange');
  22535. };
  22536. _proto.disableAudioOnlyUI_ = function disableAudioOnlyUI_() {
  22537. this.removeClass('vjs-audio-only-mode'); // Show player components that were previously hidden
  22538. this.audioOnlyCache_.hiddenChildren.forEach(function (child) {
  22539. return child.show();
  22540. }); // Reset player height
  22541. this.height(this.audioOnlyCache_.playerHeight);
  22542. this.trigger('audioonlymodechange');
  22543. }
  22544. /**
  22545. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  22546. *
  22547. * Setting this to `true` will hide all player components except the control bar,
  22548. * as well as control bar components needed only for video.
  22549. *
  22550. * @param {boolean} [value]
  22551. * The value to set audioOnlyMode to.
  22552. *
  22553. * @return {Promise|boolean}
  22554. * A Promise is returned when setting the state, and a boolean when getting
  22555. * the present state
  22556. */
  22557. ;
  22558. _proto.audioOnlyMode = function audioOnlyMode(value) {
  22559. var _this20 = this;
  22560. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  22561. return this.audioOnlyMode_;
  22562. }
  22563. this.audioOnlyMode_ = value;
  22564. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  22565. if (PromiseClass) {
  22566. // Enable Audio Only Mode
  22567. if (value) {
  22568. var exitPromises = []; // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  22569. if (this.isInPictureInPicture()) {
  22570. exitPromises.push(this.exitPictureInPicture());
  22571. }
  22572. if (this.isFullscreen()) {
  22573. exitPromises.push(this.exitFullscreen());
  22574. }
  22575. if (this.audioPosterMode()) {
  22576. exitPromises.push(this.audioPosterMode(false));
  22577. }
  22578. return PromiseClass.all(exitPromises).then(function () {
  22579. return _this20.enableAudioOnlyUI_();
  22580. });
  22581. } // Disable Audio Only Mode
  22582. return PromiseClass.resolve().then(function () {
  22583. return _this20.disableAudioOnlyUI_();
  22584. });
  22585. }
  22586. if (value) {
  22587. if (this.isInPictureInPicture()) {
  22588. this.exitPictureInPicture();
  22589. }
  22590. if (this.isFullscreen()) {
  22591. this.exitFullscreen();
  22592. }
  22593. this.enableAudioOnlyUI_();
  22594. } else {
  22595. this.disableAudioOnlyUI_();
  22596. }
  22597. };
  22598. _proto.enablePosterModeUI_ = function enablePosterModeUI_() {
  22599. // Hide the video element and show the poster image to enable posterModeUI
  22600. var tech = this.tech_ && this.tech_;
  22601. tech.hide();
  22602. this.addClass('vjs-audio-poster-mode');
  22603. this.trigger('audiopostermodechange');
  22604. };
  22605. _proto.disablePosterModeUI_ = function disablePosterModeUI_() {
  22606. // Show the video element and hide the poster image to disable posterModeUI
  22607. var tech = this.tech_ && this.tech_;
  22608. tech.show();
  22609. this.removeClass('vjs-audio-poster-mode');
  22610. this.trigger('audiopostermodechange');
  22611. }
  22612. /**
  22613. * Get the current audioPosterMode state or set audioPosterMode to true or false
  22614. *
  22615. * @param {boolean} [value]
  22616. * The value to set audioPosterMode to.
  22617. *
  22618. * @return {Promise|boolean}
  22619. * A Promise is returned when setting the state, and a boolean when getting
  22620. * the present state
  22621. */
  22622. ;
  22623. _proto.audioPosterMode = function audioPosterMode(value) {
  22624. var _this21 = this;
  22625. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  22626. return this.audioPosterMode_;
  22627. }
  22628. this.audioPosterMode_ = value;
  22629. var PromiseClass = this.options_.Promise || window__default['default'].Promise;
  22630. if (PromiseClass) {
  22631. if (value) {
  22632. if (this.audioOnlyMode()) {
  22633. var audioOnlyModePromise = this.audioOnlyMode(false);
  22634. return audioOnlyModePromise.then(function () {
  22635. // enable audio poster mode after audio only mode is disabled
  22636. _this21.enablePosterModeUI_();
  22637. });
  22638. }
  22639. return PromiseClass.resolve().then(function () {
  22640. // enable audio poster mode
  22641. _this21.enablePosterModeUI_();
  22642. });
  22643. }
  22644. return PromiseClass.resolve().then(function () {
  22645. // disable audio poster mode
  22646. _this21.disablePosterModeUI_();
  22647. });
  22648. }
  22649. if (value) {
  22650. if (this.audioOnlyMode()) {
  22651. this.audioOnlyMode(false);
  22652. }
  22653. this.enablePosterModeUI_();
  22654. return;
  22655. }
  22656. this.disablePosterModeUI_();
  22657. }
  22658. /**
  22659. * A helper method for adding a {@link TextTrack} to our
  22660. * {@link TextTrackList}.
  22661. *
  22662. * In addition to the W3C settings we allow adding additional info through options.
  22663. *
  22664. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  22665. *
  22666. * @param {string} [kind]
  22667. * the kind of TextTrack you are adding
  22668. *
  22669. * @param {string} [label]
  22670. * the label to give the TextTrack label
  22671. *
  22672. * @param {string} [language]
  22673. * the language to set on the TextTrack
  22674. *
  22675. * @return {TextTrack|undefined}
  22676. * the TextTrack that was added or undefined
  22677. * if there is no tech
  22678. */
  22679. ;
  22680. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  22681. if (this.tech_) {
  22682. return this.tech_.addTextTrack(kind, label, language);
  22683. }
  22684. }
  22685. /**
  22686. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  22687. * When manualCleanup is set to false, the track will be automatically removed
  22688. * on source changes.
  22689. *
  22690. * @param {Object} options
  22691. * Options to pass to {@link HTMLTrackElement} during creation. See
  22692. * {@link HTMLTrackElement} for object properties that you should use.
  22693. *
  22694. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  22695. * removed on a source change
  22696. *
  22697. * @return {HtmlTrackElement}
  22698. * the HTMLTrackElement that was created and added
  22699. * to the HtmlTrackElementList and the remote
  22700. * TextTrackList
  22701. *
  22702. * @deprecated The default value of the "manualCleanup" parameter will default
  22703. * to "false" in upcoming versions of Video.js
  22704. */
  22705. ;
  22706. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  22707. if (this.tech_) {
  22708. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  22709. }
  22710. }
  22711. /**
  22712. * Remove a remote {@link TextTrack} from the respective
  22713. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  22714. *
  22715. * @param {Object} track
  22716. * Remote {@link TextTrack} to remove
  22717. *
  22718. * @return {undefined}
  22719. * does not return anything
  22720. */
  22721. ;
  22722. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(obj) {
  22723. if (obj === void 0) {
  22724. obj = {};
  22725. }
  22726. var _obj = obj,
  22727. track = _obj.track;
  22728. if (!track) {
  22729. track = obj;
  22730. } // destructure the input into an object with a track argument, defaulting to arguments[0]
  22731. // default the whole argument to an empty object if nothing was passed in
  22732. if (this.tech_) {
  22733. return this.tech_.removeRemoteTextTrack(track);
  22734. }
  22735. }
  22736. /**
  22737. * Gets available media playback quality metrics as specified by the W3C's Media
  22738. * Playback Quality API.
  22739. *
  22740. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  22741. *
  22742. * @return {Object|undefined}
  22743. * An object with supported media playback quality metrics or undefined if there
  22744. * is no tech or the tech does not support it.
  22745. */
  22746. ;
  22747. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  22748. return this.techGet_('getVideoPlaybackQuality');
  22749. }
  22750. /**
  22751. * Get video width
  22752. *
  22753. * @return {number}
  22754. * current video width
  22755. */
  22756. ;
  22757. _proto.videoWidth = function videoWidth() {
  22758. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  22759. }
  22760. /**
  22761. * Get video height
  22762. *
  22763. * @return {number}
  22764. * current video height
  22765. */
  22766. ;
  22767. _proto.videoHeight = function videoHeight() {
  22768. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  22769. }
  22770. /**
  22771. * The player's language code.
  22772. *
  22773. * Changing the language will trigger
  22774. * [languagechange]{@link Player#event:languagechange}
  22775. * which Components can use to update control text.
  22776. * ClickableComponent will update its control text by default on
  22777. * [languagechange]{@link Player#event:languagechange}.
  22778. *
  22779. * @fires Player#languagechange
  22780. *
  22781. * @param {string} [code]
  22782. * the language code to set the player to
  22783. *
  22784. * @return {string}
  22785. * The current language code when getting
  22786. */
  22787. ;
  22788. _proto.language = function language(code) {
  22789. if (code === undefined) {
  22790. return this.language_;
  22791. }
  22792. if (this.language_ !== String(code).toLowerCase()) {
  22793. this.language_ = String(code).toLowerCase(); // during first init, it's possible some things won't be evented
  22794. if (isEvented(this)) {
  22795. /**
  22796. * fires when the player language change
  22797. *
  22798. * @event Player#languagechange
  22799. * @type {EventTarget~Event}
  22800. */
  22801. this.trigger('languagechange');
  22802. }
  22803. }
  22804. }
  22805. /**
  22806. * Get the player's language dictionary
  22807. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  22808. * Languages specified directly in the player options have precedence
  22809. *
  22810. * @return {Array}
  22811. * An array of of supported languages
  22812. */
  22813. ;
  22814. _proto.languages = function languages() {
  22815. return mergeOptions$3(Player.prototype.options_.languages, this.languages_);
  22816. }
  22817. /**
  22818. * returns a JavaScript object reperesenting the current track
  22819. * information. **DOES not return it as JSON**
  22820. *
  22821. * @return {Object}
  22822. * Object representing the current of track info
  22823. */
  22824. ;
  22825. _proto.toJSON = function toJSON() {
  22826. var options = mergeOptions$3(this.options_);
  22827. var tracks = options.tracks;
  22828. options.tracks = [];
  22829. for (var i = 0; i < tracks.length; i++) {
  22830. var track = tracks[i]; // deep merge tracks and null out player so no circular references
  22831. track = mergeOptions$3(track);
  22832. track.player = undefined;
  22833. options.tracks[i] = track;
  22834. }
  22835. return options;
  22836. }
  22837. /**
  22838. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  22839. * component) that immediately overlays the player with arbitrary
  22840. * content and removes itself when closed.
  22841. *
  22842. * @param {string|Function|Element|Array|null} content
  22843. * Same as {@link ModalDialog#content}'s param of the same name.
  22844. * The most straight-forward usage is to provide a string or DOM
  22845. * element.
  22846. *
  22847. * @param {Object} [options]
  22848. * Extra options which will be passed on to the {@link ModalDialog}.
  22849. *
  22850. * @return {ModalDialog}
  22851. * the {@link ModalDialog} that was created
  22852. */
  22853. ;
  22854. _proto.createModal = function createModal(content, options) {
  22855. var _this22 = this;
  22856. options = options || {};
  22857. options.content = content || '';
  22858. var modal = new ModalDialog(this, options);
  22859. this.addChild(modal);
  22860. modal.on('dispose', function () {
  22861. _this22.removeChild(modal);
  22862. });
  22863. modal.open();
  22864. return modal;
  22865. }
  22866. /**
  22867. * Change breakpoint classes when the player resizes.
  22868. *
  22869. * @private
  22870. */
  22871. ;
  22872. _proto.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() {
  22873. if (!this.responsive()) {
  22874. return;
  22875. }
  22876. var currentBreakpoint = this.currentBreakpoint();
  22877. var currentWidth = this.currentWidth();
  22878. for (var i = 0; i < BREAKPOINT_ORDER.length; i++) {
  22879. var candidateBreakpoint = BREAKPOINT_ORDER[i];
  22880. var maxWidth = this.breakpoints_[candidateBreakpoint];
  22881. if (currentWidth <= maxWidth) {
  22882. // The current breakpoint did not change, nothing to do.
  22883. if (currentBreakpoint === candidateBreakpoint) {
  22884. return;
  22885. } // Only remove a class if there is a current breakpoint.
  22886. if (currentBreakpoint) {
  22887. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  22888. }
  22889. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  22890. this.breakpoint_ = candidateBreakpoint;
  22891. break;
  22892. }
  22893. }
  22894. }
  22895. /**
  22896. * Removes the current breakpoint.
  22897. *
  22898. * @private
  22899. */
  22900. ;
  22901. _proto.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() {
  22902. var className = this.currentBreakpointClass();
  22903. this.breakpoint_ = '';
  22904. if (className) {
  22905. this.removeClass(className);
  22906. }
  22907. }
  22908. /**
  22909. * Get or set breakpoints on the player.
  22910. *
  22911. * Calling this method with an object or `true` will remove any previous
  22912. * custom breakpoints and start from the defaults again.
  22913. *
  22914. * @param {Object|boolean} [breakpoints]
  22915. * If an object is given, it can be used to provide custom
  22916. * breakpoints. If `true` is given, will set default breakpoints.
  22917. * If this argument is not given, will simply return the current
  22918. * breakpoints.
  22919. *
  22920. * @param {number} [breakpoints.tiny]
  22921. * The maximum width for the "vjs-layout-tiny" class.
  22922. *
  22923. * @param {number} [breakpoints.xsmall]
  22924. * The maximum width for the "vjs-layout-x-small" class.
  22925. *
  22926. * @param {number} [breakpoints.small]
  22927. * The maximum width for the "vjs-layout-small" class.
  22928. *
  22929. * @param {number} [breakpoints.medium]
  22930. * The maximum width for the "vjs-layout-medium" class.
  22931. *
  22932. * @param {number} [breakpoints.large]
  22933. * The maximum width for the "vjs-layout-large" class.
  22934. *
  22935. * @param {number} [breakpoints.xlarge]
  22936. * The maximum width for the "vjs-layout-x-large" class.
  22937. *
  22938. * @param {number} [breakpoints.huge]
  22939. * The maximum width for the "vjs-layout-huge" class.
  22940. *
  22941. * @return {Object}
  22942. * An object mapping breakpoint names to maximum width values.
  22943. */
  22944. ;
  22945. _proto.breakpoints = function breakpoints(_breakpoints) {
  22946. // Used as a getter.
  22947. if (_breakpoints === undefined) {
  22948. return assign(this.breakpoints_);
  22949. }
  22950. this.breakpoint_ = '';
  22951. this.breakpoints_ = assign({}, DEFAULT_BREAKPOINTS, _breakpoints); // When breakpoint definitions change, we need to update the currently
  22952. // selected breakpoint.
  22953. this.updateCurrentBreakpoint_(); // Clone the breakpoints before returning.
  22954. return assign(this.breakpoints_);
  22955. }
  22956. /**
  22957. * Get or set a flag indicating whether or not this player should adjust
  22958. * its UI based on its dimensions.
  22959. *
  22960. * @param {boolean} value
  22961. * Should be `true` if the player should adjust its UI based on its
  22962. * dimensions; otherwise, should be `false`.
  22963. *
  22964. * @return {boolean}
  22965. * Will be `true` if this player should adjust its UI based on its
  22966. * dimensions; otherwise, will be `false`.
  22967. */
  22968. ;
  22969. _proto.responsive = function responsive(value) {
  22970. // Used as a getter.
  22971. if (value === undefined) {
  22972. return this.responsive_;
  22973. }
  22974. value = Boolean(value);
  22975. var current = this.responsive_; // Nothing changed.
  22976. if (value === current) {
  22977. return;
  22978. } // The value actually changed, set it.
  22979. this.responsive_ = value; // Start listening for breakpoints and set the initial breakpoint if the
  22980. // player is now responsive.
  22981. if (value) {
  22982. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  22983. this.updateCurrentBreakpoint_(); // Stop listening for breakpoints if the player is no longer responsive.
  22984. } else {
  22985. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  22986. this.removeCurrentBreakpoint_();
  22987. }
  22988. return value;
  22989. }
  22990. /**
  22991. * Get current breakpoint name, if any.
  22992. *
  22993. * @return {string}
  22994. * If there is currently a breakpoint set, returns a the key from the
  22995. * breakpoints object matching it. Otherwise, returns an empty string.
  22996. */
  22997. ;
  22998. _proto.currentBreakpoint = function currentBreakpoint() {
  22999. return this.breakpoint_;
  23000. }
  23001. /**
  23002. * Get the current breakpoint class name.
  23003. *
  23004. * @return {string}
  23005. * The matching class name (e.g. `"vjs-layout-tiny"` or
  23006. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  23007. * there is no current breakpoint.
  23008. */
  23009. ;
  23010. _proto.currentBreakpointClass = function currentBreakpointClass() {
  23011. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  23012. }
  23013. /**
  23014. * An object that describes a single piece of media.
  23015. *
  23016. * Properties that are not part of this type description will be retained; so,
  23017. * this can be viewed as a generic metadata storage mechanism as well.
  23018. *
  23019. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  23020. * @typedef {Object} Player~MediaObject
  23021. *
  23022. * @property {string} [album]
  23023. * Unused, except if this object is passed to the `MediaSession`
  23024. * API.
  23025. *
  23026. * @property {string} [artist]
  23027. * Unused, except if this object is passed to the `MediaSession`
  23028. * API.
  23029. *
  23030. * @property {Object[]} [artwork]
  23031. * Unused, except if this object is passed to the `MediaSession`
  23032. * API. If not specified, will be populated via the `poster`, if
  23033. * available.
  23034. *
  23035. * @property {string} [poster]
  23036. * URL to an image that will display before playback.
  23037. *
  23038. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  23039. * A single source object, an array of source objects, or a string
  23040. * referencing a URL to a media source. It is _highly recommended_
  23041. * that an object or array of objects is used here, so that source
  23042. * selection algorithms can take the `type` into account.
  23043. *
  23044. * @property {string} [title]
  23045. * Unused, except if this object is passed to the `MediaSession`
  23046. * API.
  23047. *
  23048. * @property {Object[]} [textTracks]
  23049. * An array of objects to be used to create text tracks, following
  23050. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  23051. * For ease of removal, these will be created as "remote" text
  23052. * tracks and set to automatically clean up on source changes.
  23053. *
  23054. * These objects may have properties like `src`, `kind`, `label`,
  23055. * and `language`, see {@link Tech#createRemoteTextTrack}.
  23056. */
  23057. /**
  23058. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  23059. *
  23060. * @param {Player~MediaObject} media
  23061. * A media object.
  23062. *
  23063. * @param {Function} ready
  23064. * A callback to be called when the player is ready.
  23065. */
  23066. ;
  23067. _proto.loadMedia = function loadMedia(media, ready) {
  23068. var _this23 = this;
  23069. if (!media || typeof media !== 'object') {
  23070. return;
  23071. }
  23072. this.reset(); // Clone the media object so it cannot be mutated from outside.
  23073. this.cache_.media = mergeOptions$3(media);
  23074. var _this$cache_$media = this.cache_.media,
  23075. artwork = _this$cache_$media.artwork,
  23076. poster = _this$cache_$media.poster,
  23077. src = _this$cache_$media.src,
  23078. textTracks = _this$cache_$media.textTracks; // If `artwork` is not given, create it using `poster`.
  23079. if (!artwork && poster) {
  23080. this.cache_.media.artwork = [{
  23081. src: poster,
  23082. type: getMimetype(poster)
  23083. }];
  23084. }
  23085. if (src) {
  23086. this.src(src);
  23087. }
  23088. if (poster) {
  23089. this.poster(poster);
  23090. }
  23091. if (Array.isArray(textTracks)) {
  23092. textTracks.forEach(function (tt) {
  23093. return _this23.addRemoteTextTrack(tt, false);
  23094. });
  23095. }
  23096. this.ready(ready);
  23097. }
  23098. /**
  23099. * Get a clone of the current {@link Player~MediaObject} for this player.
  23100. *
  23101. * If the `loadMedia` method has not been used, will attempt to return a
  23102. * {@link Player~MediaObject} based on the current state of the player.
  23103. *
  23104. * @return {Player~MediaObject}
  23105. */
  23106. ;
  23107. _proto.getMedia = function getMedia() {
  23108. if (!this.cache_.media) {
  23109. var poster = this.poster();
  23110. var src = this.currentSources();
  23111. var textTracks = Array.prototype.map.call(this.remoteTextTracks(), function (tt) {
  23112. return {
  23113. kind: tt.kind,
  23114. label: tt.label,
  23115. language: tt.language,
  23116. src: tt.src
  23117. };
  23118. });
  23119. var media = {
  23120. src: src,
  23121. textTracks: textTracks
  23122. };
  23123. if (poster) {
  23124. media.poster = poster;
  23125. media.artwork = [{
  23126. src: media.poster,
  23127. type: getMimetype(media.poster)
  23128. }];
  23129. }
  23130. return media;
  23131. }
  23132. return mergeOptions$3(this.cache_.media);
  23133. }
  23134. /**
  23135. * Gets tag settings
  23136. *
  23137. * @param {Element} tag
  23138. * The player tag
  23139. *
  23140. * @return {Object}
  23141. * An object containing all of the settings
  23142. * for a player tag
  23143. */
  23144. ;
  23145. Player.getTagSettings = function getTagSettings(tag) {
  23146. var baseOptions = {
  23147. sources: [],
  23148. tracks: []
  23149. };
  23150. var tagOptions = getAttributes(tag);
  23151. var dataSetup = tagOptions['data-setup'];
  23152. if (hasClass(tag, 'vjs-fill')) {
  23153. tagOptions.fill = true;
  23154. }
  23155. if (hasClass(tag, 'vjs-fluid')) {
  23156. tagOptions.fluid = true;
  23157. } // Check if data-setup attr exists.
  23158. if (dataSetup !== null) {
  23159. // Parse options JSON
  23160. // If empty string, make it a parsable json object.
  23161. var _safeParseTuple = safeParseTuple__default['default'](dataSetup || '{}'),
  23162. err = _safeParseTuple[0],
  23163. data = _safeParseTuple[1];
  23164. if (err) {
  23165. log$1.error(err);
  23166. }
  23167. assign(tagOptions, data);
  23168. }
  23169. assign(baseOptions, tagOptions); // Get tag children settings
  23170. if (tag.hasChildNodes()) {
  23171. var children = tag.childNodes;
  23172. for (var i = 0, j = children.length; i < j; i++) {
  23173. var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  23174. var childName = child.nodeName.toLowerCase();
  23175. if (childName === 'source') {
  23176. baseOptions.sources.push(getAttributes(child));
  23177. } else if (childName === 'track') {
  23178. baseOptions.tracks.push(getAttributes(child));
  23179. }
  23180. }
  23181. }
  23182. return baseOptions;
  23183. }
  23184. /**
  23185. * Determine whether or not flexbox is supported
  23186. *
  23187. * @return {boolean}
  23188. * - true if flexbox is supported
  23189. * - false if flexbox is not supported
  23190. */
  23191. ;
  23192. _proto.flexNotSupported_ = function flexNotSupported_() {
  23193. var elem = document__default['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
  23194. // common flex features that we can rely on when checking for flex support.
  23195. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec), available for completeness
  23196. 'msFlexOrder' in elem.style);
  23197. }
  23198. /**
  23199. * Set debug mode to enable/disable logs at info level.
  23200. *
  23201. * @param {boolean} enabled
  23202. * @fires Player#debugon
  23203. * @fires Player#debugoff
  23204. */
  23205. ;
  23206. _proto.debug = function debug(enabled) {
  23207. if (enabled === undefined) {
  23208. return this.debugEnabled_;
  23209. }
  23210. if (enabled) {
  23211. this.trigger('debugon');
  23212. this.previousLogLevel_ = this.log.level;
  23213. this.log.level('debug');
  23214. this.debugEnabled_ = true;
  23215. } else {
  23216. this.trigger('debugoff');
  23217. this.log.level(this.previousLogLevel_);
  23218. this.previousLogLevel_ = undefined;
  23219. this.debugEnabled_ = false;
  23220. }
  23221. }
  23222. /**
  23223. * Set or get current playback rates.
  23224. * Takes an array and updates the playback rates menu with the new items.
  23225. * Pass in an empty array to hide the menu.
  23226. * Values other than arrays are ignored.
  23227. *
  23228. * @fires Player#playbackrateschange
  23229. * @param {number[]} newRates
  23230. * The new rates that the playback rates menu should update to.
  23231. * An empty array will hide the menu
  23232. * @return {number[]} When used as a getter will return the current playback rates
  23233. */
  23234. ;
  23235. _proto.playbackRates = function playbackRates(newRates) {
  23236. if (newRates === undefined) {
  23237. return this.cache_.playbackRates;
  23238. } // ignore any value that isn't an array
  23239. if (!Array.isArray(newRates)) {
  23240. return;
  23241. } // ignore any arrays that don't only contain numbers
  23242. if (!newRates.every(function (rate) {
  23243. return typeof rate === 'number';
  23244. })) {
  23245. return;
  23246. }
  23247. this.cache_.playbackRates = newRates;
  23248. /**
  23249. * fires when the playback rates in a player are changed
  23250. *
  23251. * @event Player#playbackrateschange
  23252. * @type {EventTarget~Event}
  23253. */
  23254. this.trigger('playbackrateschange');
  23255. };
  23256. return Player;
  23257. }(Component$1);
  23258. /**
  23259. * Get the {@link VideoTrackList}
  23260. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  23261. *
  23262. * @return {VideoTrackList}
  23263. * the current video track list
  23264. *
  23265. * @method Player.prototype.videoTracks
  23266. */
  23267. /**
  23268. * Get the {@link AudioTrackList}
  23269. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  23270. *
  23271. * @return {AudioTrackList}
  23272. * the current audio track list
  23273. *
  23274. * @method Player.prototype.audioTracks
  23275. */
  23276. /**
  23277. * Get the {@link TextTrackList}
  23278. *
  23279. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  23280. *
  23281. * @return {TextTrackList}
  23282. * the current text track list
  23283. *
  23284. * @method Player.prototype.textTracks
  23285. */
  23286. /**
  23287. * Get the remote {@link TextTrackList}
  23288. *
  23289. * @return {TextTrackList}
  23290. * The current remote text track list
  23291. *
  23292. * @method Player.prototype.remoteTextTracks
  23293. */
  23294. /**
  23295. * Get the remote {@link HtmlTrackElementList} tracks.
  23296. *
  23297. * @return {HtmlTrackElementList}
  23298. * The current remote text track element list
  23299. *
  23300. * @method Player.prototype.remoteTextTrackEls
  23301. */
  23302. ALL.names.forEach(function (name) {
  23303. var props = ALL[name];
  23304. Player.prototype[props.getterName] = function () {
  23305. if (this.tech_) {
  23306. return this.tech_[props.getterName]();
  23307. } // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  23308. // these will be passed to the tech during loading
  23309. this[props.privateName] = this[props.privateName] || new props.ListClass();
  23310. return this[props.privateName];
  23311. };
  23312. });
  23313. /**
  23314. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  23315. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  23316. * behavior.
  23317. *
  23318. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  23319. *
  23320. * @param {string} [value]
  23321. * The value to set the `Player`'s crossorigin to. If an argument is
  23322. * given, must be one of `anonymous` or `use-credentials`.
  23323. *
  23324. * @return {string|undefined}
  23325. * - The current crossorigin value of the `Player` when getting.
  23326. * - undefined when setting
  23327. */
  23328. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  23329. /**
  23330. * Global enumeration of players.
  23331. *
  23332. * The keys are the player IDs and the values are either the {@link Player}
  23333. * instance or `null` for disposed players.
  23334. *
  23335. * @type {Object}
  23336. */
  23337. Player.players = {};
  23338. var navigator = window__default['default'].navigator;
  23339. /*
  23340. * Player instance options, surfaced using options
  23341. * options = Player.prototype.options_
  23342. * Make changes in options, not here.
  23343. *
  23344. * @type {Object}
  23345. * @private
  23346. */
  23347. Player.prototype.options_ = {
  23348. // Default order of fallback technology
  23349. techOrder: Tech.defaultTechOrder_,
  23350. html5: {},
  23351. // default inactivity timeout
  23352. inactivityTimeout: 2000,
  23353. // default playback rates
  23354. playbackRates: [],
  23355. // Add playback rate selection by adding rates
  23356. // 'playbackRates': [0.5, 1, 1.5, 2],
  23357. liveui: false,
  23358. // Included control sets
  23359. children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  23360. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  23361. // locales and their language translations
  23362. languages: {},
  23363. // Default message to show when a video cannot be played.
  23364. notSupportedMessage: 'No compatible source was found for this media.',
  23365. normalizeAutoplay: false,
  23366. fullscreen: {
  23367. options: {
  23368. navigationUI: 'hide'
  23369. }
  23370. },
  23371. breakpoints: {},
  23372. responsive: false,
  23373. audioOnlyMode: false,
  23374. audioPosterMode: false
  23375. };
  23376. [
  23377. /**
  23378. * Returns whether or not the player is in the "ended" state.
  23379. *
  23380. * @return {Boolean} True if the player is in the ended state, false if not.
  23381. * @method Player#ended
  23382. */
  23383. 'ended',
  23384. /**
  23385. * Returns whether or not the player is in the "seeking" state.
  23386. *
  23387. * @return {Boolean} True if the player is in the seeking state, false if not.
  23388. * @method Player#seeking
  23389. */
  23390. 'seeking',
  23391. /**
  23392. * Returns the TimeRanges of the media that are currently available
  23393. * for seeking to.
  23394. *
  23395. * @return {TimeRanges} the seekable intervals of the media timeline
  23396. * @method Player#seekable
  23397. */
  23398. 'seekable',
  23399. /**
  23400. * Returns the current state of network activity for the element, from
  23401. * the codes in the list below.
  23402. * - NETWORK_EMPTY (numeric value 0)
  23403. * The element has not yet been initialised. All attributes are in
  23404. * their initial states.
  23405. * - NETWORK_IDLE (numeric value 1)
  23406. * The element's resource selection algorithm is active and has
  23407. * selected a resource, but it is not actually using the network at
  23408. * this time.
  23409. * - NETWORK_LOADING (numeric value 2)
  23410. * The user agent is actively trying to download data.
  23411. * - NETWORK_NO_SOURCE (numeric value 3)
  23412. * The element's resource selection algorithm is active, but it has
  23413. * not yet found a resource to use.
  23414. *
  23415. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  23416. * @return {number} the current network activity state
  23417. * @method Player#networkState
  23418. */
  23419. 'networkState',
  23420. /**
  23421. * Returns a value that expresses the current state of the element
  23422. * with respect to rendering the current playback position, from the
  23423. * codes in the list below.
  23424. * - HAVE_NOTHING (numeric value 0)
  23425. * No information regarding the media resource is available.
  23426. * - HAVE_METADATA (numeric value 1)
  23427. * Enough of the resource has been obtained that the duration of the
  23428. * resource is available.
  23429. * - HAVE_CURRENT_DATA (numeric value 2)
  23430. * Data for the immediate current playback position is available.
  23431. * - HAVE_FUTURE_DATA (numeric value 3)
  23432. * Data for the immediate current playback position is available, as
  23433. * well as enough data for the user agent to advance the current
  23434. * playback position in the direction of playback.
  23435. * - HAVE_ENOUGH_DATA (numeric value 4)
  23436. * The user agent estimates that enough data is available for
  23437. * playback to proceed uninterrupted.
  23438. *
  23439. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  23440. * @return {number} the current playback rendering state
  23441. * @method Player#readyState
  23442. */
  23443. 'readyState'].forEach(function (fn) {
  23444. Player.prototype[fn] = function () {
  23445. return this.techGet_(fn);
  23446. };
  23447. });
  23448. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  23449. Player.prototype["handleTech" + toTitleCase$1(event) + "_"] = function () {
  23450. return this.trigger(event);
  23451. };
  23452. });
  23453. /**
  23454. * Fired when the player has initial duration and dimension information
  23455. *
  23456. * @event Player#loadedmetadata
  23457. * @type {EventTarget~Event}
  23458. */
  23459. /**
  23460. * Fired when the player has downloaded data at the current playback position
  23461. *
  23462. * @event Player#loadeddata
  23463. * @type {EventTarget~Event}
  23464. */
  23465. /**
  23466. * Fired when the current playback position has changed *
  23467. * During playback this is fired every 15-250 milliseconds, depending on the
  23468. * playback technology in use.
  23469. *
  23470. * @event Player#timeupdate
  23471. * @type {EventTarget~Event}
  23472. */
  23473. /**
  23474. * Fired when the volume changes
  23475. *
  23476. * @event Player#volumechange
  23477. * @type {EventTarget~Event}
  23478. */
  23479. /**
  23480. * Reports whether or not a player has a plugin available.
  23481. *
  23482. * This does not report whether or not the plugin has ever been initialized
  23483. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  23484. *
  23485. * @method Player#hasPlugin
  23486. * @param {string} name
  23487. * The name of a plugin.
  23488. *
  23489. * @return {boolean}
  23490. * Whether or not this player has the requested plugin available.
  23491. */
  23492. /**
  23493. * Reports whether or not a player is using a plugin by name.
  23494. *
  23495. * For basic plugins, this only reports whether the plugin has _ever_ been
  23496. * initialized on this player.
  23497. *
  23498. * @method Player#usingPlugin
  23499. * @param {string} name
  23500. * The name of a plugin.
  23501. *
  23502. * @return {boolean}
  23503. * Whether or not this player is using the requested plugin.
  23504. */
  23505. Component$1.registerComponent('Player', Player);
  23506. /**
  23507. * The base plugin name.
  23508. *
  23509. * @private
  23510. * @constant
  23511. * @type {string}
  23512. */
  23513. var BASE_PLUGIN_NAME = 'plugin';
  23514. /**
  23515. * The key on which a player's active plugins cache is stored.
  23516. *
  23517. * @private
  23518. * @constant
  23519. * @type {string}
  23520. */
  23521. var PLUGIN_CACHE_KEY = 'activePlugins_';
  23522. /**
  23523. * Stores registered plugins in a private space.
  23524. *
  23525. * @private
  23526. * @type {Object}
  23527. */
  23528. var pluginStorage = {};
  23529. /**
  23530. * Reports whether or not a plugin has been registered.
  23531. *
  23532. * @private
  23533. * @param {string} name
  23534. * The name of a plugin.
  23535. *
  23536. * @return {boolean}
  23537. * Whether or not the plugin has been registered.
  23538. */
  23539. var pluginExists = function pluginExists(name) {
  23540. return pluginStorage.hasOwnProperty(name);
  23541. };
  23542. /**
  23543. * Get a single registered plugin by name.
  23544. *
  23545. * @private
  23546. * @param {string} name
  23547. * The name of a plugin.
  23548. *
  23549. * @return {Function|undefined}
  23550. * The plugin (or undefined).
  23551. */
  23552. var getPlugin = function getPlugin(name) {
  23553. return pluginExists(name) ? pluginStorage[name] : undefined;
  23554. };
  23555. /**
  23556. * Marks a plugin as "active" on a player.
  23557. *
  23558. * Also, ensures that the player has an object for tracking active plugins.
  23559. *
  23560. * @private
  23561. * @param {Player} player
  23562. * A Video.js player instance.
  23563. *
  23564. * @param {string} name
  23565. * The name of a plugin.
  23566. */
  23567. var markPluginAsActive = function markPluginAsActive(player, name) {
  23568. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  23569. player[PLUGIN_CACHE_KEY][name] = true;
  23570. };
  23571. /**
  23572. * Triggers a pair of plugin setup events.
  23573. *
  23574. * @private
  23575. * @param {Player} player
  23576. * A Video.js player instance.
  23577. *
  23578. * @param {Plugin~PluginEventHash} hash
  23579. * A plugin event hash.
  23580. *
  23581. * @param {boolean} [before]
  23582. * If true, prefixes the event name with "before". In other words,
  23583. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  23584. */
  23585. var triggerSetupEvent = function triggerSetupEvent(player, hash, before) {
  23586. var eventName = (before ? 'before' : '') + 'pluginsetup';
  23587. player.trigger(eventName, hash);
  23588. player.trigger(eventName + ':' + hash.name, hash);
  23589. };
  23590. /**
  23591. * Takes a basic plugin function and returns a wrapper function which marks
  23592. * on the player that the plugin has been activated.
  23593. *
  23594. * @private
  23595. * @param {string} name
  23596. * The name of the plugin.
  23597. *
  23598. * @param {Function} plugin
  23599. * The basic plugin.
  23600. *
  23601. * @return {Function}
  23602. * A wrapper function for the given plugin.
  23603. */
  23604. var createBasicPlugin = function createBasicPlugin(name, plugin) {
  23605. var basicPluginWrapper = function basicPluginWrapper() {
  23606. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  23607. // regardless, but we want the hash to be consistent with the hash provided
  23608. // for advanced plugins.
  23609. //
  23610. // The only potentially counter-intuitive thing here is the `instance` in
  23611. // the "pluginsetup" event is the value returned by the `plugin` function.
  23612. triggerSetupEvent(this, {
  23613. name: name,
  23614. plugin: plugin,
  23615. instance: null
  23616. }, true);
  23617. var instance = plugin.apply(this, arguments);
  23618. markPluginAsActive(this, name);
  23619. triggerSetupEvent(this, {
  23620. name: name,
  23621. plugin: plugin,
  23622. instance: instance
  23623. });
  23624. return instance;
  23625. };
  23626. Object.keys(plugin).forEach(function (prop) {
  23627. basicPluginWrapper[prop] = plugin[prop];
  23628. });
  23629. return basicPluginWrapper;
  23630. };
  23631. /**
  23632. * Takes a plugin sub-class and returns a factory function for generating
  23633. * instances of it.
  23634. *
  23635. * This factory function will replace itself with an instance of the requested
  23636. * sub-class of Plugin.
  23637. *
  23638. * @private
  23639. * @param {string} name
  23640. * The name of the plugin.
  23641. *
  23642. * @param {Plugin} PluginSubClass
  23643. * The advanced plugin.
  23644. *
  23645. * @return {Function}
  23646. */
  23647. var createPluginFactory = function createPluginFactory(name, PluginSubClass) {
  23648. // Add a `name` property to the plugin prototype so that each plugin can
  23649. // refer to itself by name.
  23650. PluginSubClass.prototype.name = name;
  23651. return function () {
  23652. triggerSetupEvent(this, {
  23653. name: name,
  23654. plugin: PluginSubClass,
  23655. instance: null
  23656. }, true);
  23657. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  23658. args[_key] = arguments[_key];
  23659. }
  23660. var instance = _construct__default['default'](PluginSubClass, [this].concat(args)); // The plugin is replaced by a function that returns the current instance.
  23661. this[name] = function () {
  23662. return instance;
  23663. };
  23664. triggerSetupEvent(this, instance.getEventHash());
  23665. return instance;
  23666. };
  23667. };
  23668. /**
  23669. * Parent class for all advanced plugins.
  23670. *
  23671. * @mixes module:evented~EventedMixin
  23672. * @mixes module:stateful~StatefulMixin
  23673. * @fires Player#beforepluginsetup
  23674. * @fires Player#beforepluginsetup:$name
  23675. * @fires Player#pluginsetup
  23676. * @fires Player#pluginsetup:$name
  23677. * @listens Player#dispose
  23678. * @throws {Error}
  23679. * If attempting to instantiate the base {@link Plugin} class
  23680. * directly instead of via a sub-class.
  23681. */
  23682. var Plugin = /*#__PURE__*/function () {
  23683. /**
  23684. * Creates an instance of this class.
  23685. *
  23686. * Sub-classes should call `super` to ensure plugins are properly initialized.
  23687. *
  23688. * @param {Player} player
  23689. * A Video.js player instance.
  23690. */
  23691. function Plugin(player) {
  23692. if (this.constructor === Plugin) {
  23693. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  23694. }
  23695. this.player = player;
  23696. if (!this.log) {
  23697. this.log = this.player.log.createLogger(this.name);
  23698. } // Make this object evented, but remove the added `trigger` method so we
  23699. // use the prototype version instead.
  23700. evented(this);
  23701. delete this.trigger;
  23702. stateful(this, this.constructor.defaultState);
  23703. markPluginAsActive(player, this.name); // Auto-bind the dispose method so we can use it as a listener and unbind
  23704. // it later easily.
  23705. this.dispose = this.dispose.bind(this); // If the player is disposed, dispose the plugin.
  23706. player.on('dispose', this.dispose);
  23707. }
  23708. /**
  23709. * Get the version of the plugin that was set on <pluginName>.VERSION
  23710. */
  23711. var _proto = Plugin.prototype;
  23712. _proto.version = function version() {
  23713. return this.constructor.VERSION;
  23714. }
  23715. /**
  23716. * Each event triggered by plugins includes a hash of additional data with
  23717. * conventional properties.
  23718. *
  23719. * This returns that object or mutates an existing hash.
  23720. *
  23721. * @param {Object} [hash={}]
  23722. * An object to be used as event an event hash.
  23723. *
  23724. * @return {Plugin~PluginEventHash}
  23725. * An event hash object with provided properties mixed-in.
  23726. */
  23727. ;
  23728. _proto.getEventHash = function getEventHash(hash) {
  23729. if (hash === void 0) {
  23730. hash = {};
  23731. }
  23732. hash.name = this.name;
  23733. hash.plugin = this.constructor;
  23734. hash.instance = this;
  23735. return hash;
  23736. }
  23737. /**
  23738. * Triggers an event on the plugin object and overrides
  23739. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  23740. *
  23741. * @param {string|Object} event
  23742. * An event type or an object with a type property.
  23743. *
  23744. * @param {Object} [hash={}]
  23745. * Additional data hash to merge with a
  23746. * {@link Plugin~PluginEventHash|PluginEventHash}.
  23747. *
  23748. * @return {boolean}
  23749. * Whether or not default was prevented.
  23750. */
  23751. ;
  23752. _proto.trigger = function trigger$1(event, hash) {
  23753. if (hash === void 0) {
  23754. hash = {};
  23755. }
  23756. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  23757. }
  23758. /**
  23759. * Handles "statechanged" events on the plugin. No-op by default, override by
  23760. * subclassing.
  23761. *
  23762. * @abstract
  23763. * @param {Event} e
  23764. * An event object provided by a "statechanged" event.
  23765. *
  23766. * @param {Object} e.changes
  23767. * An object describing changes that occurred with the "statechanged"
  23768. * event.
  23769. */
  23770. ;
  23771. _proto.handleStateChanged = function handleStateChanged(e) {}
  23772. /**
  23773. * Disposes a plugin.
  23774. *
  23775. * Subclasses can override this if they want, but for the sake of safety,
  23776. * it's probably best to subscribe the "dispose" event.
  23777. *
  23778. * @fires Plugin#dispose
  23779. */
  23780. ;
  23781. _proto.dispose = function dispose() {
  23782. var name = this.name,
  23783. player = this.player;
  23784. /**
  23785. * Signals that a advanced plugin is about to be disposed.
  23786. *
  23787. * @event Plugin#dispose
  23788. * @type {EventTarget~Event}
  23789. */
  23790. this.trigger('dispose');
  23791. this.off();
  23792. player.off('dispose', this.dispose); // Eliminate any possible sources of leaking memory by clearing up
  23793. // references between the player and the plugin instance and nulling out
  23794. // the plugin's state and replacing methods with a function that throws.
  23795. player[PLUGIN_CACHE_KEY][name] = false;
  23796. this.player = this.state = null; // Finally, replace the plugin name on the player with a new factory
  23797. // function, so that the plugin is ready to be set up again.
  23798. player[name] = createPluginFactory(name, pluginStorage[name]);
  23799. }
  23800. /**
  23801. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  23802. *
  23803. * @param {string|Function} plugin
  23804. * If a string, matches the name of a plugin. If a function, will be
  23805. * tested directly.
  23806. *
  23807. * @return {boolean}
  23808. * Whether or not a plugin is a basic plugin.
  23809. */
  23810. ;
  23811. Plugin.isBasic = function isBasic(plugin) {
  23812. var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  23813. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  23814. }
  23815. /**
  23816. * Register a Video.js plugin.
  23817. *
  23818. * @param {string} name
  23819. * The name of the plugin to be registered. Must be a string and
  23820. * must not match an existing plugin or a method on the `Player`
  23821. * prototype.
  23822. *
  23823. * @param {Function} plugin
  23824. * A sub-class of `Plugin` or a function for basic plugins.
  23825. *
  23826. * @return {Function}
  23827. * For advanced plugins, a factory function for that plugin. For
  23828. * basic plugins, a wrapper function that initializes the plugin.
  23829. */
  23830. ;
  23831. Plugin.registerPlugin = function registerPlugin(name, plugin) {
  23832. if (typeof name !== 'string') {
  23833. throw new Error("Illegal plugin name, \"" + name + "\", must be a string, was " + typeof name + ".");
  23834. }
  23835. if (pluginExists(name)) {
  23836. log$1.warn("A plugin named \"" + name + "\" already exists. You may want to avoid re-registering plugins!");
  23837. } else if (Player.prototype.hasOwnProperty(name)) {
  23838. throw new Error("Illegal plugin name, \"" + name + "\", cannot share a name with an existing player method!");
  23839. }
  23840. if (typeof plugin !== 'function') {
  23841. throw new Error("Illegal plugin for \"" + name + "\", must be a function, was " + typeof plugin + ".");
  23842. }
  23843. pluginStorage[name] = plugin; // Add a player prototype method for all sub-classed plugins (but not for
  23844. // the base Plugin class).
  23845. if (name !== BASE_PLUGIN_NAME) {
  23846. if (Plugin.isBasic(plugin)) {
  23847. Player.prototype[name] = createBasicPlugin(name, plugin);
  23848. } else {
  23849. Player.prototype[name] = createPluginFactory(name, plugin);
  23850. }
  23851. }
  23852. return plugin;
  23853. }
  23854. /**
  23855. * De-register a Video.js plugin.
  23856. *
  23857. * @param {string} name
  23858. * The name of the plugin to be de-registered. Must be a string that
  23859. * matches an existing plugin.
  23860. *
  23861. * @throws {Error}
  23862. * If an attempt is made to de-register the base plugin.
  23863. */
  23864. ;
  23865. Plugin.deregisterPlugin = function deregisterPlugin(name) {
  23866. if (name === BASE_PLUGIN_NAME) {
  23867. throw new Error('Cannot de-register base plugin.');
  23868. }
  23869. if (pluginExists(name)) {
  23870. delete pluginStorage[name];
  23871. delete Player.prototype[name];
  23872. }
  23873. }
  23874. /**
  23875. * Gets an object containing multiple Video.js plugins.
  23876. *
  23877. * @param {Array} [names]
  23878. * If provided, should be an array of plugin names. Defaults to _all_
  23879. * plugin names.
  23880. *
  23881. * @return {Object|undefined}
  23882. * An object containing plugin(s) associated with their name(s) or
  23883. * `undefined` if no matching plugins exist).
  23884. */
  23885. ;
  23886. Plugin.getPlugins = function getPlugins(names) {
  23887. if (names === void 0) {
  23888. names = Object.keys(pluginStorage);
  23889. }
  23890. var result;
  23891. names.forEach(function (name) {
  23892. var plugin = getPlugin(name);
  23893. if (plugin) {
  23894. result = result || {};
  23895. result[name] = plugin;
  23896. }
  23897. });
  23898. return result;
  23899. }
  23900. /**
  23901. * Gets a plugin's version, if available
  23902. *
  23903. * @param {string} name
  23904. * The name of a plugin.
  23905. *
  23906. * @return {string}
  23907. * The plugin's version or an empty string.
  23908. */
  23909. ;
  23910. Plugin.getPluginVersion = function getPluginVersion(name) {
  23911. var plugin = getPlugin(name);
  23912. return plugin && plugin.VERSION || '';
  23913. };
  23914. return Plugin;
  23915. }();
  23916. /**
  23917. * Gets a plugin by name if it exists.
  23918. *
  23919. * @static
  23920. * @method getPlugin
  23921. * @memberOf Plugin
  23922. * @param {string} name
  23923. * The name of a plugin.
  23924. *
  23925. * @returns {Function|undefined}
  23926. * The plugin (or `undefined`).
  23927. */
  23928. Plugin.getPlugin = getPlugin;
  23929. /**
  23930. * The name of the base plugin class as it is registered.
  23931. *
  23932. * @type {string}
  23933. */
  23934. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  23935. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  23936. /**
  23937. * Documented in player.js
  23938. *
  23939. * @ignore
  23940. */
  23941. Player.prototype.usingPlugin = function (name) {
  23942. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  23943. };
  23944. /**
  23945. * Documented in player.js
  23946. *
  23947. * @ignore
  23948. */
  23949. Player.prototype.hasPlugin = function (name) {
  23950. return !!pluginExists(name);
  23951. };
  23952. /**
  23953. * Signals that a plugin is about to be set up on a player.
  23954. *
  23955. * @event Player#beforepluginsetup
  23956. * @type {Plugin~PluginEventHash}
  23957. */
  23958. /**
  23959. * Signals that a plugin is about to be set up on a player - by name. The name
  23960. * is the name of the plugin.
  23961. *
  23962. * @event Player#beforepluginsetup:$name
  23963. * @type {Plugin~PluginEventHash}
  23964. */
  23965. /**
  23966. * Signals that a plugin has just been set up on a player.
  23967. *
  23968. * @event Player#pluginsetup
  23969. * @type {Plugin~PluginEventHash}
  23970. */
  23971. /**
  23972. * Signals that a plugin has just been set up on a player - by name. The name
  23973. * is the name of the plugin.
  23974. *
  23975. * @event Player#pluginsetup:$name
  23976. * @type {Plugin~PluginEventHash}
  23977. */
  23978. /**
  23979. * @typedef {Object} Plugin~PluginEventHash
  23980. *
  23981. * @property {string} instance
  23982. * For basic plugins, the return value of the plugin function. For
  23983. * advanced plugins, the plugin instance on which the event is fired.
  23984. *
  23985. * @property {string} name
  23986. * The name of the plugin.
  23987. *
  23988. * @property {string} plugin
  23989. * For basic plugins, the plugin function. For advanced plugins, the
  23990. * plugin class/constructor.
  23991. */
  23992. /**
  23993. * @file extend.js
  23994. * @module extend
  23995. */
  23996. var hasLogged = false;
  23997. /**
  23998. * Used to subclass an existing class by emulating ES subclassing using the
  23999. * `extends` keyword.
  24000. *
  24001. * @function
  24002. * @deprecated
  24003. * @example
  24004. * var MyComponent = videojs.extend(videojs.getComponent('Component'), {
  24005. * myCustomMethod: function() {
  24006. * // Do things in my method.
  24007. * }
  24008. * });
  24009. *
  24010. * @param {Function} superClass
  24011. * The class to inherit from
  24012. *
  24013. * @param {Object} [subClassMethods={}]
  24014. * Methods of the new class
  24015. *
  24016. * @return {Function}
  24017. * The new class with subClassMethods that inherited superClass.
  24018. */
  24019. var extend = function extend(superClass, subClassMethods) {
  24020. if (subClassMethods === void 0) {
  24021. subClassMethods = {};
  24022. }
  24023. // Log a warning the first time extend is called to note that it is deprecated
  24024. // It was previously deprecated in our documentation (guides, specifically),
  24025. // but was never formally deprecated in code.
  24026. if (!hasLogged) {
  24027. log$1.warn('videojs.extend is deprecated as of Video.js 7.22.0 and will be removed in Video.js 8.0.0');
  24028. hasLogged = true;
  24029. }
  24030. var subClass = function subClass() {
  24031. superClass.apply(this, arguments);
  24032. };
  24033. var methods = {};
  24034. if (typeof subClassMethods === 'object') {
  24035. if (subClassMethods.constructor !== Object.prototype.constructor) {
  24036. subClass = subClassMethods.constructor;
  24037. }
  24038. methods = subClassMethods;
  24039. } else if (typeof subClassMethods === 'function') {
  24040. subClass = subClassMethods;
  24041. }
  24042. _inherits__default['default'](subClass, superClass); // this is needed for backward-compatibility and node compatibility.
  24043. if (superClass) {
  24044. subClass.super_ = superClass;
  24045. } // Extend subObj's prototype with functions and other properties from props
  24046. for (var name in methods) {
  24047. if (methods.hasOwnProperty(name)) {
  24048. subClass.prototype[name] = methods[name];
  24049. }
  24050. }
  24051. return subClass;
  24052. };
  24053. /**
  24054. * @file video.js
  24055. * @module videojs
  24056. */
  24057. /**
  24058. * Normalize an `id` value by trimming off a leading `#`
  24059. *
  24060. * @private
  24061. * @param {string} id
  24062. * A string, maybe with a leading `#`.
  24063. *
  24064. * @return {string}
  24065. * The string, without any leading `#`.
  24066. */
  24067. var normalizeId = function normalizeId(id) {
  24068. return id.indexOf('#') === 0 ? id.slice(1) : id;
  24069. };
  24070. /**
  24071. * The `videojs()` function doubles as the main function for users to create a
  24072. * {@link Player} instance as well as the main library namespace.
  24073. *
  24074. * It can also be used as a getter for a pre-existing {@link Player} instance.
  24075. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  24076. * purpose because it avoids any potential for unintended initialization.
  24077. *
  24078. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  24079. * of our JSDoc template, we cannot properly document this as both a function
  24080. * and a namespace, so its function signature is documented here.
  24081. *
  24082. * #### Arguments
  24083. * ##### id
  24084. * string|Element, **required**
  24085. *
  24086. * Video element or video element ID.
  24087. *
  24088. * ##### options
  24089. * Object, optional
  24090. *
  24091. * Options object for providing settings.
  24092. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24093. *
  24094. * ##### ready
  24095. * {@link Component~ReadyCallback}, optional
  24096. *
  24097. * A function to be called when the {@link Player} and {@link Tech} are ready.
  24098. *
  24099. * #### Return Value
  24100. *
  24101. * The `videojs()` function returns a {@link Player} instance.
  24102. *
  24103. * @namespace
  24104. *
  24105. * @borrows AudioTrack as AudioTrack
  24106. * @borrows Component.getComponent as getComponent
  24107. * @borrows module:computed-style~computedStyle as computedStyle
  24108. * @borrows module:events.on as on
  24109. * @borrows module:events.one as one
  24110. * @borrows module:events.off as off
  24111. * @borrows module:events.trigger as trigger
  24112. * @borrows EventTarget as EventTarget
  24113. * @borrows module:extend~extend as extend
  24114. * @borrows module:fn.bind as bind
  24115. * @borrows module:format-time.formatTime as formatTime
  24116. * @borrows module:format-time.resetFormatTime as resetFormatTime
  24117. * @borrows module:format-time.setFormatTime as setFormatTime
  24118. * @borrows module:merge-options.mergeOptions as mergeOptions
  24119. * @borrows module:middleware.use as use
  24120. * @borrows Player.players as players
  24121. * @borrows Plugin.registerPlugin as registerPlugin
  24122. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  24123. * @borrows Plugin.getPlugins as getPlugins
  24124. * @borrows Plugin.getPlugin as getPlugin
  24125. * @borrows Plugin.getPluginVersion as getPluginVersion
  24126. * @borrows Tech.getTech as getTech
  24127. * @borrows Tech.registerTech as registerTech
  24128. * @borrows TextTrack as TextTrack
  24129. * @borrows module:time-ranges.createTimeRanges as createTimeRange
  24130. * @borrows module:time-ranges.createTimeRanges as createTimeRanges
  24131. * @borrows module:url.isCrossOrigin as isCrossOrigin
  24132. * @borrows module:url.parseUrl as parseUrl
  24133. * @borrows VideoTrack as VideoTrack
  24134. *
  24135. * @param {string|Element} id
  24136. * Video element or video element ID.
  24137. *
  24138. * @param {Object} [options]
  24139. * Options object for providing settings.
  24140. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24141. *
  24142. * @param {Component~ReadyCallback} [ready]
  24143. * A function to be called when the {@link Player} and {@link Tech} are
  24144. * ready.
  24145. *
  24146. * @return {Player}
  24147. * The `videojs()` function returns a {@link Player|Player} instance.
  24148. */
  24149. function videojs(id, options, ready) {
  24150. var player = videojs.getPlayer(id);
  24151. if (player) {
  24152. if (options) {
  24153. log$1.warn("Player \"" + id + "\" is already initialised. Options will not be applied.");
  24154. }
  24155. if (ready) {
  24156. player.ready(ready);
  24157. }
  24158. return player;
  24159. }
  24160. var el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  24161. if (!isEl(el)) {
  24162. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  24163. } // document.body.contains(el) will only check if el is contained within that one document.
  24164. // This causes problems for elements in iframes.
  24165. // Instead, use the element's ownerDocument instead of the global document.
  24166. // This will make sure that the element is indeed in the dom of that document.
  24167. // Additionally, check that the document in question has a default view.
  24168. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  24169. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  24170. log$1.warn('The element supplied is not included in the DOM');
  24171. }
  24172. options = options || {}; // Store a copy of the el before modification, if it is to be restored in destroy()
  24173. // If div ingest, store the parent div
  24174. if (options.restoreEl === true) {
  24175. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  24176. }
  24177. hooks('beforesetup').forEach(function (hookFunction) {
  24178. var opts = hookFunction(el, mergeOptions$3(options));
  24179. if (!isObject(opts) || Array.isArray(opts)) {
  24180. log$1.error('please return an object in beforesetup hooks');
  24181. return;
  24182. }
  24183. options = mergeOptions$3(options, opts);
  24184. }); // We get the current "Player" component here in case an integration has
  24185. // replaced it with a custom player.
  24186. var PlayerComponent = Component$1.getComponent('Player');
  24187. player = new PlayerComponent(el, options, ready);
  24188. hooks('setup').forEach(function (hookFunction) {
  24189. return hookFunction(player);
  24190. });
  24191. return player;
  24192. }
  24193. videojs.hooks_ = hooks_;
  24194. videojs.hooks = hooks;
  24195. videojs.hook = hook;
  24196. videojs.hookOnce = hookOnce;
  24197. videojs.removeHook = removeHook; // Add default styles
  24198. if (window__default['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  24199. var style = $('.vjs-styles-defaults');
  24200. if (!style) {
  24201. style = createStyleElement('vjs-styles-defaults');
  24202. var head = $('head');
  24203. if (head) {
  24204. head.insertBefore(style, head.firstChild);
  24205. }
  24206. setTextContent(style, "\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: 56.25%\n }\n ");
  24207. }
  24208. } // Run Auto-load players
  24209. // You have to wait at least once in case this script is loaded after your
  24210. // video in the DOM (weird behavior only with minified version)
  24211. autoSetupTimeout(1, videojs);
  24212. /**
  24213. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  24214. *
  24215. * @type {string}
  24216. */
  24217. videojs.VERSION = version$5;
  24218. /**
  24219. * The global options object. These are the settings that take effect
  24220. * if no overrides are specified when the player is created.
  24221. *
  24222. * @type {Object}
  24223. */
  24224. videojs.options = Player.prototype.options_;
  24225. /**
  24226. * Get an object with the currently created players, keyed by player ID
  24227. *
  24228. * @return {Object}
  24229. * The created players
  24230. */
  24231. videojs.getPlayers = function () {
  24232. return Player.players;
  24233. };
  24234. /**
  24235. * Get a single player based on an ID or DOM element.
  24236. *
  24237. * This is useful if you want to check if an element or ID has an associated
  24238. * Video.js player, but not create one if it doesn't.
  24239. *
  24240. * @param {string|Element} id
  24241. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  24242. * or a string matching the `id` of such an element.
  24243. *
  24244. * @return {Player|undefined}
  24245. * A player instance or `undefined` if there is no player instance
  24246. * matching the argument.
  24247. */
  24248. videojs.getPlayer = function (id) {
  24249. var players = Player.players;
  24250. var tag;
  24251. if (typeof id === 'string') {
  24252. var nId = normalizeId(id);
  24253. var player = players[nId];
  24254. if (player) {
  24255. return player;
  24256. }
  24257. tag = $('#' + nId);
  24258. } else {
  24259. tag = id;
  24260. }
  24261. if (isEl(tag)) {
  24262. var _tag = tag,
  24263. _player = _tag.player,
  24264. playerId = _tag.playerId; // Element may have a `player` property referring to an already created
  24265. // player instance. If so, return that.
  24266. if (_player || players[playerId]) {
  24267. return _player || players[playerId];
  24268. }
  24269. }
  24270. };
  24271. /**
  24272. * Returns an array of all current players.
  24273. *
  24274. * @return {Array}
  24275. * An array of all players. The array will be in the order that
  24276. * `Object.keys` provides, which could potentially vary between
  24277. * JavaScript engines.
  24278. *
  24279. */
  24280. videojs.getAllPlayers = function () {
  24281. return (// Disposed players leave a key with a `null` value, so we need to make sure
  24282. // we filter those out.
  24283. Object.keys(Player.players).map(function (k) {
  24284. return Player.players[k];
  24285. }).filter(Boolean)
  24286. );
  24287. };
  24288. videojs.players = Player.players;
  24289. videojs.getComponent = Component$1.getComponent;
  24290. /**
  24291. * Register a component so it can referred to by name. Used when adding to other
  24292. * components, either through addChild `component.addChild('myComponent')` or through
  24293. * default children options `{ children: ['myComponent'] }`.
  24294. *
  24295. * > NOTE: You could also just initialize the component before adding.
  24296. * `component.addChild(new MyComponent());`
  24297. *
  24298. * @param {string} name
  24299. * The class name of the component
  24300. *
  24301. * @param {Component} comp
  24302. * The component class
  24303. *
  24304. * @return {Component}
  24305. * The newly registered component
  24306. */
  24307. videojs.registerComponent = function (name, comp) {
  24308. if (Tech.isTech(comp)) {
  24309. log$1.warn("The " + name + " tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)");
  24310. }
  24311. Component$1.registerComponent.call(Component$1, name, comp);
  24312. };
  24313. videojs.getTech = Tech.getTech;
  24314. videojs.registerTech = Tech.registerTech;
  24315. videojs.use = use;
  24316. /**
  24317. * An object that can be returned by a middleware to signify
  24318. * that the middleware is being terminated.
  24319. *
  24320. * @type {object}
  24321. * @property {object} middleware.TERMINATOR
  24322. */
  24323. Object.defineProperty(videojs, 'middleware', {
  24324. value: {},
  24325. writeable: false,
  24326. enumerable: true
  24327. });
  24328. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  24329. value: TERMINATOR,
  24330. writeable: false,
  24331. enumerable: true
  24332. });
  24333. /**
  24334. * A reference to the {@link module:browser|browser utility module} as an object.
  24335. *
  24336. * @type {Object}
  24337. * @see {@link module:browser|browser}
  24338. */
  24339. videojs.browser = browser;
  24340. /**
  24341. * Use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED} instead; only
  24342. * included for backward-compatibility with 4.x.
  24343. *
  24344. * @deprecated Since version 5.0, use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED instead.
  24345. * @type {boolean}
  24346. */
  24347. videojs.TOUCH_ENABLED = TOUCH_ENABLED;
  24348. videojs.extend = extend;
  24349. videojs.mergeOptions = mergeOptions$3;
  24350. videojs.bind = bind;
  24351. videojs.registerPlugin = Plugin.registerPlugin;
  24352. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  24353. /**
  24354. * Deprecated method to register a plugin with Video.js
  24355. *
  24356. * @deprecated videojs.plugin() is deprecated; use videojs.registerPlugin() instead
  24357. *
  24358. * @param {string} name
  24359. * The plugin name
  24360. *
  24361. * @param {Plugin|Function} plugin
  24362. * The plugin sub-class or function
  24363. */
  24364. videojs.plugin = function (name, plugin) {
  24365. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  24366. return Plugin.registerPlugin(name, plugin);
  24367. };
  24368. videojs.getPlugins = Plugin.getPlugins;
  24369. videojs.getPlugin = Plugin.getPlugin;
  24370. videojs.getPluginVersion = Plugin.getPluginVersion;
  24371. /**
  24372. * Adding languages so that they're available to all players.
  24373. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  24374. *
  24375. * @param {string} code
  24376. * The language code or dictionary property
  24377. *
  24378. * @param {Object} data
  24379. * The data values to be translated
  24380. *
  24381. * @return {Object}
  24382. * The resulting language dictionary object
  24383. */
  24384. videojs.addLanguage = function (code, data) {
  24385. var _mergeOptions;
  24386. code = ('' + code).toLowerCase();
  24387. videojs.options.languages = mergeOptions$3(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions));
  24388. return videojs.options.languages[code];
  24389. };
  24390. /**
  24391. * A reference to the {@link module:log|log utility module} as an object.
  24392. *
  24393. * @type {Function}
  24394. * @see {@link module:log|log}
  24395. */
  24396. videojs.log = log$1;
  24397. videojs.createLogger = createLogger;
  24398. videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
  24399. videojs.formatTime = formatTime;
  24400. videojs.setFormatTime = setFormatTime;
  24401. videojs.resetFormatTime = resetFormatTime;
  24402. videojs.parseUrl = parseUrl;
  24403. videojs.isCrossOrigin = isCrossOrigin;
  24404. videojs.EventTarget = EventTarget$2;
  24405. videojs.on = on;
  24406. videojs.one = one;
  24407. videojs.off = off;
  24408. videojs.trigger = trigger;
  24409. /**
  24410. * A cross-browser XMLHttpRequest wrapper.
  24411. *
  24412. * @function
  24413. * @param {Object} options
  24414. * Settings for the request.
  24415. *
  24416. * @return {XMLHttpRequest|XDomainRequest}
  24417. * The request object.
  24418. *
  24419. * @see https://github.com/Raynos/xhr
  24420. */
  24421. videojs.xhr = XHR__default['default'];
  24422. videojs.TextTrack = TextTrack;
  24423. videojs.AudioTrack = AudioTrack;
  24424. videojs.VideoTrack = VideoTrack;
  24425. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) {
  24426. videojs[k] = function () {
  24427. log$1.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead");
  24428. return Dom[k].apply(null, arguments);
  24429. };
  24430. });
  24431. videojs.computedStyle = computedStyle;
  24432. /**
  24433. * A reference to the {@link module:dom|DOM utility module} as an object.
  24434. *
  24435. * @type {Object}
  24436. * @see {@link module:dom|dom}
  24437. */
  24438. videojs.dom = Dom;
  24439. /**
  24440. * A reference to the {@link module:url|URL utility module} as an object.
  24441. *
  24442. * @type {Object}
  24443. * @see {@link module:url|url}
  24444. */
  24445. videojs.url = Url;
  24446. videojs.defineLazyProperty = defineLazyProperty; // Adding less ambiguous text for fullscreen button.
  24447. // In a major update this could become the default text and key.
  24448. videojs.addLanguage('en', {
  24449. 'Non-Fullscreen': 'Exit Fullscreen'
  24450. });
  24451. /*! @name @videojs/http-streaming @version 2.16.2 @license Apache-2.0 */
  24452. /**
  24453. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  24454. */
  24455. var resolveUrl = _resolveUrl__default['default'];
  24456. /**
  24457. * Checks whether xhr request was redirected and returns correct url depending
  24458. * on `handleManifestRedirects` option
  24459. *
  24460. * @api private
  24461. *
  24462. * @param {string} url - an url being requested
  24463. * @param {XMLHttpRequest} req - xhr request result
  24464. *
  24465. * @return {string}
  24466. */
  24467. var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
  24468. // To understand how the responseURL below is set and generated:
  24469. // - https://fetch.spec.whatwg.org/#concept-response-url
  24470. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  24471. if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
  24472. return req.responseURL;
  24473. }
  24474. return url;
  24475. };
  24476. var logger = function logger(source) {
  24477. if (videojs.log.debug) {
  24478. return videojs.log.debug.bind(videojs, 'VHS:', source + " >");
  24479. }
  24480. return function () {};
  24481. };
  24482. /**
  24483. * ranges
  24484. *
  24485. * Utilities for working with TimeRanges.
  24486. *
  24487. */
  24488. var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  24489. // can be misleading because of precision differences or when the current media has poorly
  24490. // aligned audio and video, which can cause values to be slightly off from what you would
  24491. // expect. This value is what we consider to be safe to use in such comparisons to account
  24492. // for these scenarios.
  24493. var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  24494. var filterRanges = function filterRanges(timeRanges, predicate) {
  24495. var results = [];
  24496. var i;
  24497. if (timeRanges && timeRanges.length) {
  24498. // Search for ranges that match the predicate
  24499. for (i = 0; i < timeRanges.length; i++) {
  24500. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  24501. results.push([timeRanges.start(i), timeRanges.end(i)]);
  24502. }
  24503. }
  24504. }
  24505. return videojs.createTimeRanges(results);
  24506. };
  24507. /**
  24508. * Attempts to find the buffered TimeRange that contains the specified
  24509. * time.
  24510. *
  24511. * @param {TimeRanges} buffered - the TimeRanges object to query
  24512. * @param {number} time - the time to filter on.
  24513. * @return {TimeRanges} a new TimeRanges object
  24514. */
  24515. var findRange = function findRange(buffered, time) {
  24516. return filterRanges(buffered, function (start, end) {
  24517. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  24518. });
  24519. };
  24520. /**
  24521. * Returns the TimeRanges that begin later than the specified time.
  24522. *
  24523. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  24524. * @param {number} time - the time to filter on.
  24525. * @return {TimeRanges} a new TimeRanges object.
  24526. */
  24527. var findNextRange = function findNextRange(timeRanges, time) {
  24528. return filterRanges(timeRanges, function (start) {
  24529. return start - TIME_FUDGE_FACTOR >= time;
  24530. });
  24531. };
  24532. /**
  24533. * Returns gaps within a list of TimeRanges
  24534. *
  24535. * @param {TimeRanges} buffered - the TimeRanges object
  24536. * @return {TimeRanges} a TimeRanges object of gaps
  24537. */
  24538. var findGaps = function findGaps(buffered) {
  24539. if (buffered.length < 2) {
  24540. return videojs.createTimeRanges();
  24541. }
  24542. var ranges = [];
  24543. for (var i = 1; i < buffered.length; i++) {
  24544. var start = buffered.end(i - 1);
  24545. var end = buffered.start(i);
  24546. ranges.push([start, end]);
  24547. }
  24548. return videojs.createTimeRanges(ranges);
  24549. };
  24550. /**
  24551. * Calculate the intersection of two TimeRanges
  24552. *
  24553. * @param {TimeRanges} bufferA
  24554. * @param {TimeRanges} bufferB
  24555. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  24556. */
  24557. var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
  24558. var start = null;
  24559. var end = null;
  24560. var arity = 0;
  24561. var extents = [];
  24562. var ranges = [];
  24563. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  24564. return videojs.createTimeRange();
  24565. } // Handle the case where we have both buffers and create an
  24566. // intersection of the two
  24567. var count = bufferA.length; // A) Gather up all start and end times
  24568. while (count--) {
  24569. extents.push({
  24570. time: bufferA.start(count),
  24571. type: 'start'
  24572. });
  24573. extents.push({
  24574. time: bufferA.end(count),
  24575. type: 'end'
  24576. });
  24577. }
  24578. count = bufferB.length;
  24579. while (count--) {
  24580. extents.push({
  24581. time: bufferB.start(count),
  24582. type: 'start'
  24583. });
  24584. extents.push({
  24585. time: bufferB.end(count),
  24586. type: 'end'
  24587. });
  24588. } // B) Sort them by time
  24589. extents.sort(function (a, b) {
  24590. return a.time - b.time;
  24591. }); // C) Go along one by one incrementing arity for start and decrementing
  24592. // arity for ends
  24593. for (count = 0; count < extents.length; count++) {
  24594. if (extents[count].type === 'start') {
  24595. arity++; // D) If arity is ever incremented to 2 we are entering an
  24596. // overlapping range
  24597. if (arity === 2) {
  24598. start = extents[count].time;
  24599. }
  24600. } else if (extents[count].type === 'end') {
  24601. arity--; // E) If arity is ever decremented to 1 we leaving an
  24602. // overlapping range
  24603. if (arity === 1) {
  24604. end = extents[count].time;
  24605. }
  24606. } // F) Record overlapping ranges
  24607. if (start !== null && end !== null) {
  24608. ranges.push([start, end]);
  24609. start = null;
  24610. end = null;
  24611. }
  24612. }
  24613. return videojs.createTimeRanges(ranges);
  24614. };
  24615. /**
  24616. * Gets a human readable string for a TimeRange
  24617. *
  24618. * @param {TimeRange} range
  24619. * @return {string} a human readable string
  24620. */
  24621. var printableRange = function printableRange(range) {
  24622. var strArr = [];
  24623. if (!range || !range.length) {
  24624. return '';
  24625. }
  24626. for (var i = 0; i < range.length; i++) {
  24627. strArr.push(range.start(i) + ' => ' + range.end(i));
  24628. }
  24629. return strArr.join(', ');
  24630. };
  24631. /**
  24632. * Calculates the amount of time left in seconds until the player hits the end of the
  24633. * buffer and causes a rebuffer
  24634. *
  24635. * @param {TimeRange} buffered
  24636. * The state of the buffer
  24637. * @param {Numnber} currentTime
  24638. * The current time of the player
  24639. * @param {number} playbackRate
  24640. * The current playback rate of the player. Defaults to 1.
  24641. * @return {number}
  24642. * Time until the player has to start rebuffering in seconds.
  24643. * @function timeUntilRebuffer
  24644. */
  24645. var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
  24646. if (playbackRate === void 0) {
  24647. playbackRate = 1;
  24648. }
  24649. var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  24650. return (bufferedEnd - currentTime) / playbackRate;
  24651. };
  24652. /**
  24653. * Converts a TimeRanges object into an array representation
  24654. *
  24655. * @param {TimeRanges} timeRanges
  24656. * @return {Array}
  24657. */
  24658. var timeRangesToArray = function timeRangesToArray(timeRanges) {
  24659. var timeRangesList = [];
  24660. for (var i = 0; i < timeRanges.length; i++) {
  24661. timeRangesList.push({
  24662. start: timeRanges.start(i),
  24663. end: timeRanges.end(i)
  24664. });
  24665. }
  24666. return timeRangesList;
  24667. };
  24668. /**
  24669. * Determines if two time range objects are different.
  24670. *
  24671. * @param {TimeRange} a
  24672. * the first time range object to check
  24673. *
  24674. * @param {TimeRange} b
  24675. * the second time range object to check
  24676. *
  24677. * @return {Boolean}
  24678. * Whether the time range objects differ
  24679. */
  24680. var isRangeDifferent = function isRangeDifferent(a, b) {
  24681. // same object
  24682. if (a === b) {
  24683. return false;
  24684. } // one or the other is undefined
  24685. if (!a && b || !b && a) {
  24686. return true;
  24687. } // length is different
  24688. if (a.length !== b.length) {
  24689. return true;
  24690. } // see if any start/end pair is different
  24691. for (var i = 0; i < a.length; i++) {
  24692. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  24693. return true;
  24694. }
  24695. } // if the length and every pair is the same
  24696. // this is the same time range
  24697. return false;
  24698. };
  24699. var lastBufferedEnd = function lastBufferedEnd(a) {
  24700. if (!a || !a.length || !a.end) {
  24701. return;
  24702. }
  24703. return a.end(a.length - 1);
  24704. };
  24705. /**
  24706. * A utility function to add up the amount of time in a timeRange
  24707. * after a specified startTime.
  24708. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  24709. * would return 40 as there are 40s seconds after 0 in the timeRange
  24710. *
  24711. * @param {TimeRange} range
  24712. * The range to check against
  24713. * @param {number} startTime
  24714. * The time in the time range that you should start counting from
  24715. *
  24716. * @return {number}
  24717. * The number of seconds in the buffer passed the specified time.
  24718. */
  24719. var timeAheadOf = function timeAheadOf(range, startTime) {
  24720. var time = 0;
  24721. if (!range || !range.length) {
  24722. return time;
  24723. }
  24724. for (var i = 0; i < range.length; i++) {
  24725. var start = range.start(i);
  24726. var end = range.end(i); // startTime is after this range entirely
  24727. if (startTime > end) {
  24728. continue;
  24729. } // startTime is within this range
  24730. if (startTime > start && startTime <= end) {
  24731. time += end - startTime;
  24732. continue;
  24733. } // startTime is before this range.
  24734. time += end - start;
  24735. }
  24736. return time;
  24737. };
  24738. /**
  24739. * @file playlist.js
  24740. *
  24741. * Playlist related utilities.
  24742. */
  24743. var createTimeRange = videojs.createTimeRange;
  24744. /**
  24745. * Get the duration of a segment, with special cases for
  24746. * llhls segments that do not have a duration yet.
  24747. *
  24748. * @param {Object} playlist
  24749. * the playlist that the segment belongs to.
  24750. * @param {Object} segment
  24751. * the segment to get a duration for.
  24752. *
  24753. * @return {number}
  24754. * the segment duration
  24755. */
  24756. var segmentDurationWithParts = function segmentDurationWithParts(playlist, segment) {
  24757. // if this isn't a preload segment
  24758. // then we will have a segment duration that is accurate.
  24759. if (!segment.preload) {
  24760. return segment.duration;
  24761. } // otherwise we have to add up parts and preload hints
  24762. // to get an up to date duration.
  24763. var result = 0;
  24764. (segment.parts || []).forEach(function (p) {
  24765. result += p.duration;
  24766. }); // for preload hints we have to use partTargetDuration
  24767. // as they won't even have a duration yet.
  24768. (segment.preloadHints || []).forEach(function (p) {
  24769. if (p.type === 'PART') {
  24770. result += playlist.partTargetDuration;
  24771. }
  24772. });
  24773. return result;
  24774. };
  24775. /**
  24776. * A function to get a combined list of parts and segments with durations
  24777. * and indexes.
  24778. *
  24779. * @param {Playlist} playlist the playlist to get the list for.
  24780. *
  24781. * @return {Array} The part/segment list.
  24782. */
  24783. var getPartsAndSegments = function getPartsAndSegments(playlist) {
  24784. return (playlist.segments || []).reduce(function (acc, segment, si) {
  24785. if (segment.parts) {
  24786. segment.parts.forEach(function (part, pi) {
  24787. acc.push({
  24788. duration: part.duration,
  24789. segmentIndex: si,
  24790. partIndex: pi,
  24791. part: part,
  24792. segment: segment
  24793. });
  24794. });
  24795. } else {
  24796. acc.push({
  24797. duration: segment.duration,
  24798. segmentIndex: si,
  24799. partIndex: null,
  24800. segment: segment,
  24801. part: null
  24802. });
  24803. }
  24804. return acc;
  24805. }, []);
  24806. };
  24807. var getLastParts = function getLastParts(media) {
  24808. var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  24809. return lastSegment && lastSegment.parts || [];
  24810. };
  24811. var getKnownPartCount = function getKnownPartCount(_ref) {
  24812. var preloadSegment = _ref.preloadSegment;
  24813. if (!preloadSegment) {
  24814. return;
  24815. }
  24816. var parts = preloadSegment.parts,
  24817. preloadHints = preloadSegment.preloadHints;
  24818. var partCount = (preloadHints || []).reduce(function (count, hint) {
  24819. return count + (hint.type === 'PART' ? 1 : 0);
  24820. }, 0);
  24821. partCount += parts && parts.length ? parts.length : 0;
  24822. return partCount;
  24823. };
  24824. /**
  24825. * Get the number of seconds to delay from the end of a
  24826. * live playlist.
  24827. *
  24828. * @param {Playlist} master the master playlist
  24829. * @param {Playlist} media the media playlist
  24830. * @return {number} the hold back in seconds.
  24831. */
  24832. var liveEdgeDelay = function liveEdgeDelay(master, media) {
  24833. if (media.endList) {
  24834. return 0;
  24835. } // dash suggestedPresentationDelay trumps everything
  24836. if (master && master.suggestedPresentationDelay) {
  24837. return master.suggestedPresentationDelay;
  24838. }
  24839. var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  24840. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  24841. return media.serverControl.partHoldBack;
  24842. } else if (hasParts && media.partTargetDuration) {
  24843. return media.partTargetDuration * 3; // finally look for full segment delays
  24844. } else if (media.serverControl && media.serverControl.holdBack) {
  24845. return media.serverControl.holdBack;
  24846. } else if (media.targetDuration) {
  24847. return media.targetDuration * 3;
  24848. }
  24849. return 0;
  24850. };
  24851. /**
  24852. * walk backward until we find a duration we can use
  24853. * or return a failure
  24854. *
  24855. * @param {Playlist} playlist the playlist to walk through
  24856. * @param {Number} endSequence the mediaSequence to stop walking on
  24857. */
  24858. var backwardDuration = function backwardDuration(playlist, endSequence) {
  24859. var result = 0;
  24860. var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  24861. // the interval, use it
  24862. var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  24863. // information that is earlier than endSequence
  24864. if (segment) {
  24865. if (typeof segment.start !== 'undefined') {
  24866. return {
  24867. result: segment.start,
  24868. precise: true
  24869. };
  24870. }
  24871. if (typeof segment.end !== 'undefined') {
  24872. return {
  24873. result: segment.end - segment.duration,
  24874. precise: true
  24875. };
  24876. }
  24877. }
  24878. while (i--) {
  24879. segment = playlist.segments[i];
  24880. if (typeof segment.end !== 'undefined') {
  24881. return {
  24882. result: result + segment.end,
  24883. precise: true
  24884. };
  24885. }
  24886. result += segmentDurationWithParts(playlist, segment);
  24887. if (typeof segment.start !== 'undefined') {
  24888. return {
  24889. result: result + segment.start,
  24890. precise: true
  24891. };
  24892. }
  24893. }
  24894. return {
  24895. result: result,
  24896. precise: false
  24897. };
  24898. };
  24899. /**
  24900. * walk forward until we find a duration we can use
  24901. * or return a failure
  24902. *
  24903. * @param {Playlist} playlist the playlist to walk through
  24904. * @param {number} endSequence the mediaSequence to stop walking on
  24905. */
  24906. var forwardDuration = function forwardDuration(playlist, endSequence) {
  24907. var result = 0;
  24908. var segment;
  24909. var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  24910. // information
  24911. for (; i < playlist.segments.length; i++) {
  24912. segment = playlist.segments[i];
  24913. if (typeof segment.start !== 'undefined') {
  24914. return {
  24915. result: segment.start - result,
  24916. precise: true
  24917. };
  24918. }
  24919. result += segmentDurationWithParts(playlist, segment);
  24920. if (typeof segment.end !== 'undefined') {
  24921. return {
  24922. result: segment.end - result,
  24923. precise: true
  24924. };
  24925. }
  24926. } // indicate we didn't find a useful duration estimate
  24927. return {
  24928. result: -1,
  24929. precise: false
  24930. };
  24931. };
  24932. /**
  24933. * Calculate the media duration from the segments associated with a
  24934. * playlist. The duration of a subinterval of the available segments
  24935. * may be calculated by specifying an end index.
  24936. *
  24937. * @param {Object} playlist a media playlist object
  24938. * @param {number=} endSequence an exclusive upper boundary
  24939. * for the playlist. Defaults to playlist length.
  24940. * @param {number} expired the amount of time that has dropped
  24941. * off the front of the playlist in a live scenario
  24942. * @return {number} the duration between the first available segment
  24943. * and end index.
  24944. */
  24945. var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
  24946. if (typeof endSequence === 'undefined') {
  24947. endSequence = playlist.mediaSequence + playlist.segments.length;
  24948. }
  24949. if (endSequence < playlist.mediaSequence) {
  24950. return 0;
  24951. } // do a backward walk to estimate the duration
  24952. var backward = backwardDuration(playlist, endSequence);
  24953. if (backward.precise) {
  24954. // if we were able to base our duration estimate on timing
  24955. // information provided directly from the Media Source, return
  24956. // it
  24957. return backward.result;
  24958. } // walk forward to see if a precise duration estimate can be made
  24959. // that way
  24960. var forward = forwardDuration(playlist, endSequence);
  24961. if (forward.precise) {
  24962. // we found a segment that has been buffered and so it's
  24963. // position is known precisely
  24964. return forward.result;
  24965. } // return the less-precise, playlist-based duration estimate
  24966. return backward.result + expired;
  24967. };
  24968. /**
  24969. * Calculates the duration of a playlist. If a start and end index
  24970. * are specified, the duration will be for the subset of the media
  24971. * timeline between those two indices. The total duration for live
  24972. * playlists is always Infinity.
  24973. *
  24974. * @param {Object} playlist a media playlist object
  24975. * @param {number=} endSequence an exclusive upper
  24976. * boundary for the playlist. Defaults to the playlist media
  24977. * sequence number plus its length.
  24978. * @param {number=} expired the amount of time that has
  24979. * dropped off the front of the playlist in a live scenario
  24980. * @return {number} the duration between the start index and end
  24981. * index.
  24982. */
  24983. var duration = function duration(playlist, endSequence, expired) {
  24984. if (!playlist) {
  24985. return 0;
  24986. }
  24987. if (typeof expired !== 'number') {
  24988. expired = 0;
  24989. } // if a slice of the total duration is not requested, use
  24990. // playlist-level duration indicators when they're present
  24991. if (typeof endSequence === 'undefined') {
  24992. // if present, use the duration specified in the playlist
  24993. if (playlist.totalDuration) {
  24994. return playlist.totalDuration;
  24995. } // duration should be Infinity for live playlists
  24996. if (!playlist.endList) {
  24997. return window__default['default'].Infinity;
  24998. }
  24999. } // calculate the total duration based on the segment durations
  25000. return intervalDuration(playlist, endSequence, expired);
  25001. };
  25002. /**
  25003. * Calculate the time between two indexes in the current playlist
  25004. * neight the start- nor the end-index need to be within the current
  25005. * playlist in which case, the targetDuration of the playlist is used
  25006. * to approximate the durations of the segments
  25007. *
  25008. * @param {Array} options.durationList list to iterate over for durations.
  25009. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  25010. * @param {number} options.startIndex partsAndSegments index to start
  25011. * @param {number} options.endIndex partsAndSegments index to end.
  25012. * @return {number} the number of seconds between startIndex and endIndex
  25013. */
  25014. var sumDurations = function sumDurations(_ref2) {
  25015. var defaultDuration = _ref2.defaultDuration,
  25016. durationList = _ref2.durationList,
  25017. startIndex = _ref2.startIndex,
  25018. endIndex = _ref2.endIndex;
  25019. var durations = 0;
  25020. if (startIndex > endIndex) {
  25021. var _ref3 = [endIndex, startIndex];
  25022. startIndex = _ref3[0];
  25023. endIndex = _ref3[1];
  25024. }
  25025. if (startIndex < 0) {
  25026. for (var i = startIndex; i < Math.min(0, endIndex); i++) {
  25027. durations += defaultDuration;
  25028. }
  25029. startIndex = 0;
  25030. }
  25031. for (var _i = startIndex; _i < endIndex; _i++) {
  25032. durations += durationList[_i].duration;
  25033. }
  25034. return durations;
  25035. };
  25036. /**
  25037. * Calculates the playlist end time
  25038. *
  25039. * @param {Object} playlist a media playlist object
  25040. * @param {number=} expired the amount of time that has
  25041. * dropped off the front of the playlist in a live scenario
  25042. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  25043. * playlist end calculation should consider the safe live end
  25044. * (truncate the playlist end by three segments). This is normally
  25045. * used for calculating the end of the playlist's seekable range.
  25046. * This takes into account the value of liveEdgePadding.
  25047. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  25048. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  25049. * If this is provided, it is used in the safe live end calculation.
  25050. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  25051. * Corresponds to suggestedPresentationDelay in DASH manifests.
  25052. * @return {number} the end time of playlist
  25053. * @function playlistEnd
  25054. */
  25055. var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  25056. if (!playlist || !playlist.segments) {
  25057. return null;
  25058. }
  25059. if (playlist.endList) {
  25060. return duration(playlist);
  25061. }
  25062. if (expired === null) {
  25063. return null;
  25064. }
  25065. expired = expired || 0;
  25066. var lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  25067. if (useSafeLiveEnd) {
  25068. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  25069. lastSegmentEndTime -= liveEdgePadding;
  25070. } // don't return a time less than zero
  25071. return Math.max(0, lastSegmentEndTime);
  25072. };
  25073. /**
  25074. * Calculates the interval of time that is currently seekable in a
  25075. * playlist. The returned time ranges are relative to the earliest
  25076. * moment in the specified playlist that is still available. A full
  25077. * seekable implementation for live streams would need to offset
  25078. * these values by the duration of content that has expired from the
  25079. * stream.
  25080. *
  25081. * @param {Object} playlist a media playlist object
  25082. * dropped off the front of the playlist in a live scenario
  25083. * @param {number=} expired the amount of time that has
  25084. * dropped off the front of the playlist in a live scenario
  25085. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  25086. * Corresponds to suggestedPresentationDelay in DASH manifests.
  25087. * @return {TimeRanges} the periods of time that are valid targets
  25088. * for seeking
  25089. */
  25090. var seekable = function seekable(playlist, expired, liveEdgePadding) {
  25091. var useSafeLiveEnd = true;
  25092. var seekableStart = expired || 0;
  25093. var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  25094. if (seekableEnd === null) {
  25095. return createTimeRange();
  25096. }
  25097. return createTimeRange(seekableStart, seekableEnd);
  25098. };
  25099. /**
  25100. * Determine the index and estimated starting time of the segment that
  25101. * contains a specified playback position in a media playlist.
  25102. *
  25103. * @param {Object} options.playlist the media playlist to query
  25104. * @param {number} options.currentTime The number of seconds since the earliest
  25105. * possible position to determine the containing segment for
  25106. * @param {number} options.startTime the time when the segment/part starts
  25107. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  25108. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  25109. *
  25110. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  25111. */
  25112. var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
  25113. var playlist = _ref4.playlist,
  25114. currentTime = _ref4.currentTime,
  25115. startingSegmentIndex = _ref4.startingSegmentIndex,
  25116. startingPartIndex = _ref4.startingPartIndex,
  25117. startTime = _ref4.startTime,
  25118. experimentalExactManifestTimings = _ref4.experimentalExactManifestTimings;
  25119. var time = currentTime - startTime;
  25120. var partsAndSegments = getPartsAndSegments(playlist);
  25121. var startIndex = 0;
  25122. for (var i = 0; i < partsAndSegments.length; i++) {
  25123. var partAndSegment = partsAndSegments[i];
  25124. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  25125. continue;
  25126. } // skip this if part index does not match.
  25127. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  25128. continue;
  25129. }
  25130. startIndex = i;
  25131. break;
  25132. }
  25133. if (time < 0) {
  25134. // Walk backward from startIndex in the playlist, adding durations
  25135. // until we find a segment that contains `time` and return it
  25136. if (startIndex > 0) {
  25137. for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
  25138. var _partAndSegment = partsAndSegments[_i2];
  25139. time += _partAndSegment.duration;
  25140. if (experimentalExactManifestTimings) {
  25141. if (time < 0) {
  25142. continue;
  25143. }
  25144. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  25145. continue;
  25146. }
  25147. return {
  25148. partIndex: _partAndSegment.partIndex,
  25149. segmentIndex: _partAndSegment.segmentIndex,
  25150. startTime: startTime - sumDurations({
  25151. defaultDuration: playlist.targetDuration,
  25152. durationList: partsAndSegments,
  25153. startIndex: startIndex,
  25154. endIndex: _i2
  25155. })
  25156. };
  25157. }
  25158. } // We were unable to find a good segment within the playlist
  25159. // so select the first segment
  25160. return {
  25161. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  25162. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  25163. startTime: currentTime
  25164. };
  25165. } // When startIndex is negative, we first walk forward to first segment
  25166. // adding target durations. If we "run out of time" before getting to
  25167. // the first segment, return the first segment
  25168. if (startIndex < 0) {
  25169. for (var _i3 = startIndex; _i3 < 0; _i3++) {
  25170. time -= playlist.targetDuration;
  25171. if (time < 0) {
  25172. return {
  25173. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  25174. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  25175. startTime: currentTime
  25176. };
  25177. }
  25178. }
  25179. startIndex = 0;
  25180. } // Walk forward from startIndex in the playlist, subtracting durations
  25181. // until we find a segment that contains `time` and return it
  25182. for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
  25183. var _partAndSegment2 = partsAndSegments[_i4];
  25184. time -= _partAndSegment2.duration;
  25185. if (experimentalExactManifestTimings) {
  25186. if (time > 0) {
  25187. continue;
  25188. }
  25189. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  25190. continue;
  25191. }
  25192. return {
  25193. partIndex: _partAndSegment2.partIndex,
  25194. segmentIndex: _partAndSegment2.segmentIndex,
  25195. startTime: startTime + sumDurations({
  25196. defaultDuration: playlist.targetDuration,
  25197. durationList: partsAndSegments,
  25198. startIndex: startIndex,
  25199. endIndex: _i4
  25200. })
  25201. };
  25202. } // We are out of possible candidates so load the last one...
  25203. return {
  25204. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  25205. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  25206. startTime: currentTime
  25207. };
  25208. };
  25209. /**
  25210. * Check whether the playlist is blacklisted or not.
  25211. *
  25212. * @param {Object} playlist the media playlist object
  25213. * @return {boolean} whether the playlist is blacklisted or not
  25214. * @function isBlacklisted
  25215. */
  25216. var isBlacklisted = function isBlacklisted(playlist) {
  25217. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  25218. };
  25219. /**
  25220. * Check whether the playlist is compatible with current playback configuration or has
  25221. * been blacklisted permanently for being incompatible.
  25222. *
  25223. * @param {Object} playlist the media playlist object
  25224. * @return {boolean} whether the playlist is incompatible or not
  25225. * @function isIncompatible
  25226. */
  25227. var isIncompatible = function isIncompatible(playlist) {
  25228. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  25229. };
  25230. /**
  25231. * Check whether the playlist is enabled or not.
  25232. *
  25233. * @param {Object} playlist the media playlist object
  25234. * @return {boolean} whether the playlist is enabled or not
  25235. * @function isEnabled
  25236. */
  25237. var isEnabled = function isEnabled(playlist) {
  25238. var blacklisted = isBlacklisted(playlist);
  25239. return !playlist.disabled && !blacklisted;
  25240. };
  25241. /**
  25242. * Check whether the playlist has been manually disabled through the representations api.
  25243. *
  25244. * @param {Object} playlist the media playlist object
  25245. * @return {boolean} whether the playlist is disabled manually or not
  25246. * @function isDisabled
  25247. */
  25248. var isDisabled = function isDisabled(playlist) {
  25249. return playlist.disabled;
  25250. };
  25251. /**
  25252. * Returns whether the current playlist is an AES encrypted HLS stream
  25253. *
  25254. * @return {boolean} true if it's an AES encrypted HLS stream
  25255. */
  25256. var isAes = function isAes(media) {
  25257. for (var i = 0; i < media.segments.length; i++) {
  25258. if (media.segments[i].key) {
  25259. return true;
  25260. }
  25261. }
  25262. return false;
  25263. };
  25264. /**
  25265. * Checks if the playlist has a value for the specified attribute
  25266. *
  25267. * @param {string} attr
  25268. * Attribute to check for
  25269. * @param {Object} playlist
  25270. * The media playlist object
  25271. * @return {boolean}
  25272. * Whether the playlist contains a value for the attribute or not
  25273. * @function hasAttribute
  25274. */
  25275. var hasAttribute = function hasAttribute(attr, playlist) {
  25276. return playlist.attributes && playlist.attributes[attr];
  25277. };
  25278. /**
  25279. * Estimates the time required to complete a segment download from the specified playlist
  25280. *
  25281. * @param {number} segmentDuration
  25282. * Duration of requested segment
  25283. * @param {number} bandwidth
  25284. * Current measured bandwidth of the player
  25285. * @param {Object} playlist
  25286. * The media playlist object
  25287. * @param {number=} bytesReceived
  25288. * Number of bytes already received for the request. Defaults to 0
  25289. * @return {number|NaN}
  25290. * The estimated time to request the segment. NaN if bandwidth information for
  25291. * the given playlist is unavailable
  25292. * @function estimateSegmentRequestTime
  25293. */
  25294. var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
  25295. if (bytesReceived === void 0) {
  25296. bytesReceived = 0;
  25297. }
  25298. if (!hasAttribute('BANDWIDTH', playlist)) {
  25299. return NaN;
  25300. }
  25301. var size = segmentDuration * playlist.attributes.BANDWIDTH;
  25302. return (size - bytesReceived * 8) / bandwidth;
  25303. };
  25304. /*
  25305. * Returns whether the current playlist is the lowest rendition
  25306. *
  25307. * @return {Boolean} true if on lowest rendition
  25308. */
  25309. var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
  25310. if (master.playlists.length === 1) {
  25311. return true;
  25312. }
  25313. var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  25314. return master.playlists.filter(function (playlist) {
  25315. if (!isEnabled(playlist)) {
  25316. return false;
  25317. }
  25318. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  25319. }).length === 0;
  25320. };
  25321. var playlistMatch = function playlistMatch(a, b) {
  25322. // both playlits are null
  25323. // or only one playlist is non-null
  25324. // no match
  25325. if (!a && !b || !a && b || a && !b) {
  25326. return false;
  25327. } // playlist objects are the same, match
  25328. if (a === b) {
  25329. return true;
  25330. } // first try to use id as it should be the most
  25331. // accurate
  25332. if (a.id && b.id && a.id === b.id) {
  25333. return true;
  25334. } // next try to use reslovedUri as it should be the
  25335. // second most accurate.
  25336. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  25337. return true;
  25338. } // finally try to use uri as it should be accurate
  25339. // but might miss a few cases for relative uris
  25340. if (a.uri && b.uri && a.uri === b.uri) {
  25341. return true;
  25342. }
  25343. return false;
  25344. };
  25345. var someAudioVariant = function someAudioVariant(master, callback) {
  25346. var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
  25347. var found = false;
  25348. for (var groupName in AUDIO) {
  25349. for (var label in AUDIO[groupName]) {
  25350. found = callback(AUDIO[groupName][label]);
  25351. if (found) {
  25352. break;
  25353. }
  25354. }
  25355. if (found) {
  25356. break;
  25357. }
  25358. }
  25359. return !!found;
  25360. };
  25361. var isAudioOnly = function isAudioOnly(master) {
  25362. // we are audio only if we have no main playlists but do
  25363. // have media group playlists.
  25364. if (!master || !master.playlists || !master.playlists.length) {
  25365. // without audio variants or playlists this
  25366. // is not an audio only master.
  25367. var found = someAudioVariant(master, function (variant) {
  25368. return variant.playlists && variant.playlists.length || variant.uri;
  25369. });
  25370. return found;
  25371. } // if every playlist has only an audio codec it is audio only
  25372. var _loop = function _loop(i) {
  25373. var playlist = master.playlists[i];
  25374. var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  25375. if (CODECS && CODECS.split(',').every(function (c) {
  25376. return codecs_js.isAudioCodec(c);
  25377. })) {
  25378. return "continue";
  25379. } // playlist is in an audio group it is audio only
  25380. var found = someAudioVariant(master, function (variant) {
  25381. return playlistMatch(playlist, variant);
  25382. });
  25383. if (found) {
  25384. return "continue";
  25385. } // if we make it here this playlist isn't audio and we
  25386. // are not audio only
  25387. return {
  25388. v: false
  25389. };
  25390. };
  25391. for (var i = 0; i < master.playlists.length; i++) {
  25392. var _ret = _loop(i);
  25393. if (_ret === "continue") continue;
  25394. if (typeof _ret === "object") return _ret.v;
  25395. } // if we make it past every playlist without returning, then
  25396. // this is an audio only playlist.
  25397. return true;
  25398. }; // exports
  25399. var Playlist = {
  25400. liveEdgeDelay: liveEdgeDelay,
  25401. duration: duration,
  25402. seekable: seekable,
  25403. getMediaInfoForTime: getMediaInfoForTime,
  25404. isEnabled: isEnabled,
  25405. isDisabled: isDisabled,
  25406. isBlacklisted: isBlacklisted,
  25407. isIncompatible: isIncompatible,
  25408. playlistEnd: playlistEnd,
  25409. isAes: isAes,
  25410. hasAttribute: hasAttribute,
  25411. estimateSegmentRequestTime: estimateSegmentRequestTime,
  25412. isLowestEnabledRendition: isLowestEnabledRendition,
  25413. isAudioOnly: isAudioOnly,
  25414. playlistMatch: playlistMatch,
  25415. segmentDurationWithParts: segmentDurationWithParts
  25416. };
  25417. var log = videojs.log;
  25418. var createPlaylistID = function createPlaylistID(index, uri) {
  25419. return index + "-" + uri;
  25420. }; // default function for creating a group id
  25421. var groupID = function groupID(type, group, label) {
  25422. return "placeholder-uri-" + type + "-" + group + "-" + label;
  25423. };
  25424. /**
  25425. * Parses a given m3u8 playlist
  25426. *
  25427. * @param {Function} [onwarn]
  25428. * a function to call when the parser triggers a warning event.
  25429. * @param {Function} [oninfo]
  25430. * a function to call when the parser triggers an info event.
  25431. * @param {string} manifestString
  25432. * The downloaded manifest string
  25433. * @param {Object[]} [customTagParsers]
  25434. * An array of custom tag parsers for the m3u8-parser instance
  25435. * @param {Object[]} [customTagMappers]
  25436. * An array of custom tag mappers for the m3u8-parser instance
  25437. * @param {boolean} [experimentalLLHLS=false]
  25438. * Whether to keep ll-hls features in the manifest after parsing.
  25439. * @return {Object}
  25440. * The manifest object
  25441. */
  25442. var parseManifest = function parseManifest(_ref) {
  25443. var onwarn = _ref.onwarn,
  25444. oninfo = _ref.oninfo,
  25445. manifestString = _ref.manifestString,
  25446. _ref$customTagParsers = _ref.customTagParsers,
  25447. customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
  25448. _ref$customTagMappers = _ref.customTagMappers,
  25449. customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
  25450. experimentalLLHLS = _ref.experimentalLLHLS;
  25451. var parser = new m3u8Parser.Parser();
  25452. if (onwarn) {
  25453. parser.on('warn', onwarn);
  25454. }
  25455. if (oninfo) {
  25456. parser.on('info', oninfo);
  25457. }
  25458. customTagParsers.forEach(function (customParser) {
  25459. return parser.addParser(customParser);
  25460. });
  25461. customTagMappers.forEach(function (mapper) {
  25462. return parser.addTagMapper(mapper);
  25463. });
  25464. parser.push(manifestString);
  25465. parser.end();
  25466. var manifest = parser.manifest; // remove llhls features from the parsed manifest
  25467. // if we don't want llhls support.
  25468. if (!experimentalLLHLS) {
  25469. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  25470. if (manifest.hasOwnProperty(k)) {
  25471. delete manifest[k];
  25472. }
  25473. });
  25474. if (manifest.segments) {
  25475. manifest.segments.forEach(function (segment) {
  25476. ['parts', 'preloadHints'].forEach(function (k) {
  25477. if (segment.hasOwnProperty(k)) {
  25478. delete segment[k];
  25479. }
  25480. });
  25481. });
  25482. }
  25483. }
  25484. if (!manifest.targetDuration) {
  25485. var targetDuration = 10;
  25486. if (manifest.segments && manifest.segments.length) {
  25487. targetDuration = manifest.segments.reduce(function (acc, s) {
  25488. return Math.max(acc, s.duration);
  25489. }, 0);
  25490. }
  25491. if (onwarn) {
  25492. onwarn("manifest has no targetDuration defaulting to " + targetDuration);
  25493. }
  25494. manifest.targetDuration = targetDuration;
  25495. }
  25496. var parts = getLastParts(manifest);
  25497. if (parts.length && !manifest.partTargetDuration) {
  25498. var partTargetDuration = parts.reduce(function (acc, p) {
  25499. return Math.max(acc, p.duration);
  25500. }, 0);
  25501. if (onwarn) {
  25502. onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
  25503. 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.');
  25504. }
  25505. manifest.partTargetDuration = partTargetDuration;
  25506. }
  25507. return manifest;
  25508. };
  25509. /**
  25510. * Loops through all supported media groups in master and calls the provided
  25511. * callback for each group
  25512. *
  25513. * @param {Object} master
  25514. * The parsed master manifest object
  25515. * @param {Function} callback
  25516. * Callback to call for each media group
  25517. */
  25518. var forEachMediaGroup = function forEachMediaGroup(master, callback) {
  25519. if (!master.mediaGroups) {
  25520. return;
  25521. }
  25522. ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
  25523. if (!master.mediaGroups[mediaType]) {
  25524. return;
  25525. }
  25526. for (var groupKey in master.mediaGroups[mediaType]) {
  25527. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  25528. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  25529. callback(mediaProperties, mediaType, groupKey, labelKey);
  25530. }
  25531. }
  25532. });
  25533. };
  25534. /**
  25535. * Adds properties and attributes to the playlist to keep consistent functionality for
  25536. * playlists throughout VHS.
  25537. *
  25538. * @param {Object} config
  25539. * Arguments object
  25540. * @param {Object} config.playlist
  25541. * The media playlist
  25542. * @param {string} [config.uri]
  25543. * The uri to the media playlist (if media playlist is not from within a master
  25544. * playlist)
  25545. * @param {string} id
  25546. * ID to use for the playlist
  25547. */
  25548. var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
  25549. var playlist = _ref2.playlist,
  25550. uri = _ref2.uri,
  25551. id = _ref2.id;
  25552. playlist.id = id;
  25553. playlist.playlistErrors_ = 0;
  25554. if (uri) {
  25555. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  25556. // playlists do not contain their own source URI, but one is needed for consistency in
  25557. // VHS.
  25558. playlist.uri = uri;
  25559. } // For HLS master playlists, even though certain attributes MUST be defined, the
  25560. // stream may still be played without them.
  25561. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  25562. // manifest.
  25563. //
  25564. // To avoid undefined reference errors through the project, and make the code easier
  25565. // to write/read, add an empty attributes object for these cases.
  25566. playlist.attributes = playlist.attributes || {};
  25567. };
  25568. /**
  25569. * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
  25570. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  25571. * playlist references to the playlists array.
  25572. *
  25573. * @param {Object} master
  25574. * The master playlist
  25575. */
  25576. var setupMediaPlaylists = function setupMediaPlaylists(master) {
  25577. var i = master.playlists.length;
  25578. while (i--) {
  25579. var playlist = master.playlists[i];
  25580. setupMediaPlaylist({
  25581. playlist: playlist,
  25582. id: createPlaylistID(i, playlist.uri)
  25583. });
  25584. playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
  25585. master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  25586. master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  25587. // the stream can be played without it. Although an attributes property may have been
  25588. // added to the playlist to prevent undefined references, issue a warning to fix the
  25589. // manifest.
  25590. if (!playlist.attributes.BANDWIDTH) {
  25591. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  25592. }
  25593. }
  25594. };
  25595. /**
  25596. * Adds resolvedUri properties to each media group.
  25597. *
  25598. * @param {Object} master
  25599. * The master playlist
  25600. */
  25601. var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
  25602. forEachMediaGroup(master, function (properties) {
  25603. if (properties.uri) {
  25604. properties.resolvedUri = resolveUrl(master.uri, properties.uri);
  25605. }
  25606. });
  25607. };
  25608. /**
  25609. * Creates a master playlist wrapper to insert a sole media playlist into.
  25610. *
  25611. * @param {Object} media
  25612. * Media playlist
  25613. * @param {string} uri
  25614. * The media URI
  25615. *
  25616. * @return {Object}
  25617. * Master playlist
  25618. */
  25619. var masterForMedia = function masterForMedia(media, uri) {
  25620. var id = createPlaylistID(0, uri);
  25621. var master = {
  25622. mediaGroups: {
  25623. 'AUDIO': {},
  25624. 'VIDEO': {},
  25625. 'CLOSED-CAPTIONS': {},
  25626. 'SUBTITLES': {}
  25627. },
  25628. uri: window__default['default'].location.href,
  25629. resolvedUri: window__default['default'].location.href,
  25630. playlists: [{
  25631. uri: uri,
  25632. id: id,
  25633. resolvedUri: uri,
  25634. // m3u8-parser does not attach an attributes property to media playlists so make
  25635. // sure that the property is attached to avoid undefined reference errors
  25636. attributes: {}
  25637. }]
  25638. }; // set up ID reference
  25639. master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
  25640. master.playlists[uri] = master.playlists[0];
  25641. return master;
  25642. };
  25643. /**
  25644. * Does an in-place update of the master manifest to add updated playlist URI references
  25645. * as well as other properties needed by VHS that aren't included by the parser.
  25646. *
  25647. * @param {Object} master
  25648. * Master manifest object
  25649. * @param {string} uri
  25650. * The source URI
  25651. * @param {function} createGroupID
  25652. * A function to determine how to create the groupID for mediaGroups
  25653. */
  25654. var addPropertiesToMaster = function addPropertiesToMaster(master, uri, createGroupID) {
  25655. if (createGroupID === void 0) {
  25656. createGroupID = groupID;
  25657. }
  25658. master.uri = uri;
  25659. for (var i = 0; i < master.playlists.length; i++) {
  25660. if (!master.playlists[i].uri) {
  25661. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  25662. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  25663. // TODO: consider adding dummy URIs in mpd-parser
  25664. var phonyUri = "placeholder-uri-" + i;
  25665. master.playlists[i].uri = phonyUri;
  25666. }
  25667. }
  25668. var audioOnlyMaster = isAudioOnly(master);
  25669. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  25670. // add a playlist array under properties
  25671. if (!properties.playlists || !properties.playlists.length) {
  25672. // If the manifest is audio only and this media group does not have a uri, check
  25673. // if the media group is located in the main list of playlists. If it is, don't add
  25674. // placeholder properties as it shouldn't be considered an alternate audio track.
  25675. if (audioOnlyMaster && mediaType === 'AUDIO' && !properties.uri) {
  25676. for (var _i = 0; _i < master.playlists.length; _i++) {
  25677. var p = master.playlists[_i];
  25678. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  25679. return;
  25680. }
  25681. }
  25682. }
  25683. properties.playlists = [_extends__default['default']({}, properties)];
  25684. }
  25685. properties.playlists.forEach(function (p, i) {
  25686. var groupId = createGroupID(mediaType, groupKey, labelKey, p);
  25687. var id = createPlaylistID(i, groupId);
  25688. if (p.uri) {
  25689. p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
  25690. } else {
  25691. // DEPRECATED, this has been added to prevent a breaking change.
  25692. // previously we only ever had a single media group playlist, so
  25693. // we mark the first playlist uri without prepending the index as we used to
  25694. // ideally we would do all of the playlists the same way.
  25695. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  25696. // the placeholder again
  25697. p.resolvedUri = p.uri;
  25698. }
  25699. p.id = p.id || id; // add an empty attributes object, all playlists are
  25700. // expected to have this.
  25701. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  25702. master.playlists[p.id] = p;
  25703. master.playlists[p.uri] = p;
  25704. });
  25705. });
  25706. setupMediaPlaylists(master);
  25707. resolveMediaGroupUris(master);
  25708. };
  25709. var mergeOptions$2 = videojs.mergeOptions,
  25710. EventTarget$1 = videojs.EventTarget;
  25711. var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
  25712. if (media.endList || !media.serverControl) {
  25713. return uri;
  25714. }
  25715. var parameters = {};
  25716. if (media.serverControl.canBlockReload) {
  25717. var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
  25718. var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  25719. // that we are going to request a part of that preload segment.
  25720. // the logic below is used to determine that.
  25721. if (preloadSegment) {
  25722. var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  25723. var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  25724. // length of parts, then we know we had part preload hints
  25725. // and we need to add the _HLS_part= query
  25726. if (nextPart > -1 && nextPart !== parts.length - 1) {
  25727. // add existing parts to our preload hints
  25728. // eslint-disable-next-line
  25729. parameters._HLS_part = nextPart;
  25730. } // this if statement makes sure that we request the msn
  25731. // of the preload segment if:
  25732. // 1. the preload segment had parts (and was not yet a full segment)
  25733. // but was added to our segments array
  25734. // 2. the preload segment had preload hints for parts that are not in
  25735. // the manifest yet.
  25736. // in all other cases we want the segment after the preload segment
  25737. // which will be given by using media.segments.length because it is 1 based
  25738. // rather than 0 based.
  25739. if (nextPart > -1 || parts.length) {
  25740. nextMSN--;
  25741. }
  25742. } // add _HLS_msn= in front of any _HLS_part query
  25743. // eslint-disable-next-line
  25744. parameters._HLS_msn = nextMSN;
  25745. }
  25746. if (media.serverControl && media.serverControl.canSkipUntil) {
  25747. // add _HLS_skip= infront of all other queries.
  25748. // eslint-disable-next-line
  25749. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  25750. }
  25751. if (Object.keys(parameters).length) {
  25752. var parsedUri = new window__default['default'].URL(uri);
  25753. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  25754. if (!parameters.hasOwnProperty(name)) {
  25755. return;
  25756. }
  25757. parsedUri.searchParams.set(name, parameters[name]);
  25758. });
  25759. uri = parsedUri.toString();
  25760. }
  25761. return uri;
  25762. };
  25763. /**
  25764. * Returns a new segment object with properties and
  25765. * the parts array merged.
  25766. *
  25767. * @param {Object} a the old segment
  25768. * @param {Object} b the new segment
  25769. *
  25770. * @return {Object} the merged segment
  25771. */
  25772. var updateSegment = function updateSegment(a, b) {
  25773. if (!a) {
  25774. return b;
  25775. }
  25776. var result = mergeOptions$2(a, b); // if only the old segment has preload hints
  25777. // and the new one does not, remove preload hints.
  25778. if (a.preloadHints && !b.preloadHints) {
  25779. delete result.preloadHints;
  25780. } // if only the old segment has parts
  25781. // then the parts are no longer valid
  25782. if (a.parts && !b.parts) {
  25783. delete result.parts; // if both segments have parts
  25784. // copy part propeties from the old segment
  25785. // to the new one.
  25786. } else if (a.parts && b.parts) {
  25787. for (var i = 0; i < b.parts.length; i++) {
  25788. if (a.parts && a.parts[i]) {
  25789. result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
  25790. }
  25791. }
  25792. } // set skipped to false for segments that have
  25793. // have had information merged from the old segment.
  25794. if (!a.skipped && b.skipped) {
  25795. result.skipped = false;
  25796. } // set preload to false for segments that have
  25797. // had information added in the new segment.
  25798. if (a.preload && !b.preload) {
  25799. result.preload = false;
  25800. }
  25801. return result;
  25802. };
  25803. /**
  25804. * Returns a new array of segments that is the result of merging
  25805. * properties from an older list of segments onto an updated
  25806. * list. No properties on the updated playlist will be ovewritten.
  25807. *
  25808. * @param {Array} original the outdated list of segments
  25809. * @param {Array} update the updated list of segments
  25810. * @param {number=} offset the index of the first update
  25811. * segment in the original segment list. For non-live playlists,
  25812. * this should always be zero and does not need to be
  25813. * specified. For live playlists, it should be the difference
  25814. * between the media sequence numbers in the original and updated
  25815. * playlists.
  25816. * @return {Array} a list of merged segment objects
  25817. */
  25818. var updateSegments = function updateSegments(original, update, offset) {
  25819. var oldSegments = original.slice();
  25820. var newSegments = update.slice();
  25821. offset = offset || 0;
  25822. var result = [];
  25823. var currentMap;
  25824. for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
  25825. var oldSegment = oldSegments[newIndex + offset];
  25826. var newSegment = newSegments[newIndex];
  25827. if (oldSegment) {
  25828. currentMap = oldSegment.map || currentMap;
  25829. result.push(updateSegment(oldSegment, newSegment));
  25830. } else {
  25831. // carry over map to new segment if it is missing
  25832. if (currentMap && !newSegment.map) {
  25833. newSegment.map = currentMap;
  25834. }
  25835. result.push(newSegment);
  25836. }
  25837. }
  25838. return result;
  25839. };
  25840. var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
  25841. // preloadSegment will not have a uri at all
  25842. // as the segment isn't actually in the manifest yet, only parts
  25843. if (!segment.resolvedUri && segment.uri) {
  25844. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  25845. }
  25846. if (segment.key && !segment.key.resolvedUri) {
  25847. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  25848. }
  25849. if (segment.map && !segment.map.resolvedUri) {
  25850. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  25851. }
  25852. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  25853. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  25854. }
  25855. if (segment.parts && segment.parts.length) {
  25856. segment.parts.forEach(function (p) {
  25857. if (p.resolvedUri) {
  25858. return;
  25859. }
  25860. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25861. });
  25862. }
  25863. if (segment.preloadHints && segment.preloadHints.length) {
  25864. segment.preloadHints.forEach(function (p) {
  25865. if (p.resolvedUri) {
  25866. return;
  25867. }
  25868. p.resolvedUri = resolveUrl(baseUri, p.uri);
  25869. });
  25870. }
  25871. };
  25872. var getAllSegments = function getAllSegments(media) {
  25873. var segments = media.segments || [];
  25874. var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  25875. // a usable segment, only include a preloadSegment that has
  25876. // parts.
  25877. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  25878. // if preloadHints has a MAP that means that the
  25879. // init segment is going to change. We cannot use any of the parts
  25880. // from this preload segment.
  25881. if (preloadSegment.preloadHints) {
  25882. for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
  25883. if (preloadSegment.preloadHints[i].type === 'MAP') {
  25884. return segments;
  25885. }
  25886. }
  25887. } // set the duration for our preload segment to target duration.
  25888. preloadSegment.duration = media.targetDuration;
  25889. preloadSegment.preload = true;
  25890. segments.push(preloadSegment);
  25891. }
  25892. return segments;
  25893. }; // consider the playlist unchanged if the playlist object is the same or
  25894. // the number of segments is equal, the media sequence number is unchanged,
  25895. // and this playlist hasn't become the end of the playlist
  25896. var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
  25897. return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
  25898. };
  25899. /**
  25900. * Returns a new master playlist that is the result of merging an
  25901. * updated media playlist into the original version. If the
  25902. * updated media playlist does not match any of the playlist
  25903. * entries in the original master playlist, null is returned.
  25904. *
  25905. * @param {Object} master a parsed master M3U8 object
  25906. * @param {Object} media a parsed media M3U8 object
  25907. * @return {Object} a new object that represents the original
  25908. * master playlist with the updated media playlist merged in, or
  25909. * null if the merge produced no change.
  25910. */
  25911. var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
  25912. if (unchangedCheck === void 0) {
  25913. unchangedCheck = isPlaylistUnchanged;
  25914. }
  25915. var result = mergeOptions$2(master, {});
  25916. var oldMedia = result.playlists[newMedia.id];
  25917. if (!oldMedia) {
  25918. return null;
  25919. }
  25920. if (unchangedCheck(oldMedia, newMedia)) {
  25921. return null;
  25922. }
  25923. newMedia.segments = getAllSegments(newMedia);
  25924. var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
  25925. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  25926. delete mergedPlaylist.preloadSegment;
  25927. } // if the update could overlap existing segment information, merge the two segment lists
  25928. if (oldMedia.segments) {
  25929. if (newMedia.skip) {
  25930. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  25931. // old properties into the new segments
  25932. for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
  25933. newMedia.segments.unshift({
  25934. skipped: true
  25935. });
  25936. }
  25937. }
  25938. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  25939. } // resolve any segment URIs to prevent us from having to do it later
  25940. mergedPlaylist.segments.forEach(function (segment) {
  25941. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  25942. }); // TODO Right now in the playlists array there are two references to each playlist, one
  25943. // that is referenced by index, and one by URI. The index reference may no longer be
  25944. // necessary.
  25945. for (var _i = 0; _i < result.playlists.length; _i++) {
  25946. if (result.playlists[_i].id === newMedia.id) {
  25947. result.playlists[_i] = mergedPlaylist;
  25948. }
  25949. }
  25950. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  25951. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  25952. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  25953. if (!properties.playlists) {
  25954. return;
  25955. }
  25956. for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
  25957. if (newMedia.id === properties.playlists[_i2].id) {
  25958. properties.playlists[_i2] = mergedPlaylist;
  25959. }
  25960. }
  25961. });
  25962. return result;
  25963. };
  25964. /**
  25965. * Calculates the time to wait before refreshing a live playlist
  25966. *
  25967. * @param {Object} media
  25968. * The current media
  25969. * @param {boolean} update
  25970. * True if there were any updates from the last refresh, false otherwise
  25971. * @return {number}
  25972. * The time in ms to wait before refreshing the live playlist
  25973. */
  25974. var refreshDelay = function refreshDelay(media, update) {
  25975. var segments = media.segments || [];
  25976. var lastSegment = segments[segments.length - 1];
  25977. var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  25978. var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  25979. if (update && lastDuration) {
  25980. return lastDuration * 1000;
  25981. } // if the playlist is unchanged since the last reload or last segment duration
  25982. // cannot be determined, try again after half the target duration
  25983. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  25984. };
  25985. /**
  25986. * Load a playlist from a remote location
  25987. *
  25988. * @class PlaylistLoader
  25989. * @extends Stream
  25990. * @param {string|Object} src url or object of manifest
  25991. * @param {boolean} withCredentials the withCredentials xhr option
  25992. * @class
  25993. */
  25994. var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  25995. _inheritsLoose__default['default'](PlaylistLoader, _EventTarget);
  25996. function PlaylistLoader(src, vhs, options) {
  25997. var _this;
  25998. if (options === void 0) {
  25999. options = {};
  26000. }
  26001. _this = _EventTarget.call(this) || this;
  26002. if (!src) {
  26003. throw new Error('A non-empty playlist URL or object is required');
  26004. }
  26005. _this.logger_ = logger('PlaylistLoader');
  26006. var _options = options,
  26007. _options$withCredenti = _options.withCredentials,
  26008. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  26009. _options$handleManife = _options.handleManifestRedirects,
  26010. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  26011. _this.src = src;
  26012. _this.vhs_ = vhs;
  26013. _this.withCredentials = withCredentials;
  26014. _this.handleManifestRedirects = handleManifestRedirects;
  26015. var vhsOptions = vhs.options_;
  26016. _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  26017. _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  26018. _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // force experimentalLLHLS for IE 11
  26019. if (videojs.browser.IE_VERSION) {
  26020. _this.experimentalLLHLS = false;
  26021. } // initialize the loader state
  26022. _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  26023. _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(_assertThisInitialized__default['default'](_this));
  26024. _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
  26025. return _this;
  26026. }
  26027. var _proto = PlaylistLoader.prototype;
  26028. _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
  26029. var _this2 = this;
  26030. if (this.state !== 'HAVE_METADATA') {
  26031. // only refresh the media playlist if no other activity is going on
  26032. return;
  26033. }
  26034. var media = this.media();
  26035. var uri = resolveUrl(this.master.uri, media.uri);
  26036. if (this.experimentalLLHLS) {
  26037. uri = addLLHLSQueryDirectives(uri, media);
  26038. }
  26039. this.state = 'HAVE_CURRENT_METADATA';
  26040. this.request = this.vhs_.xhr({
  26041. uri: uri,
  26042. withCredentials: this.withCredentials
  26043. }, function (error, req) {
  26044. // disposed
  26045. if (!_this2.request) {
  26046. return;
  26047. }
  26048. if (error) {
  26049. return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
  26050. }
  26051. _this2.haveMetadata({
  26052. playlistString: _this2.request.responseText,
  26053. url: _this2.media().uri,
  26054. id: _this2.media().id
  26055. });
  26056. });
  26057. };
  26058. _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
  26059. var uri = playlist.uri,
  26060. id = playlist.id; // any in-flight request is now finished
  26061. this.request = null;
  26062. if (startingState) {
  26063. this.state = startingState;
  26064. }
  26065. this.error = {
  26066. playlist: this.master.playlists[id],
  26067. status: xhr.status,
  26068. message: "HLS playlist request error at URL: " + uri + ".",
  26069. responseText: xhr.responseText,
  26070. code: xhr.status >= 500 ? 4 : 2
  26071. };
  26072. this.trigger('error');
  26073. };
  26074. _proto.parseManifest_ = function parseManifest_(_ref) {
  26075. var _this3 = this;
  26076. var url = _ref.url,
  26077. manifestString = _ref.manifestString;
  26078. return parseManifest({
  26079. onwarn: function onwarn(_ref2) {
  26080. var message = _ref2.message;
  26081. return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
  26082. },
  26083. oninfo: function oninfo(_ref3) {
  26084. var message = _ref3.message;
  26085. return _this3.logger_("m3u8-parser info for " + url + ": " + message);
  26086. },
  26087. manifestString: manifestString,
  26088. customTagParsers: this.customTagParsers,
  26089. customTagMappers: this.customTagMappers,
  26090. experimentalLLHLS: this.experimentalLLHLS
  26091. });
  26092. }
  26093. /**
  26094. * Update the playlist loader's state in response to a new or updated playlist.
  26095. *
  26096. * @param {string} [playlistString]
  26097. * Playlist string (if playlistObject is not provided)
  26098. * @param {Object} [playlistObject]
  26099. * Playlist object (if playlistString is not provided)
  26100. * @param {string} url
  26101. * URL of playlist
  26102. * @param {string} id
  26103. * ID to use for playlist
  26104. */
  26105. ;
  26106. _proto.haveMetadata = function haveMetadata(_ref4) {
  26107. var playlistString = _ref4.playlistString,
  26108. playlistObject = _ref4.playlistObject,
  26109. url = _ref4.url,
  26110. id = _ref4.id; // any in-flight request is now finished
  26111. this.request = null;
  26112. this.state = 'HAVE_METADATA';
  26113. var playlist = playlistObject || this.parseManifest_({
  26114. url: url,
  26115. manifestString: playlistString
  26116. });
  26117. playlist.lastRequest = Date.now();
  26118. setupMediaPlaylist({
  26119. playlist: playlist,
  26120. uri: url,
  26121. id: id
  26122. }); // merge this playlist into the master
  26123. var update = updateMaster$1(this.master, playlist);
  26124. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  26125. this.pendingMedia_ = null;
  26126. if (update) {
  26127. this.master = update;
  26128. this.media_ = this.master.playlists[id];
  26129. } else {
  26130. this.trigger('playlistunchanged');
  26131. }
  26132. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  26133. this.trigger('loadedplaylist');
  26134. }
  26135. /**
  26136. * Abort any outstanding work and clean up.
  26137. */
  26138. ;
  26139. _proto.dispose = function dispose() {
  26140. this.trigger('dispose');
  26141. this.stopRequest();
  26142. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  26143. window__default['default'].clearTimeout(this.finalRenditionTimeout);
  26144. this.off();
  26145. };
  26146. _proto.stopRequest = function stopRequest() {
  26147. if (this.request) {
  26148. var oldRequest = this.request;
  26149. this.request = null;
  26150. oldRequest.onreadystatechange = null;
  26151. oldRequest.abort();
  26152. }
  26153. }
  26154. /**
  26155. * When called without any arguments, returns the currently
  26156. * active media playlist. When called with a single argument,
  26157. * triggers the playlist loader to asynchronously switch to the
  26158. * specified media playlist. Calling this method while the
  26159. * loader is in the HAVE_NOTHING causes an error to be emitted
  26160. * but otherwise has no effect.
  26161. *
  26162. * @param {Object=} playlist the parsed media playlist
  26163. * object to switch to
  26164. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  26165. *
  26166. * @return {Playlist} the current loaded media
  26167. */
  26168. ;
  26169. _proto.media = function media(playlist, shouldDelay) {
  26170. var _this4 = this; // getter
  26171. if (!playlist) {
  26172. return this.media_;
  26173. } // setter
  26174. if (this.state === 'HAVE_NOTHING') {
  26175. throw new Error('Cannot switch media playlist from ' + this.state);
  26176. } // find the playlist object if the target playlist has been
  26177. // specified by URI
  26178. if (typeof playlist === 'string') {
  26179. if (!this.master.playlists[playlist]) {
  26180. throw new Error('Unknown playlist URI: ' + playlist);
  26181. }
  26182. playlist = this.master.playlists[playlist];
  26183. }
  26184. window__default['default'].clearTimeout(this.finalRenditionTimeout);
  26185. if (shouldDelay) {
  26186. var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  26187. this.finalRenditionTimeout = window__default['default'].setTimeout(this.media.bind(this, playlist, false), delay);
  26188. return;
  26189. }
  26190. var startingState = this.state;
  26191. var mediaChange = !this.media_ || playlist.id !== this.media_.id;
  26192. var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
  26193. if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  26194. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  26195. playlist.endList && playlist.segments.length) {
  26196. // abort outstanding playlist requests
  26197. if (this.request) {
  26198. this.request.onreadystatechange = null;
  26199. this.request.abort();
  26200. this.request = null;
  26201. }
  26202. this.state = 'HAVE_METADATA';
  26203. this.media_ = playlist; // trigger media change if the active media has been updated
  26204. if (mediaChange) {
  26205. this.trigger('mediachanging');
  26206. if (startingState === 'HAVE_MASTER') {
  26207. // The initial playlist was a master manifest, and the first media selected was
  26208. // also provided (in the form of a resolved playlist object) as part of the
  26209. // source object (rather than just a URL). Therefore, since the media playlist
  26210. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  26211. // normal flow, and needs an explicit trigger here.
  26212. this.trigger('loadedmetadata');
  26213. } else {
  26214. this.trigger('mediachange');
  26215. }
  26216. }
  26217. return;
  26218. } // We update/set the timeout here so that live playlists
  26219. // that are not a media change will "start" the loader as expected.
  26220. // We expect that this function will start the media update timeout
  26221. // cycle again. This also prevents a playlist switch failure from
  26222. // causing us to stall during live.
  26223. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  26224. if (!mediaChange) {
  26225. return;
  26226. }
  26227. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  26228. if (this.request) {
  26229. if (playlist.resolvedUri === this.request.url) {
  26230. // requesting to switch to the same playlist multiple times
  26231. // has no effect after the first
  26232. return;
  26233. }
  26234. this.request.onreadystatechange = null;
  26235. this.request.abort();
  26236. this.request = null;
  26237. } // request the new playlist
  26238. if (this.media_) {
  26239. this.trigger('mediachanging');
  26240. }
  26241. this.pendingMedia_ = playlist;
  26242. this.request = this.vhs_.xhr({
  26243. uri: playlist.resolvedUri,
  26244. withCredentials: this.withCredentials
  26245. }, function (error, req) {
  26246. // disposed
  26247. if (!_this4.request) {
  26248. return;
  26249. }
  26250. playlist.lastRequest = Date.now();
  26251. playlist.resolvedUri = resolveManifestRedirect(_this4.handleManifestRedirects, playlist.resolvedUri, req);
  26252. if (error) {
  26253. return _this4.playlistRequestError(_this4.request, playlist, startingState);
  26254. }
  26255. _this4.haveMetadata({
  26256. playlistString: req.responseText,
  26257. url: playlist.uri,
  26258. id: playlist.id
  26259. }); // fire loadedmetadata the first time a media playlist is loaded
  26260. if (startingState === 'HAVE_MASTER') {
  26261. _this4.trigger('loadedmetadata');
  26262. } else {
  26263. _this4.trigger('mediachange');
  26264. }
  26265. });
  26266. }
  26267. /**
  26268. * pause loading of the playlist
  26269. */
  26270. ;
  26271. _proto.pause = function pause() {
  26272. if (this.mediaUpdateTimeout) {
  26273. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  26274. this.mediaUpdateTimeout = null;
  26275. }
  26276. this.stopRequest();
  26277. if (this.state === 'HAVE_NOTHING') {
  26278. // If we pause the loader before any data has been retrieved, its as if we never
  26279. // started, so reset to an unstarted state.
  26280. this.started = false;
  26281. } // Need to restore state now that no activity is happening
  26282. if (this.state === 'SWITCHING_MEDIA') {
  26283. // if the loader was in the process of switching media, it should either return to
  26284. // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
  26285. // playlist yet. This is determined by the existence of loader.media_
  26286. if (this.media_) {
  26287. this.state = 'HAVE_METADATA';
  26288. } else {
  26289. this.state = 'HAVE_MASTER';
  26290. }
  26291. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  26292. this.state = 'HAVE_METADATA';
  26293. }
  26294. }
  26295. /**
  26296. * start loading of the playlist
  26297. */
  26298. ;
  26299. _proto.load = function load(shouldDelay) {
  26300. var _this5 = this;
  26301. if (this.mediaUpdateTimeout) {
  26302. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  26303. this.mediaUpdateTimeout = null;
  26304. }
  26305. var media = this.media();
  26306. if (shouldDelay) {
  26307. var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  26308. this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
  26309. _this5.mediaUpdateTimeout = null;
  26310. _this5.load();
  26311. }, delay);
  26312. return;
  26313. }
  26314. if (!this.started) {
  26315. this.start();
  26316. return;
  26317. }
  26318. if (media && !media.endList) {
  26319. this.trigger('mediaupdatetimeout');
  26320. } else {
  26321. this.trigger('loadedplaylist');
  26322. }
  26323. };
  26324. _proto.updateMediaUpdateTimeout_ = function updateMediaUpdateTimeout_(delay) {
  26325. var _this6 = this;
  26326. if (this.mediaUpdateTimeout) {
  26327. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  26328. this.mediaUpdateTimeout = null;
  26329. } // we only have use mediaupdatetimeout for live playlists.
  26330. if (!this.media() || this.media().endList) {
  26331. return;
  26332. }
  26333. this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
  26334. _this6.mediaUpdateTimeout = null;
  26335. _this6.trigger('mediaupdatetimeout');
  26336. _this6.updateMediaUpdateTimeout_(delay);
  26337. }, delay);
  26338. }
  26339. /**
  26340. * start loading of the playlist
  26341. */
  26342. ;
  26343. _proto.start = function start() {
  26344. var _this7 = this;
  26345. this.started = true;
  26346. if (typeof this.src === 'object') {
  26347. // in the case of an entirely constructed manifest object (meaning there's no actual
  26348. // manifest on a server), default the uri to the page's href
  26349. if (!this.src.uri) {
  26350. this.src.uri = window__default['default'].location.href;
  26351. } // resolvedUri is added on internally after the initial request. Since there's no
  26352. // request for pre-resolved manifests, add on resolvedUri here.
  26353. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  26354. // request can be skipped (since the top level of the manifest, at a minimum, is
  26355. // already available as a parsed manifest object). However, if the manifest object
  26356. // represents a master playlist, some media playlists may need to be resolved before
  26357. // the starting segment list is available. Therefore, go directly to setup of the
  26358. // initial playlist, and let the normal flow continue from there.
  26359. //
  26360. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  26361. // that the first request is asynchronous.
  26362. setTimeout(function () {
  26363. _this7.setupInitialPlaylist(_this7.src);
  26364. }, 0);
  26365. return;
  26366. } // request the specified URL
  26367. this.request = this.vhs_.xhr({
  26368. uri: this.src,
  26369. withCredentials: this.withCredentials
  26370. }, function (error, req) {
  26371. // disposed
  26372. if (!_this7.request) {
  26373. return;
  26374. } // clear the loader's request reference
  26375. _this7.request = null;
  26376. if (error) {
  26377. _this7.error = {
  26378. status: req.status,
  26379. message: "HLS playlist request error at URL: " + _this7.src + ".",
  26380. responseText: req.responseText,
  26381. // MEDIA_ERR_NETWORK
  26382. code: 2
  26383. };
  26384. if (_this7.state === 'HAVE_NOTHING') {
  26385. _this7.started = false;
  26386. }
  26387. return _this7.trigger('error');
  26388. }
  26389. _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
  26390. var manifest = _this7.parseManifest_({
  26391. manifestString: req.responseText,
  26392. url: _this7.src
  26393. });
  26394. _this7.setupInitialPlaylist(manifest);
  26395. });
  26396. };
  26397. _proto.srcUri = function srcUri() {
  26398. return typeof this.src === 'string' ? this.src : this.src.uri;
  26399. }
  26400. /**
  26401. * Given a manifest object that's either a master or media playlist, trigger the proper
  26402. * events and set the state of the playlist loader.
  26403. *
  26404. * If the manifest object represents a master playlist, `loadedplaylist` will be
  26405. * triggered to allow listeners to select a playlist. If none is selected, the loader
  26406. * will default to the first one in the playlists array.
  26407. *
  26408. * If the manifest object represents a media playlist, `loadedplaylist` will be
  26409. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  26410. *
  26411. * In the case of a media playlist, a master playlist object wrapper with one playlist
  26412. * will be created so that all logic can handle playlists in the same fashion (as an
  26413. * assumed manifest object schema).
  26414. *
  26415. * @param {Object} manifest
  26416. * The parsed manifest object
  26417. */
  26418. ;
  26419. _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
  26420. this.state = 'HAVE_MASTER';
  26421. if (manifest.playlists) {
  26422. this.master = manifest;
  26423. addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
  26424. // then resolve URIs in advance, as they are usually done after a playlist request,
  26425. // which may not happen if the playlist is resolved.
  26426. manifest.playlists.forEach(function (playlist) {
  26427. playlist.segments = getAllSegments(playlist);
  26428. playlist.segments.forEach(function (segment) {
  26429. resolveSegmentUris(segment, playlist.resolvedUri);
  26430. });
  26431. });
  26432. this.trigger('loadedplaylist');
  26433. if (!this.request) {
  26434. // no media playlist was specifically selected so start
  26435. // from the first listed one
  26436. this.media(this.master.playlists[0]);
  26437. }
  26438. return;
  26439. } // In order to support media playlists passed in as vhs-json, the case where the uri
  26440. // is not provided as part of the manifest should be considered, and an appropriate
  26441. // default used.
  26442. var uri = this.srcUri() || window__default['default'].location.href;
  26443. this.master = masterForMedia(manifest, uri);
  26444. this.haveMetadata({
  26445. playlistObject: manifest,
  26446. url: uri,
  26447. id: this.master.playlists[0].id
  26448. });
  26449. this.trigger('loadedmetadata');
  26450. };
  26451. return PlaylistLoader;
  26452. }(EventTarget$1);
  26453. /**
  26454. * @file xhr.js
  26455. */
  26456. var videojsXHR = videojs.xhr,
  26457. mergeOptions$1 = videojs.mergeOptions;
  26458. var callbackWrapper = function callbackWrapper(request, error, response, callback) {
  26459. var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  26460. if (!error && reqResponse) {
  26461. request.responseTime = Date.now();
  26462. request.roundTripTime = request.responseTime - request.requestTime;
  26463. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  26464. if (!request.bandwidth) {
  26465. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  26466. }
  26467. }
  26468. if (response.headers) {
  26469. request.responseHeaders = response.headers;
  26470. } // videojs.xhr now uses a specific code on the error
  26471. // object to signal that a request has timed out instead
  26472. // of setting a boolean on the request object
  26473. if (error && error.code === 'ETIMEDOUT') {
  26474. request.timedout = true;
  26475. } // videojs.xhr no longer considers status codes outside of 200 and 0
  26476. // (for file uris) to be errors, but the old XHR did, so emulate that
  26477. // behavior. Status 206 may be used in response to byterange requests.
  26478. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  26479. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  26480. }
  26481. callback(error, request);
  26482. };
  26483. var xhrFactory = function xhrFactory() {
  26484. var xhr = function XhrFunction(options, callback) {
  26485. // Add a default timeout
  26486. options = mergeOptions$1({
  26487. timeout: 45e3
  26488. }, options); // Allow an optional user-specified function to modify the option
  26489. // object before we construct the xhr request
  26490. var beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  26491. if (beforeRequest && typeof beforeRequest === 'function') {
  26492. var newOptions = beforeRequest(options);
  26493. if (newOptions) {
  26494. options = newOptions;
  26495. }
  26496. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  26497. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  26498. var xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  26499. var request = xhrMethod(options, function (error, response) {
  26500. return callbackWrapper(request, error, response, callback);
  26501. });
  26502. var originalAbort = request.abort;
  26503. request.abort = function () {
  26504. request.aborted = true;
  26505. return originalAbort.apply(request, arguments);
  26506. };
  26507. request.uri = options.uri;
  26508. request.requestTime = Date.now();
  26509. return request;
  26510. };
  26511. xhr.original = true;
  26512. return xhr;
  26513. };
  26514. /**
  26515. * Turns segment byterange into a string suitable for use in
  26516. * HTTP Range requests
  26517. *
  26518. * @param {Object} byterange - an object with two values defining the start and end
  26519. * of a byte-range
  26520. */
  26521. var byterangeStr = function byterangeStr(byterange) {
  26522. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  26523. // header uses inclusive ranges
  26524. var byterangeEnd;
  26525. var byterangeStart = byterange.offset;
  26526. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  26527. byterangeEnd = window__default['default'].BigInt(byterange.offset) + window__default['default'].BigInt(byterange.length) - window__default['default'].BigInt(1);
  26528. } else {
  26529. byterangeEnd = byterange.offset + byterange.length - 1;
  26530. }
  26531. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  26532. };
  26533. /**
  26534. * Defines headers for use in the xhr request for a particular segment.
  26535. *
  26536. * @param {Object} segment - a simplified copy of the segmentInfo object
  26537. * from SegmentLoader
  26538. */
  26539. var segmentXhrHeaders = function segmentXhrHeaders(segment) {
  26540. var headers = {};
  26541. if (segment.byterange) {
  26542. headers.Range = byterangeStr(segment.byterange);
  26543. }
  26544. return headers;
  26545. };
  26546. /**
  26547. * @file bin-utils.js
  26548. */
  26549. /**
  26550. * convert a TimeRange to text
  26551. *
  26552. * @param {TimeRange} range the timerange to use for conversion
  26553. * @param {number} i the iterator on the range to convert
  26554. * @return {string} the range in string format
  26555. */
  26556. var textRange = function textRange(range, i) {
  26557. return range.start(i) + '-' + range.end(i);
  26558. };
  26559. /**
  26560. * format a number as hex string
  26561. *
  26562. * @param {number} e The number
  26563. * @param {number} i the iterator
  26564. * @return {string} the hex formatted number as a string
  26565. */
  26566. var formatHexString = function formatHexString(e, i) {
  26567. var value = e.toString(16);
  26568. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  26569. };
  26570. var formatAsciiString = function formatAsciiString(e) {
  26571. if (e >= 0x20 && e < 0x7e) {
  26572. return String.fromCharCode(e);
  26573. }
  26574. return '.';
  26575. };
  26576. /**
  26577. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  26578. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  26579. *
  26580. * @param {Object} message
  26581. * Object of properties and values to send to the web worker
  26582. * @return {Object}
  26583. * Modified message with TypedArray values expanded
  26584. * @function createTransferableMessage
  26585. */
  26586. var createTransferableMessage = function createTransferableMessage(message) {
  26587. var transferable = {};
  26588. Object.keys(message).forEach(function (key) {
  26589. var value = message[key];
  26590. if (byteHelpers.isArrayBufferView(value)) {
  26591. transferable[key] = {
  26592. bytes: value.buffer,
  26593. byteOffset: value.byteOffset,
  26594. byteLength: value.byteLength
  26595. };
  26596. } else {
  26597. transferable[key] = value;
  26598. }
  26599. });
  26600. return transferable;
  26601. };
  26602. /**
  26603. * Returns a unique string identifier for a media initialization
  26604. * segment.
  26605. *
  26606. * @param {Object} initSegment
  26607. * the init segment object.
  26608. *
  26609. * @return {string} the generated init segment id
  26610. */
  26611. var initSegmentId = function initSegmentId(initSegment) {
  26612. var byterange = initSegment.byterange || {
  26613. length: Infinity,
  26614. offset: 0
  26615. };
  26616. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  26617. };
  26618. /**
  26619. * Returns a unique string identifier for a media segment key.
  26620. *
  26621. * @param {Object} key the encryption key
  26622. * @return {string} the unique id for the media segment key.
  26623. */
  26624. var segmentKeyId = function segmentKeyId(key) {
  26625. return key.resolvedUri;
  26626. };
  26627. /**
  26628. * utils to help dump binary data to the console
  26629. *
  26630. * @param {Array|TypedArray} data
  26631. * data to dump to a string
  26632. *
  26633. * @return {string} the data as a hex string.
  26634. */
  26635. var hexDump = function hexDump(data) {
  26636. var bytes = Array.prototype.slice.call(data);
  26637. var step = 16;
  26638. var result = '';
  26639. var hex;
  26640. var ascii;
  26641. for (var j = 0; j < bytes.length / step; j++) {
  26642. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  26643. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  26644. result += hex + ' ' + ascii + '\n';
  26645. }
  26646. return result;
  26647. };
  26648. var tagDump = function tagDump(_ref) {
  26649. var bytes = _ref.bytes;
  26650. return hexDump(bytes);
  26651. };
  26652. var textRanges = function textRanges(ranges) {
  26653. var result = '';
  26654. var i;
  26655. for (i = 0; i < ranges.length; i++) {
  26656. result += textRange(ranges, i) + ' ';
  26657. }
  26658. return result;
  26659. };
  26660. var utils = /*#__PURE__*/Object.freeze({
  26661. __proto__: null,
  26662. createTransferableMessage: createTransferableMessage,
  26663. initSegmentId: initSegmentId,
  26664. segmentKeyId: segmentKeyId,
  26665. hexDump: hexDump,
  26666. tagDump: tagDump,
  26667. textRanges: textRanges
  26668. }); // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  26669. // 25% was arbitrarily chosen, and may need to be refined over time.
  26670. var SEGMENT_END_FUDGE_PERCENT = 0.25;
  26671. /**
  26672. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  26673. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  26674. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  26675. *
  26676. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  26677. * point" (a point where we have a mapping from program time to player time, with player
  26678. * time being the post transmux start of the segment).
  26679. *
  26680. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  26681. *
  26682. * @param {number} playerTime the player time
  26683. * @param {Object} segment the segment which contains the player time
  26684. * @return {Date} program time
  26685. */
  26686. var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
  26687. if (!segment.dateTimeObject) {
  26688. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  26689. // be used to map the start of a segment with a real world time).
  26690. return null;
  26691. }
  26692. var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  26693. var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  26694. var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  26695. var offsetFromSegmentStart = playerTime - startOfSegment;
  26696. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  26697. };
  26698. var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
  26699. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  26700. };
  26701. /**
  26702. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  26703. * returned segment might be an estimate or an accurate match.
  26704. *
  26705. * @param {string} programTime The ISO-8601 programTime to find a match for
  26706. * @param {Object} playlist A playlist object to search within
  26707. */
  26708. var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
  26709. // Assumptions:
  26710. // - verifyProgramDateTimeTags has already been run
  26711. // - live streams have been started
  26712. var dateTimeObject;
  26713. try {
  26714. dateTimeObject = new Date(programTime);
  26715. } catch (e) {
  26716. return null;
  26717. }
  26718. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26719. return null;
  26720. }
  26721. var segment = playlist.segments[0];
  26722. if (dateTimeObject < segment.dateTimeObject) {
  26723. // Requested time is before stream start.
  26724. return null;
  26725. }
  26726. for (var i = 0; i < playlist.segments.length - 1; i++) {
  26727. segment = playlist.segments[i];
  26728. var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  26729. if (dateTimeObject < nextSegmentStart) {
  26730. break;
  26731. }
  26732. }
  26733. var lastSegment = playlist.segments[playlist.segments.length - 1];
  26734. var lastSegmentStart = lastSegment.dateTimeObject;
  26735. var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  26736. var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  26737. if (dateTimeObject > lastSegmentEnd) {
  26738. // Beyond the end of the stream, or our best guess of the end of the stream.
  26739. return null;
  26740. }
  26741. if (dateTimeObject > lastSegmentStart) {
  26742. segment = lastSegment;
  26743. }
  26744. return {
  26745. segment: segment,
  26746. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  26747. // Although, given that all segments have accurate date time objects, the segment
  26748. // selected should be accurate, unless the video has been transmuxed at some point
  26749. // (determined by the presence of the videoTimingInfo object), the segment's "player
  26750. // time" (the start time in the player) can't be considered accurate.
  26751. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26752. };
  26753. };
  26754. /**
  26755. * Finds a segment that contains the given player time(in seconds).
  26756. *
  26757. * @param {number} time The player time to find a match for
  26758. * @param {Object} playlist A playlist object to search within
  26759. */
  26760. var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
  26761. // Assumptions:
  26762. // - there will always be a segment.duration
  26763. // - we can start from zero
  26764. // - segments are in time order
  26765. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  26766. return null;
  26767. }
  26768. var segmentEnd = 0;
  26769. var segment;
  26770. for (var i = 0; i < playlist.segments.length; i++) {
  26771. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  26772. // should contain the most accurate values we have for the segment's player times.
  26773. //
  26774. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  26775. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  26776. // calculate an end value.
  26777. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  26778. if (time <= segmentEnd) {
  26779. break;
  26780. }
  26781. }
  26782. var lastSegment = playlist.segments[playlist.segments.length - 1];
  26783. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  26784. // The time requested is beyond the stream end.
  26785. return null;
  26786. }
  26787. if (time > segmentEnd) {
  26788. // The time is within or beyond the last segment.
  26789. //
  26790. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  26791. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  26792. // Technically, because the duration value is only an estimate, the time may still
  26793. // exist in the last segment, however, there isn't enough information to make even
  26794. // a reasonable estimate.
  26795. return null;
  26796. }
  26797. segment = lastSegment;
  26798. }
  26799. return {
  26800. segment: segment,
  26801. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  26802. // Because videoTimingInfo is only set after transmux, it is the only way to get
  26803. // accurate timing values.
  26804. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  26805. };
  26806. };
  26807. /**
  26808. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  26809. * If the offset returned is positive, the programTime occurs after the
  26810. * comparisonTimestamp.
  26811. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  26812. *
  26813. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  26814. * @param {string} programTime The programTime as an ISO-8601 string
  26815. * @return {number} offset
  26816. */
  26817. var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
  26818. var segmentDateTime;
  26819. var programDateTime;
  26820. try {
  26821. segmentDateTime = new Date(comparisonTimeStamp);
  26822. programDateTime = new Date(programTime);
  26823. } catch (e) {// TODO handle error
  26824. }
  26825. var segmentTimeEpoch = segmentDateTime.getTime();
  26826. var programTimeEpoch = programDateTime.getTime();
  26827. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  26828. };
  26829. /**
  26830. * Checks that all segments in this playlist have programDateTime tags.
  26831. *
  26832. * @param {Object} playlist A playlist object
  26833. */
  26834. var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
  26835. if (!playlist.segments || playlist.segments.length === 0) {
  26836. return false;
  26837. }
  26838. for (var i = 0; i < playlist.segments.length; i++) {
  26839. var segment = playlist.segments[i];
  26840. if (!segment.dateTimeObject) {
  26841. return false;
  26842. }
  26843. }
  26844. return true;
  26845. };
  26846. /**
  26847. * Returns the programTime of the media given a playlist and a playerTime.
  26848. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  26849. * If the segments containing the time requested have not been buffered yet, an estimate
  26850. * may be returned to the callback.
  26851. *
  26852. * @param {Object} args
  26853. * @param {Object} args.playlist A playlist object to search within
  26854. * @param {number} time A playerTime in seconds
  26855. * @param {Function} callback(err, programTime)
  26856. * @return {string} err.message A detailed error message
  26857. * @return {Object} programTime
  26858. * @return {number} programTime.mediaSeconds The streamTime in seconds
  26859. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  26860. */
  26861. var getProgramTime = function getProgramTime(_ref) {
  26862. var playlist = _ref.playlist,
  26863. _ref$time = _ref.time,
  26864. time = _ref$time === void 0 ? undefined : _ref$time,
  26865. callback = _ref.callback;
  26866. if (!callback) {
  26867. throw new Error('getProgramTime: callback must be provided');
  26868. }
  26869. if (!playlist || time === undefined) {
  26870. return callback({
  26871. message: 'getProgramTime: playlist and time must be provided'
  26872. });
  26873. }
  26874. var matchedSegment = findSegmentForPlayerTime(time, playlist);
  26875. if (!matchedSegment) {
  26876. return callback({
  26877. message: 'valid programTime was not found'
  26878. });
  26879. }
  26880. if (matchedSegment.type === 'estimate') {
  26881. return callback({
  26882. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  26883. seekTime: matchedSegment.estimatedStart
  26884. });
  26885. }
  26886. var programTimeObject = {
  26887. mediaSeconds: time
  26888. };
  26889. var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  26890. if (programTime) {
  26891. programTimeObject.programDateTime = programTime.toISOString();
  26892. }
  26893. return callback(null, programTimeObject);
  26894. };
  26895. /**
  26896. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  26897. *
  26898. * @param {Object} args
  26899. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  26900. * @param {Object} args.playlist A playlist to look within
  26901. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  26902. * @param {Function} args.seekTo A method to perform a seek
  26903. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  26904. * @param {Object} args.tech The tech to seek on
  26905. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  26906. * @return {string} err.message A detailed error message
  26907. * @return {number} newTime The exact time that was seeked to in seconds
  26908. */
  26909. var seekToProgramTime = function seekToProgramTime(_ref2) {
  26910. var programTime = _ref2.programTime,
  26911. playlist = _ref2.playlist,
  26912. _ref2$retryCount = _ref2.retryCount,
  26913. retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
  26914. seekTo = _ref2.seekTo,
  26915. _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
  26916. pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
  26917. tech = _ref2.tech,
  26918. callback = _ref2.callback;
  26919. if (!callback) {
  26920. throw new Error('seekToProgramTime: callback must be provided');
  26921. }
  26922. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  26923. return callback({
  26924. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  26925. });
  26926. }
  26927. if (!playlist.endList && !tech.hasStarted_) {
  26928. return callback({
  26929. message: 'player must be playing a live stream to start buffering'
  26930. });
  26931. }
  26932. if (!verifyProgramDateTimeTags(playlist)) {
  26933. return callback({
  26934. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  26935. });
  26936. }
  26937. var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  26938. if (!matchedSegment) {
  26939. return callback({
  26940. message: programTime + " was not found in the stream"
  26941. });
  26942. }
  26943. var segment = matchedSegment.segment;
  26944. var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  26945. if (matchedSegment.type === 'estimate') {
  26946. // we've run out of retries
  26947. if (retryCount === 0) {
  26948. return callback({
  26949. message: programTime + " is not buffered yet. Try again"
  26950. });
  26951. }
  26952. seekTo(matchedSegment.estimatedStart + mediaOffset);
  26953. tech.one('seeked', function () {
  26954. seekToProgramTime({
  26955. programTime: programTime,
  26956. playlist: playlist,
  26957. retryCount: retryCount - 1,
  26958. seekTo: seekTo,
  26959. pauseAfterSeek: pauseAfterSeek,
  26960. tech: tech,
  26961. callback: callback
  26962. });
  26963. });
  26964. return;
  26965. } // Since the segment.start value is determined from the buffered end or ending time
  26966. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  26967. // modifications.
  26968. var seekToTime = segment.start + mediaOffset;
  26969. var seekedCallback = function seekedCallback() {
  26970. return callback(null, tech.currentTime());
  26971. }; // listen for seeked event
  26972. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  26973. if (pauseAfterSeek) {
  26974. tech.pause();
  26975. }
  26976. seekTo(seekToTime);
  26977. }; // which will only happen if the request is complete.
  26978. var callbackOnCompleted = function callbackOnCompleted(request, cb) {
  26979. if (request.readyState === 4) {
  26980. return cb();
  26981. }
  26982. return;
  26983. };
  26984. var containerRequest = function containerRequest(uri, xhr, cb) {
  26985. var bytes = [];
  26986. var id3Offset;
  26987. var finished = false;
  26988. var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
  26989. req.abort();
  26990. finished = true;
  26991. return cb(err, req, type, _bytes);
  26992. };
  26993. var progressListener = function progressListener(error, request) {
  26994. if (finished) {
  26995. return;
  26996. }
  26997. if (error) {
  26998. return endRequestAndCallback(error, request, '', bytes);
  26999. } // grap the new part of content that was just downloaded
  27000. var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  27001. bytes = byteHelpers.concatTypedArrays(bytes, byteHelpers.stringToBytes(newPart, true));
  27002. id3Offset = id3Offset || id3Helpers.getId3Offset(bytes); // we need at least 10 bytes to determine a type
  27003. // or we need at least two bytes after an id3Offset
  27004. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  27005. return callbackOnCompleted(request, function () {
  27006. return endRequestAndCallback(error, request, '', bytes);
  27007. });
  27008. }
  27009. var type = containers.detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  27010. // to see the second sync byte, wait until we have enough data
  27011. // before declaring it ts
  27012. if (type === 'ts' && bytes.length < 188) {
  27013. return callbackOnCompleted(request, function () {
  27014. return endRequestAndCallback(error, request, '', bytes);
  27015. });
  27016. } // this may be an unsynced ts segment
  27017. // wait for 376 bytes before detecting no container
  27018. if (!type && bytes.length < 376) {
  27019. return callbackOnCompleted(request, function () {
  27020. return endRequestAndCallback(error, request, '', bytes);
  27021. });
  27022. }
  27023. return endRequestAndCallback(null, request, type, bytes);
  27024. };
  27025. var options = {
  27026. uri: uri,
  27027. beforeSend: function beforeSend(request) {
  27028. // this forces the browser to pass the bytes to us unprocessed
  27029. request.overrideMimeType('text/plain; charset=x-user-defined');
  27030. request.addEventListener('progress', function (_ref) {
  27031. _ref.total;
  27032. _ref.loaded;
  27033. return callbackWrapper(request, null, {
  27034. statusCode: request.status
  27035. }, progressListener);
  27036. });
  27037. }
  27038. };
  27039. var request = xhr(options, function (error, response) {
  27040. return callbackWrapper(request, error, response, progressListener);
  27041. });
  27042. return request;
  27043. };
  27044. var EventTarget = videojs.EventTarget,
  27045. mergeOptions = videojs.mergeOptions;
  27046. var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
  27047. if (!isPlaylistUnchanged(a, b)) {
  27048. return false;
  27049. } // for dash the above check will often return true in scenarios where
  27050. // the playlist actually has changed because mediaSequence isn't a
  27051. // dash thing, and we often set it to 1. So if the playlists have the same amount
  27052. // of segments we return true.
  27053. // So for dash we need to make sure that the underlying segments are different.
  27054. // if sidx changed then the playlists are different.
  27055. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  27056. return false;
  27057. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  27058. return false;
  27059. } // one or the other does not have segments
  27060. // there was a change.
  27061. if (a.segments && !b.segments || !a.segments && b.segments) {
  27062. return false;
  27063. } // neither has segments nothing changed
  27064. if (!a.segments && !b.segments) {
  27065. return true;
  27066. } // check segments themselves
  27067. for (var i = 0; i < a.segments.length; i++) {
  27068. var aSegment = a.segments[i];
  27069. var bSegment = b.segments[i]; // if uris are different between segments there was a change
  27070. if (aSegment.uri !== bSegment.uri) {
  27071. return false;
  27072. } // neither segment has a byterange, there will be no byterange change.
  27073. if (!aSegment.byterange && !bSegment.byterange) {
  27074. continue;
  27075. }
  27076. var aByterange = aSegment.byterange;
  27077. var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  27078. if (aByterange && !bByterange || !aByterange && bByterange) {
  27079. return false;
  27080. } // if both segments have byterange with different offsets, there was a change.
  27081. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  27082. return false;
  27083. }
  27084. } // if everything was the same with segments, this is the same playlist.
  27085. return true;
  27086. };
  27087. /**
  27088. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  27089. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  27090. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  27091. * periods without continuous playback this function may need modification as well as the parser.
  27092. */
  27093. var dashGroupId = function dashGroupId(type, group, label, playlist) {
  27094. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  27095. var playlistId = playlist.attributes.NAME || label;
  27096. return "placeholder-uri-" + type + "-" + group + "-" + playlistId;
  27097. };
  27098. /**
  27099. * Parses the master XML string and updates playlist URI references.
  27100. *
  27101. * @param {Object} config
  27102. * Object of arguments
  27103. * @param {string} config.masterXml
  27104. * The mpd XML
  27105. * @param {string} config.srcUrl
  27106. * The mpd URL
  27107. * @param {Date} config.clientOffset
  27108. * A time difference between server and client
  27109. * @param {Object} config.sidxMapping
  27110. * SIDX mappings for moof/mdat URIs and byte ranges
  27111. * @return {Object}
  27112. * The parsed mpd manifest object
  27113. */
  27114. var parseMasterXml = function parseMasterXml(_ref) {
  27115. var masterXml = _ref.masterXml,
  27116. srcUrl = _ref.srcUrl,
  27117. clientOffset = _ref.clientOffset,
  27118. sidxMapping = _ref.sidxMapping,
  27119. previousManifest = _ref.previousManifest;
  27120. var manifest = mpdParser.parse(masterXml, {
  27121. manifestUri: srcUrl,
  27122. clientOffset: clientOffset,
  27123. sidxMapping: sidxMapping,
  27124. previousManifest: previousManifest
  27125. });
  27126. addPropertiesToMaster(manifest, srcUrl, dashGroupId);
  27127. return manifest;
  27128. };
  27129. /**
  27130. * Removes any mediaGroup labels that no longer exist in the newMaster
  27131. *
  27132. * @param {Object} update
  27133. * The previous mpd object being updated
  27134. * @param {Object} newMaster
  27135. * The new mpd object
  27136. */
  27137. var removeOldMediaGroupLabels = function removeOldMediaGroupLabels(update, newMaster) {
  27138. forEachMediaGroup(update, function (properties, type, group, label) {
  27139. if (!(label in newMaster.mediaGroups[type][group])) {
  27140. delete update.mediaGroups[type][group][label];
  27141. }
  27142. });
  27143. };
  27144. /**
  27145. * Returns a new master manifest that is the result of merging an updated master manifest
  27146. * into the original version.
  27147. *
  27148. * @param {Object} oldMaster
  27149. * The old parsed mpd object
  27150. * @param {Object} newMaster
  27151. * The updated parsed mpd object
  27152. * @return {Object}
  27153. * A new object representing the original master manifest with the updated media
  27154. * playlists merged in
  27155. */
  27156. var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
  27157. var noChanges = true;
  27158. var update = mergeOptions(oldMaster, {
  27159. // These are top level properties that can be updated
  27160. duration: newMaster.duration,
  27161. minimumUpdatePeriod: newMaster.minimumUpdatePeriod,
  27162. timelineStarts: newMaster.timelineStarts
  27163. }); // First update the playlists in playlist list
  27164. for (var i = 0; i < newMaster.playlists.length; i++) {
  27165. var playlist = newMaster.playlists[i];
  27166. if (playlist.sidx) {
  27167. var sidxKey = mpdParser.generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  27168. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  27169. mpdParser.addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  27170. }
  27171. }
  27172. var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
  27173. if (playlistUpdate) {
  27174. update = playlistUpdate;
  27175. noChanges = false;
  27176. }
  27177. } // Then update media group playlists
  27178. forEachMediaGroup(newMaster, function (properties, type, group, label) {
  27179. if (properties.playlists && properties.playlists.length) {
  27180. var id = properties.playlists[0].id;
  27181. var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
  27182. if (_playlistUpdate) {
  27183. update = _playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  27184. if (!(label in update.mediaGroups[type][group])) {
  27185. update.mediaGroups[type][group][label] = properties;
  27186. } // update the playlist reference within media groups
  27187. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  27188. noChanges = false;
  27189. }
  27190. }
  27191. }); // remove mediaGroup labels and references that no longer exist in the newMaster
  27192. removeOldMediaGroupLabels(update, newMaster);
  27193. if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  27194. noChanges = false;
  27195. }
  27196. if (noChanges) {
  27197. return null;
  27198. }
  27199. return update;
  27200. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  27201. // If the SIDXs have maps, the two maps should match,
  27202. // both `a` and `b` missing SIDXs is considered matching.
  27203. // If `a` or `b` but not both have a map, they aren't matching.
  27204. var equivalentSidx = function equivalentSidx(a, b) {
  27205. var neitherMap = Boolean(!a.map && !b.map);
  27206. var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  27207. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  27208. }; // exported for testing
  27209. var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
  27210. var newSidxMapping = {};
  27211. for (var id in playlists) {
  27212. var playlist = playlists[id];
  27213. var currentSidxInfo = playlist.sidx;
  27214. if (currentSidxInfo) {
  27215. var key = mpdParser.generateSidxKey(currentSidxInfo);
  27216. if (!oldSidxMapping[key]) {
  27217. break;
  27218. }
  27219. var savedSidxInfo = oldSidxMapping[key].sidxInfo;
  27220. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  27221. newSidxMapping[key] = oldSidxMapping[key];
  27222. }
  27223. }
  27224. }
  27225. return newSidxMapping;
  27226. };
  27227. /**
  27228. * A function that filters out changed items as they need to be requested separately.
  27229. *
  27230. * The method is exported for testing
  27231. *
  27232. * @param {Object} master the parsed mpd XML returned via mpd-parser
  27233. * @param {Object} oldSidxMapping the SIDX to compare against
  27234. */
  27235. var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
  27236. var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
  27237. var mediaGroupSidx = videoSidx;
  27238. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  27239. if (properties.playlists && properties.playlists.length) {
  27240. var playlists = properties.playlists;
  27241. mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  27242. }
  27243. });
  27244. return mediaGroupSidx;
  27245. };
  27246. var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  27247. _inheritsLoose__default['default'](DashPlaylistLoader, _EventTarget); // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  27248. // playlist loader setups from media groups will expect to be able to pass a playlist
  27249. // (since there aren't external URLs to media playlists with DASH)
  27250. function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
  27251. var _this;
  27252. if (options === void 0) {
  27253. options = {};
  27254. }
  27255. _this = _EventTarget.call(this) || this;
  27256. _this.masterPlaylistLoader_ = masterPlaylistLoader || _assertThisInitialized__default['default'](_this);
  27257. if (!masterPlaylistLoader) {
  27258. _this.isMaster_ = true;
  27259. }
  27260. var _options = options,
  27261. _options$withCredenti = _options.withCredentials,
  27262. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  27263. _options$handleManife = _options.handleManifestRedirects,
  27264. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  27265. _this.vhs_ = vhs;
  27266. _this.withCredentials = withCredentials;
  27267. _this.handleManifestRedirects = handleManifestRedirects;
  27268. if (!srcUrlOrPlaylist) {
  27269. throw new Error('A non-empty playlist URL or object is required');
  27270. } // event naming?
  27271. _this.on('minimumUpdatePeriod', function () {
  27272. _this.refreshXml_();
  27273. }); // live playlist staleness timeout
  27274. _this.on('mediaupdatetimeout', function () {
  27275. _this.refreshMedia_(_this.media().id);
  27276. });
  27277. _this.state = 'HAVE_NOTHING';
  27278. _this.loadedPlaylists_ = {};
  27279. _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  27280. // The masterPlaylistLoader will be created with a string
  27281. if (_this.isMaster_) {
  27282. _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  27283. // once multi-period is refactored
  27284. _this.masterPlaylistLoader_.sidxMapping_ = {};
  27285. } else {
  27286. _this.childPlaylist_ = srcUrlOrPlaylist;
  27287. }
  27288. return _this;
  27289. }
  27290. var _proto = DashPlaylistLoader.prototype;
  27291. _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
  27292. // disposed
  27293. if (!this.request) {
  27294. return true;
  27295. } // pending request is cleared
  27296. this.request = null;
  27297. if (err) {
  27298. // use the provided error object or create one
  27299. // based on the request/response
  27300. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  27301. status: request.status,
  27302. message: 'DASH request error at URL: ' + request.uri,
  27303. response: request.response,
  27304. // MEDIA_ERR_NETWORK
  27305. code: 2
  27306. };
  27307. if (startingState) {
  27308. this.state = startingState;
  27309. }
  27310. this.trigger('error');
  27311. return true;
  27312. }
  27313. }
  27314. /**
  27315. * Verify that the container of the sidx segment can be parsed
  27316. * and if it can, get and parse that segment.
  27317. */
  27318. ;
  27319. _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
  27320. var _this2 = this;
  27321. var sidxKey = playlist.sidx && mpdParser.generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  27322. if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
  27323. // keep this function async
  27324. this.mediaRequest_ = window__default['default'].setTimeout(function () {
  27325. return cb(false);
  27326. }, 0);
  27327. return;
  27328. } // resolve the segment URL relative to the playlist
  27329. var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
  27330. var fin = function fin(err, request) {
  27331. if (_this2.requestErrored_(err, request, startingState)) {
  27332. return;
  27333. }
  27334. var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
  27335. var sidx;
  27336. try {
  27337. sidx = parseSidx__default['default'](byteHelpers.toUint8(request.response).subarray(8));
  27338. } catch (e) {
  27339. // sidx parsing failed.
  27340. _this2.requestErrored_(e, request, startingState);
  27341. return;
  27342. }
  27343. sidxMapping[sidxKey] = {
  27344. sidxInfo: playlist.sidx,
  27345. sidx: sidx
  27346. };
  27347. mpdParser.addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  27348. return cb(true);
  27349. };
  27350. this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
  27351. if (err) {
  27352. return fin(err, request);
  27353. }
  27354. if (!container || container !== 'mp4') {
  27355. return fin({
  27356. status: request.status,
  27357. message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
  27358. // response is just bytes in this case
  27359. // but we really don't want to return that.
  27360. response: '',
  27361. playlist: playlist,
  27362. internal: true,
  27363. blacklistDuration: Infinity,
  27364. // MEDIA_ERR_NETWORK
  27365. code: 2
  27366. }, request);
  27367. } // if we already downloaded the sidx bytes in the container request, use them
  27368. var _playlist$sidx$bytera = playlist.sidx.byterange,
  27369. offset = _playlist$sidx$bytera.offset,
  27370. length = _playlist$sidx$bytera.length;
  27371. if (bytes.length >= length + offset) {
  27372. return fin(err, {
  27373. response: bytes.subarray(offset, offset + length),
  27374. status: request.status,
  27375. uri: request.uri
  27376. });
  27377. } // otherwise request sidx bytes
  27378. _this2.request = _this2.vhs_.xhr({
  27379. uri: uri,
  27380. responseType: 'arraybuffer',
  27381. headers: segmentXhrHeaders({
  27382. byterange: playlist.sidx.byterange
  27383. })
  27384. }, fin);
  27385. });
  27386. };
  27387. _proto.dispose = function dispose() {
  27388. this.trigger('dispose');
  27389. this.stopRequest();
  27390. this.loadedPlaylists_ = {};
  27391. window__default['default'].clearTimeout(this.minimumUpdatePeriodTimeout_);
  27392. window__default['default'].clearTimeout(this.mediaRequest_);
  27393. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  27394. this.mediaUpdateTimeout = null;
  27395. this.mediaRequest_ = null;
  27396. this.minimumUpdatePeriodTimeout_ = null;
  27397. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  27398. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  27399. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  27400. }
  27401. this.off();
  27402. };
  27403. _proto.hasPendingRequest = function hasPendingRequest() {
  27404. return this.request || this.mediaRequest_;
  27405. };
  27406. _proto.stopRequest = function stopRequest() {
  27407. if (this.request) {
  27408. var oldRequest = this.request;
  27409. this.request = null;
  27410. oldRequest.onreadystatechange = null;
  27411. oldRequest.abort();
  27412. }
  27413. };
  27414. _proto.media = function media(playlist) {
  27415. var _this3 = this; // getter
  27416. if (!playlist) {
  27417. return this.media_;
  27418. } // setter
  27419. if (this.state === 'HAVE_NOTHING') {
  27420. throw new Error('Cannot switch media playlist from ' + this.state);
  27421. }
  27422. var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  27423. if (typeof playlist === 'string') {
  27424. if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
  27425. throw new Error('Unknown playlist URI: ' + playlist);
  27426. }
  27427. playlist = this.masterPlaylistLoader_.master.playlists[playlist];
  27428. }
  27429. var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  27430. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  27431. this.state = 'HAVE_METADATA';
  27432. this.media_ = playlist; // trigger media change if the active media has been updated
  27433. if (mediaChange) {
  27434. this.trigger('mediachanging');
  27435. this.trigger('mediachange');
  27436. }
  27437. return;
  27438. } // switching to the active playlist is a no-op
  27439. if (!mediaChange) {
  27440. return;
  27441. } // switching from an already loaded playlist
  27442. if (this.media_) {
  27443. this.trigger('mediachanging');
  27444. }
  27445. this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
  27446. // everything is ready just continue to haveMetadata
  27447. _this3.haveMetadata({
  27448. startingState: startingState,
  27449. playlist: playlist
  27450. });
  27451. });
  27452. };
  27453. _proto.haveMetadata = function haveMetadata(_ref2) {
  27454. var startingState = _ref2.startingState,
  27455. playlist = _ref2.playlist;
  27456. this.state = 'HAVE_METADATA';
  27457. this.loadedPlaylists_[playlist.id] = playlist;
  27458. this.mediaRequest_ = null; // This will trigger loadedplaylist
  27459. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  27460. // to resolve setup of media groups
  27461. if (startingState === 'HAVE_MASTER') {
  27462. this.trigger('loadedmetadata');
  27463. } else {
  27464. // trigger media change if the active media has been updated
  27465. this.trigger('mediachange');
  27466. }
  27467. };
  27468. _proto.pause = function pause() {
  27469. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  27470. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  27471. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  27472. }
  27473. this.stopRequest();
  27474. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  27475. this.mediaUpdateTimeout = null;
  27476. if (this.isMaster_) {
  27477. window__default['default'].clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
  27478. this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  27479. }
  27480. if (this.state === 'HAVE_NOTHING') {
  27481. // If we pause the loader before any data has been retrieved, its as if we never
  27482. // started, so reset to an unstarted state.
  27483. this.started = false;
  27484. }
  27485. };
  27486. _proto.load = function load(isFinalRendition) {
  27487. var _this4 = this;
  27488. window__default['default'].clearTimeout(this.mediaUpdateTimeout);
  27489. this.mediaUpdateTimeout = null;
  27490. var media = this.media();
  27491. if (isFinalRendition) {
  27492. var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  27493. this.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
  27494. return _this4.load();
  27495. }, delay);
  27496. return;
  27497. } // because the playlists are internal to the manifest, load should either load the
  27498. // main manifest, or do nothing but trigger an event
  27499. if (!this.started) {
  27500. this.start();
  27501. return;
  27502. }
  27503. if (media && !media.endList) {
  27504. // Check to see if this is the master loader and the MUP was cleared (this happens
  27505. // when the loader was paused). `media` should be set at this point since one is always
  27506. // set during `start()`.
  27507. if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
  27508. // Trigger minimumUpdatePeriod to refresh the master manifest
  27509. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  27510. this.updateMinimumUpdatePeriodTimeout_();
  27511. }
  27512. this.trigger('mediaupdatetimeout');
  27513. } else {
  27514. this.trigger('loadedplaylist');
  27515. }
  27516. };
  27517. _proto.start = function start() {
  27518. var _this5 = this;
  27519. this.started = true; // We don't need to request the master manifest again
  27520. // Call this asynchronously to match the xhr request behavior below
  27521. if (!this.isMaster_) {
  27522. this.mediaRequest_ = window__default['default'].setTimeout(function () {
  27523. return _this5.haveMaster_();
  27524. }, 0);
  27525. return;
  27526. }
  27527. this.requestMaster_(function (req, masterChanged) {
  27528. _this5.haveMaster_();
  27529. if (!_this5.hasPendingRequest() && !_this5.media_) {
  27530. _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
  27531. }
  27532. });
  27533. };
  27534. _proto.requestMaster_ = function requestMaster_(cb) {
  27535. var _this6 = this;
  27536. this.request = this.vhs_.xhr({
  27537. uri: this.masterPlaylistLoader_.srcUrl,
  27538. withCredentials: this.withCredentials
  27539. }, function (error, req) {
  27540. if (_this6.requestErrored_(error, req)) {
  27541. if (_this6.state === 'HAVE_NOTHING') {
  27542. _this6.started = false;
  27543. }
  27544. return;
  27545. }
  27546. var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
  27547. _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
  27548. if (req.responseHeaders && req.responseHeaders.date) {
  27549. _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
  27550. } else {
  27551. _this6.masterLoaded_ = Date.now();
  27552. }
  27553. _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
  27554. if (masterChanged) {
  27555. _this6.handleMaster_();
  27556. _this6.syncClientServerClock_(function () {
  27557. return cb(req, masterChanged);
  27558. });
  27559. return;
  27560. }
  27561. return cb(req, masterChanged);
  27562. });
  27563. }
  27564. /**
  27565. * Parses the master xml for UTCTiming node to sync the client clock to the server
  27566. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  27567. *
  27568. * @param {Function} done
  27569. * Function to call when clock sync has completed
  27570. */
  27571. ;
  27572. _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
  27573. var _this7 = this;
  27574. var utcTiming = mpdParser.parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  27575. // server clock
  27576. if (utcTiming === null) {
  27577. this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
  27578. return done();
  27579. }
  27580. if (utcTiming.method === 'DIRECT') {
  27581. this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  27582. return done();
  27583. }
  27584. this.request = this.vhs_.xhr({
  27585. uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
  27586. method: utcTiming.method,
  27587. withCredentials: this.withCredentials
  27588. }, function (error, req) {
  27589. // disposed
  27590. if (!_this7.request) {
  27591. return;
  27592. }
  27593. if (error) {
  27594. // sync request failed, fall back to using date header from mpd
  27595. // TODO: log warning
  27596. _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
  27597. return done();
  27598. }
  27599. var serverTime;
  27600. if (utcTiming.method === 'HEAD') {
  27601. if (!req.responseHeaders || !req.responseHeaders.date) {
  27602. // expected date header not preset, fall back to using date header from mpd
  27603. // TODO: log warning
  27604. serverTime = _this7.masterLoaded_;
  27605. } else {
  27606. serverTime = Date.parse(req.responseHeaders.date);
  27607. }
  27608. } else {
  27609. serverTime = Date.parse(req.responseText);
  27610. }
  27611. _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  27612. done();
  27613. });
  27614. };
  27615. _proto.haveMaster_ = function haveMaster_() {
  27616. this.state = 'HAVE_MASTER';
  27617. if (this.isMaster_) {
  27618. // We have the master playlist at this point, so
  27619. // trigger this to allow MasterPlaylistController
  27620. // to make an initial playlist selection
  27621. this.trigger('loadedplaylist');
  27622. } else if (!this.media_) {
  27623. // no media playlist was specifically selected so select
  27624. // the one the child playlist loader was created with
  27625. this.media(this.childPlaylist_);
  27626. }
  27627. };
  27628. _proto.handleMaster_ = function handleMaster_() {
  27629. // clear media request
  27630. this.mediaRequest_ = null;
  27631. var oldMaster = this.masterPlaylistLoader_.master;
  27632. var newMaster = parseMasterXml({
  27633. masterXml: this.masterPlaylistLoader_.masterXml_,
  27634. srcUrl: this.masterPlaylistLoader_.srcUrl,
  27635. clientOffset: this.masterPlaylistLoader_.clientOffset_,
  27636. sidxMapping: this.masterPlaylistLoader_.sidxMapping_,
  27637. previousManifest: oldMaster
  27638. }); // if we have an old master to compare the new master against
  27639. if (oldMaster) {
  27640. newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
  27641. } // only update master if we have a new master
  27642. this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
  27643. var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
  27644. if (location && location !== this.masterPlaylistLoader_.srcUrl) {
  27645. this.masterPlaylistLoader_.srcUrl = location;
  27646. }
  27647. if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  27648. this.updateMinimumUpdatePeriodTimeout_();
  27649. }
  27650. return Boolean(newMaster);
  27651. };
  27652. _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
  27653. var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
  27654. // a new one will be added if needed.
  27655. if (mpl.createMupOnMedia_) {
  27656. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  27657. mpl.createMupOnMedia_ = null;
  27658. } // clear any pending timeouts
  27659. if (mpl.minimumUpdatePeriodTimeout_) {
  27660. window__default['default'].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  27661. mpl.minimumUpdatePeriodTimeout_ = null;
  27662. }
  27663. var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  27664. // MPD has no future validity, so a new one will need to be acquired when new
  27665. // media segments are to be made available. Thus, we use the target duration
  27666. // in this case
  27667. if (mup === 0) {
  27668. if (mpl.media()) {
  27669. mup = mpl.media().targetDuration * 1000;
  27670. } else {
  27671. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  27672. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  27673. }
  27674. } // if minimumUpdatePeriod is invalid or <= zero, which
  27675. // can happen when a live video becomes VOD. skip timeout
  27676. // creation.
  27677. if (typeof mup !== 'number' || mup <= 0) {
  27678. if (mup < 0) {
  27679. this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
  27680. }
  27681. return;
  27682. }
  27683. this.createMUPTimeout_(mup);
  27684. };
  27685. _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
  27686. var mpl = this.masterPlaylistLoader_;
  27687. mpl.minimumUpdatePeriodTimeout_ = window__default['default'].setTimeout(function () {
  27688. mpl.minimumUpdatePeriodTimeout_ = null;
  27689. mpl.trigger('minimumUpdatePeriod');
  27690. mpl.createMUPTimeout_(mup);
  27691. }, mup);
  27692. }
  27693. /**
  27694. * Sends request to refresh the master xml and updates the parsed master manifest
  27695. */
  27696. ;
  27697. _proto.refreshXml_ = function refreshXml_() {
  27698. var _this8 = this;
  27699. this.requestMaster_(function (req, masterChanged) {
  27700. if (!masterChanged) {
  27701. return;
  27702. }
  27703. if (_this8.media_) {
  27704. _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
  27705. } // This will filter out updated sidx info from the mapping
  27706. _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
  27707. _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
  27708. // TODO: do we need to reload the current playlist?
  27709. _this8.refreshMedia_(_this8.media().id);
  27710. });
  27711. });
  27712. }
  27713. /**
  27714. * Refreshes the media playlist by re-parsing the master xml and updating playlist
  27715. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  27716. * from the master loader.
  27717. */
  27718. ;
  27719. _proto.refreshMedia_ = function refreshMedia_(mediaID) {
  27720. var _this9 = this;
  27721. if (!mediaID) {
  27722. throw new Error('refreshMedia_ must take a media id');
  27723. } // for master we have to reparse the master xml
  27724. // to re-create segments based on current timing values
  27725. // which may change media. We only skip updating master
  27726. // if this is the first time this.media_ is being set.
  27727. // as master was just parsed in that case.
  27728. if (this.media_ && this.isMaster_) {
  27729. this.handleMaster_();
  27730. }
  27731. var playlists = this.masterPlaylistLoader_.master.playlists;
  27732. var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  27733. if (mediaChanged) {
  27734. this.media_ = playlists[mediaID];
  27735. } else {
  27736. this.trigger('playlistunchanged');
  27737. }
  27738. if (!this.mediaUpdateTimeout) {
  27739. var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
  27740. if (_this9.media().endList) {
  27741. return;
  27742. }
  27743. _this9.mediaUpdateTimeout = window__default['default'].setTimeout(function () {
  27744. _this9.trigger('mediaupdatetimeout');
  27745. createMediaUpdateTimeout();
  27746. }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
  27747. };
  27748. createMediaUpdateTimeout();
  27749. }
  27750. this.trigger('loadedplaylist');
  27751. };
  27752. return DashPlaylistLoader;
  27753. }(EventTarget);
  27754. var Config = {
  27755. GOAL_BUFFER_LENGTH: 30,
  27756. MAX_GOAL_BUFFER_LENGTH: 60,
  27757. BACK_BUFFER_LENGTH: 30,
  27758. GOAL_BUFFER_LENGTH_RATE: 1,
  27759. // 0.5 MB/s
  27760. INITIAL_BANDWIDTH: 4194304,
  27761. // A fudge factor to apply to advertised playlist bitrates to account for
  27762. // temporary flucations in client bandwidth
  27763. BANDWIDTH_VARIANCE: 1.2,
  27764. // How much of the buffer must be filled before we consider upswitching
  27765. BUFFER_LOW_WATER_LINE: 0,
  27766. MAX_BUFFER_LOW_WATER_LINE: 30,
  27767. // TODO: Remove this when experimentalBufferBasedABR is removed
  27768. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  27769. BUFFER_LOW_WATER_LINE_RATE: 1,
  27770. // If the buffer is greater than the high water line, we won't switch down
  27771. BUFFER_HIGH_WATER_LINE: 30
  27772. };
  27773. var stringToArrayBuffer = function stringToArrayBuffer(string) {
  27774. var view = new Uint8Array(new ArrayBuffer(string.length));
  27775. for (var i = 0; i < string.length; i++) {
  27776. view[i] = string.charCodeAt(i);
  27777. }
  27778. return view.buffer;
  27779. };
  27780. /* global Blob, BlobBuilder, Worker */
  27781. // unify worker interface
  27782. var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
  27783. // node only supports on/off
  27784. workerObj.on = workerObj.addEventListener;
  27785. workerObj.off = workerObj.removeEventListener;
  27786. return workerObj;
  27787. };
  27788. var createObjectURL = function createObjectURL(str) {
  27789. try {
  27790. return URL.createObjectURL(new Blob([str], {
  27791. type: 'application/javascript'
  27792. }));
  27793. } catch (e) {
  27794. var blob = new BlobBuilder();
  27795. blob.append(str);
  27796. return URL.createObjectURL(blob.getBlob());
  27797. }
  27798. };
  27799. var factory = function factory(code) {
  27800. return function () {
  27801. var objectUrl = createObjectURL(code);
  27802. var worker = browserWorkerPolyFill(new Worker(objectUrl));
  27803. worker.objURL = objectUrl;
  27804. var terminate = worker.terminate;
  27805. worker.on = worker.addEventListener;
  27806. worker.off = worker.removeEventListener;
  27807. worker.terminate = function () {
  27808. URL.revokeObjectURL(objectUrl);
  27809. return terminate.call(this);
  27810. };
  27811. return worker;
  27812. };
  27813. };
  27814. var transform = function transform(code) {
  27815. return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
  27816. };
  27817. var getWorkerString = function getWorkerString(fn) {
  27818. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  27819. };
  27820. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  27821. var workerCode$1 = transform(getWorkerString(function () {
  27822. /**
  27823. * mux.js
  27824. *
  27825. * Copyright (c) Brightcove
  27826. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  27827. *
  27828. * A lightweight readable stream implemention that handles event dispatching.
  27829. * Objects that inherit from streams should call init in their constructors.
  27830. */
  27831. var Stream = function Stream() {
  27832. this.init = function () {
  27833. var listeners = {};
  27834. /**
  27835. * Add a listener for a specified event type.
  27836. * @param type {string} the event name
  27837. * @param listener {function} the callback to be invoked when an event of
  27838. * the specified type occurs
  27839. */
  27840. this.on = function (type, listener) {
  27841. if (!listeners[type]) {
  27842. listeners[type] = [];
  27843. }
  27844. listeners[type] = listeners[type].concat(listener);
  27845. };
  27846. /**
  27847. * Remove a listener for a specified event type.
  27848. * @param type {string} the event name
  27849. * @param listener {function} a function previously registered for this
  27850. * type of event through `on`
  27851. */
  27852. this.off = function (type, listener) {
  27853. var index;
  27854. if (!listeners[type]) {
  27855. return false;
  27856. }
  27857. index = listeners[type].indexOf(listener);
  27858. listeners[type] = listeners[type].slice();
  27859. listeners[type].splice(index, 1);
  27860. return index > -1;
  27861. };
  27862. /**
  27863. * Trigger an event of the specified type on this stream. Any additional
  27864. * arguments to this function are passed as parameters to event listeners.
  27865. * @param type {string} the event name
  27866. */
  27867. this.trigger = function (type) {
  27868. var callbacks, i, length, args;
  27869. callbacks = listeners[type];
  27870. if (!callbacks) {
  27871. return;
  27872. } // Slicing the arguments on every invocation of this method
  27873. // can add a significant amount of overhead. Avoid the
  27874. // intermediate object creation for the common case of a
  27875. // single callback argument
  27876. if (arguments.length === 2) {
  27877. length = callbacks.length;
  27878. for (i = 0; i < length; ++i) {
  27879. callbacks[i].call(this, arguments[1]);
  27880. }
  27881. } else {
  27882. args = [];
  27883. i = arguments.length;
  27884. for (i = 1; i < arguments.length; ++i) {
  27885. args.push(arguments[i]);
  27886. }
  27887. length = callbacks.length;
  27888. for (i = 0; i < length; ++i) {
  27889. callbacks[i].apply(this, args);
  27890. }
  27891. }
  27892. };
  27893. /**
  27894. * Destroys the stream and cleans up.
  27895. */
  27896. this.dispose = function () {
  27897. listeners = {};
  27898. };
  27899. };
  27900. };
  27901. /**
  27902. * Forwards all `data` events on this stream to the destination stream. The
  27903. * destination stream should provide a method `push` to receive the data
  27904. * events as they arrive.
  27905. * @param destination {stream} the stream that will receive all `data` events
  27906. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  27907. * when the current stream emits a 'done' event
  27908. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  27909. */
  27910. Stream.prototype.pipe = function (destination) {
  27911. this.on('data', function (data) {
  27912. destination.push(data);
  27913. });
  27914. this.on('done', function (flushSource) {
  27915. destination.flush(flushSource);
  27916. });
  27917. this.on('partialdone', function (flushSource) {
  27918. destination.partialFlush(flushSource);
  27919. });
  27920. this.on('endedtimeline', function (flushSource) {
  27921. destination.endTimeline(flushSource);
  27922. });
  27923. this.on('reset', function (flushSource) {
  27924. destination.reset(flushSource);
  27925. });
  27926. return destination;
  27927. }; // Default stream functions that are expected to be overridden to perform
  27928. // actual work. These are provided by the prototype as a sort of no-op
  27929. // implementation so that we don't have to check for their existence in the
  27930. // `pipe` function above.
  27931. Stream.prototype.push = function (data) {
  27932. this.trigger('data', data);
  27933. };
  27934. Stream.prototype.flush = function (flushSource) {
  27935. this.trigger('done', flushSource);
  27936. };
  27937. Stream.prototype.partialFlush = function (flushSource) {
  27938. this.trigger('partialdone', flushSource);
  27939. };
  27940. Stream.prototype.endTimeline = function (flushSource) {
  27941. this.trigger('endedtimeline', flushSource);
  27942. };
  27943. Stream.prototype.reset = function (flushSource) {
  27944. this.trigger('reset', flushSource);
  27945. };
  27946. var stream = Stream;
  27947. var MAX_UINT32$1 = Math.pow(2, 32);
  27948. var getUint64$2 = function getUint64(uint8) {
  27949. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  27950. var value;
  27951. if (dv.getBigUint64) {
  27952. value = dv.getBigUint64(0);
  27953. if (value < Number.MAX_SAFE_INTEGER) {
  27954. return Number(value);
  27955. }
  27956. return value;
  27957. }
  27958. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  27959. };
  27960. var numbers = {
  27961. getUint64: getUint64$2,
  27962. MAX_UINT32: MAX_UINT32$1
  27963. };
  27964. var MAX_UINT32 = numbers.MAX_UINT32;
  27965. 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
  27966. (function () {
  27967. var i;
  27968. types = {
  27969. avc1: [],
  27970. // codingname
  27971. avcC: [],
  27972. btrt: [],
  27973. dinf: [],
  27974. dref: [],
  27975. esds: [],
  27976. ftyp: [],
  27977. hdlr: [],
  27978. mdat: [],
  27979. mdhd: [],
  27980. mdia: [],
  27981. mfhd: [],
  27982. minf: [],
  27983. moof: [],
  27984. moov: [],
  27985. mp4a: [],
  27986. // codingname
  27987. mvex: [],
  27988. mvhd: [],
  27989. pasp: [],
  27990. sdtp: [],
  27991. smhd: [],
  27992. stbl: [],
  27993. stco: [],
  27994. stsc: [],
  27995. stsd: [],
  27996. stsz: [],
  27997. stts: [],
  27998. styp: [],
  27999. tfdt: [],
  28000. tfhd: [],
  28001. traf: [],
  28002. trak: [],
  28003. trun: [],
  28004. trex: [],
  28005. tkhd: [],
  28006. vmhd: []
  28007. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  28008. // don't throw an error
  28009. if (typeof Uint8Array === 'undefined') {
  28010. return;
  28011. }
  28012. for (i in types) {
  28013. if (types.hasOwnProperty(i)) {
  28014. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  28015. }
  28016. }
  28017. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  28018. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  28019. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  28020. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  28021. 0x00, 0x00, 0x00, // flags
  28022. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28023. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  28024. 0x00, 0x00, 0x00, 0x00, // reserved
  28025. 0x00, 0x00, 0x00, 0x00, // reserved
  28026. 0x00, 0x00, 0x00, 0x00, // reserved
  28027. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  28028. ]);
  28029. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  28030. 0x00, 0x00, 0x00, // flags
  28031. 0x00, 0x00, 0x00, 0x00, // pre_defined
  28032. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  28033. 0x00, 0x00, 0x00, 0x00, // reserved
  28034. 0x00, 0x00, 0x00, 0x00, // reserved
  28035. 0x00, 0x00, 0x00, 0x00, // reserved
  28036. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  28037. ]);
  28038. HDLR_TYPES = {
  28039. video: VIDEO_HDLR,
  28040. audio: AUDIO_HDLR
  28041. };
  28042. DREF = new Uint8Array([0x00, // version 0
  28043. 0x00, 0x00, 0x00, // flags
  28044. 0x00, 0x00, 0x00, 0x01, // entry_count
  28045. 0x00, 0x00, 0x00, 0x0c, // entry_size
  28046. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  28047. 0x00, // version 0
  28048. 0x00, 0x00, 0x01 // entry_flags
  28049. ]);
  28050. SMHD = new Uint8Array([0x00, // version
  28051. 0x00, 0x00, 0x00, // flags
  28052. 0x00, 0x00, // balance, 0 means centered
  28053. 0x00, 0x00 // reserved
  28054. ]);
  28055. STCO = new Uint8Array([0x00, // version
  28056. 0x00, 0x00, 0x00, // flags
  28057. 0x00, 0x00, 0x00, 0x00 // entry_count
  28058. ]);
  28059. STSC = STCO;
  28060. STSZ = new Uint8Array([0x00, // version
  28061. 0x00, 0x00, 0x00, // flags
  28062. 0x00, 0x00, 0x00, 0x00, // sample_size
  28063. 0x00, 0x00, 0x00, 0x00 // sample_count
  28064. ]);
  28065. STTS = STCO;
  28066. VMHD = new Uint8Array([0x00, // version
  28067. 0x00, 0x00, 0x01, // flags
  28068. 0x00, 0x00, // graphicsmode
  28069. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  28070. ]);
  28071. })();
  28072. box = function box(type) {
  28073. var payload = [],
  28074. size = 0,
  28075. i,
  28076. result,
  28077. view;
  28078. for (i = 1; i < arguments.length; i++) {
  28079. payload.push(arguments[i]);
  28080. }
  28081. i = payload.length; // calculate the total size we need to allocate
  28082. while (i--) {
  28083. size += payload[i].byteLength;
  28084. }
  28085. result = new Uint8Array(size + 8);
  28086. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  28087. view.setUint32(0, result.byteLength);
  28088. result.set(type, 4); // copy the payload into the result
  28089. for (i = 0, size = 8; i < payload.length; i++) {
  28090. result.set(payload[i], size);
  28091. size += payload[i].byteLength;
  28092. }
  28093. return result;
  28094. };
  28095. dinf = function dinf() {
  28096. return box(types.dinf, box(types.dref, DREF));
  28097. };
  28098. esds = function esds(track) {
  28099. return box(types.esds, new Uint8Array([0x00, // version
  28100. 0x00, 0x00, 0x00, // flags
  28101. // ES_Descriptor
  28102. 0x03, // tag, ES_DescrTag
  28103. 0x19, // length
  28104. 0x00, 0x00, // ES_ID
  28105. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  28106. // DecoderConfigDescriptor
  28107. 0x04, // tag, DecoderConfigDescrTag
  28108. 0x11, // length
  28109. 0x40, // object type
  28110. 0x15, // streamType
  28111. 0x00, 0x06, 0x00, // bufferSizeDB
  28112. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  28113. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  28114. // DecoderSpecificInfo
  28115. 0x05, // tag, DecoderSpecificInfoTag
  28116. 0x02, // length
  28117. // ISO/IEC 14496-3, AudioSpecificConfig
  28118. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  28119. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  28120. ]));
  28121. };
  28122. ftyp = function ftyp() {
  28123. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  28124. };
  28125. hdlr = function hdlr(type) {
  28126. return box(types.hdlr, HDLR_TYPES[type]);
  28127. };
  28128. mdat = function mdat(data) {
  28129. return box(types.mdat, data);
  28130. };
  28131. mdhd = function mdhd(track) {
  28132. var result = new Uint8Array([0x00, // version 0
  28133. 0x00, 0x00, 0x00, // flags
  28134. 0x00, 0x00, 0x00, 0x02, // creation_time
  28135. 0x00, 0x00, 0x00, 0x03, // modification_time
  28136. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  28137. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  28138. 0x55, 0xc4, // 'und' language (undetermined)
  28139. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  28140. // defined. The sample rate can be parsed out of an ADTS header, for
  28141. // instance.
  28142. if (track.samplerate) {
  28143. result[12] = track.samplerate >>> 24 & 0xFF;
  28144. result[13] = track.samplerate >>> 16 & 0xFF;
  28145. result[14] = track.samplerate >>> 8 & 0xFF;
  28146. result[15] = track.samplerate & 0xFF;
  28147. }
  28148. return box(types.mdhd, result);
  28149. };
  28150. mdia = function mdia(track) {
  28151. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  28152. };
  28153. mfhd = function mfhd(sequenceNumber) {
  28154. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  28155. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  28156. ]));
  28157. };
  28158. minf = function minf(track) {
  28159. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  28160. };
  28161. moof = function moof(sequenceNumber, tracks) {
  28162. var trackFragments = [],
  28163. i = tracks.length; // build traf boxes for each track fragment
  28164. while (i--) {
  28165. trackFragments[i] = traf(tracks[i]);
  28166. }
  28167. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  28168. };
  28169. /**
  28170. * Returns a movie box.
  28171. * @param tracks {array} the tracks associated with this movie
  28172. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  28173. */
  28174. moov = function moov(tracks) {
  28175. var i = tracks.length,
  28176. boxes = [];
  28177. while (i--) {
  28178. boxes[i] = trak(tracks[i]);
  28179. }
  28180. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  28181. };
  28182. mvex = function mvex(tracks) {
  28183. var i = tracks.length,
  28184. boxes = [];
  28185. while (i--) {
  28186. boxes[i] = trex(tracks[i]);
  28187. }
  28188. return box.apply(null, [types.mvex].concat(boxes));
  28189. };
  28190. mvhd = function mvhd(duration) {
  28191. var bytes = new Uint8Array([0x00, // version 0
  28192. 0x00, 0x00, 0x00, // flags
  28193. 0x00, 0x00, 0x00, 0x01, // creation_time
  28194. 0x00, 0x00, 0x00, 0x02, // modification_time
  28195. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  28196. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  28197. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  28198. 0x01, 0x00, // 1.0 volume
  28199. 0x00, 0x00, // reserved
  28200. 0x00, 0x00, 0x00, 0x00, // reserved
  28201. 0x00, 0x00, 0x00, 0x00, // reserved
  28202. 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, // transformation: unity matrix
  28203. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  28204. 0xff, 0xff, 0xff, 0xff // next_track_ID
  28205. ]);
  28206. return box(types.mvhd, bytes);
  28207. };
  28208. sdtp = function sdtp(track) {
  28209. var samples = track.samples || [],
  28210. bytes = new Uint8Array(4 + samples.length),
  28211. flags,
  28212. i; // leave the full box header (4 bytes) all zero
  28213. // write the sample table
  28214. for (i = 0; i < samples.length; i++) {
  28215. flags = samples[i].flags;
  28216. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  28217. }
  28218. return box(types.sdtp, bytes);
  28219. };
  28220. stbl = function stbl(track) {
  28221. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  28222. };
  28223. (function () {
  28224. var videoSample, audioSample;
  28225. stsd = function stsd(track) {
  28226. return box(types.stsd, new Uint8Array([0x00, // version 0
  28227. 0x00, 0x00, 0x00, // flags
  28228. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  28229. };
  28230. videoSample = function videoSample(track) {
  28231. var sps = track.sps || [],
  28232. pps = track.pps || [],
  28233. sequenceParameterSets = [],
  28234. pictureParameterSets = [],
  28235. i,
  28236. avc1Box; // assemble the SPSs
  28237. for (i = 0; i < sps.length; i++) {
  28238. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  28239. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  28240. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  28241. } // assemble the PPSs
  28242. for (i = 0; i < pps.length; i++) {
  28243. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  28244. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  28245. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  28246. }
  28247. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  28248. 0x00, 0x01, // data_reference_index
  28249. 0x00, 0x00, // pre_defined
  28250. 0x00, 0x00, // reserved
  28251. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  28252. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  28253. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  28254. 0x00, 0x48, 0x00, 0x00, // horizresolution
  28255. 0x00, 0x48, 0x00, 0x00, // vertresolution
  28256. 0x00, 0x00, 0x00, 0x00, // reserved
  28257. 0x00, 0x01, // frame_count
  28258. 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, // compressorname
  28259. 0x00, 0x18, // depth = 24
  28260. 0x11, 0x11 // pre_defined = -1
  28261. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  28262. track.profileIdc, // AVCProfileIndication
  28263. track.profileCompatibility, // profile_compatibility
  28264. track.levelIdc, // AVCLevelIndication
  28265. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  28266. ].concat([sps.length], // numOfSequenceParameterSets
  28267. sequenceParameterSets, // "SPS"
  28268. [pps.length], // numOfPictureParameterSets
  28269. pictureParameterSets // "PPS"
  28270. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  28271. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  28272. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  28273. ]))];
  28274. if (track.sarRatio) {
  28275. var hSpacing = track.sarRatio[0],
  28276. vSpacing = track.sarRatio[1];
  28277. 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])));
  28278. }
  28279. return box.apply(null, avc1Box);
  28280. };
  28281. audioSample = function audioSample(track) {
  28282. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  28283. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  28284. 0x00, 0x01, // data_reference_index
  28285. // AudioSampleEntry, ISO/IEC 14496-12
  28286. 0x00, 0x00, 0x00, 0x00, // reserved
  28287. 0x00, 0x00, 0x00, 0x00, // reserved
  28288. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  28289. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  28290. 0x00, 0x00, // pre_defined
  28291. 0x00, 0x00, // reserved
  28292. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  28293. // MP4AudioSampleEntry, ISO/IEC 14496-14
  28294. ]), esds(track));
  28295. };
  28296. })();
  28297. tkhd = function tkhd(track) {
  28298. var result = new Uint8Array([0x00, // version 0
  28299. 0x00, 0x00, 0x07, // flags
  28300. 0x00, 0x00, 0x00, 0x00, // creation_time
  28301. 0x00, 0x00, 0x00, 0x00, // modification_time
  28302. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  28303. 0x00, 0x00, 0x00, 0x00, // reserved
  28304. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  28305. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  28306. 0x00, 0x00, // layer
  28307. 0x00, 0x00, // alternate_group
  28308. 0x01, 0x00, // non-audio track volume
  28309. 0x00, 0x00, // reserved
  28310. 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, // transformation: unity matrix
  28311. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  28312. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  28313. ]);
  28314. return box(types.tkhd, result);
  28315. };
  28316. /**
  28317. * Generate a track fragment (traf) box. A traf box collects metadata
  28318. * about tracks in a movie fragment (moof) box.
  28319. */
  28320. traf = function traf(track) {
  28321. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  28322. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  28323. 0x00, 0x00, 0x3a, // flags
  28324. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  28325. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  28326. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  28327. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  28328. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  28329. ]));
  28330. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  28331. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  28332. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  28333. 0x00, 0x00, 0x00, // flags
  28334. // baseMediaDecodeTime
  28335. 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
  28336. // the containing moof to the first payload byte of the associated
  28337. // mdat
  28338. dataOffset = 32 + // tfhd
  28339. 20 + // tfdt
  28340. 8 + // traf header
  28341. 16 + // mfhd
  28342. 8 + // moof header
  28343. 8; // mdat header
  28344. // audio tracks require less metadata
  28345. if (track.type === 'audio') {
  28346. trackFragmentRun = trun$1(track, dataOffset);
  28347. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  28348. } // video tracks should contain an independent and disposable samples
  28349. // box (sdtp)
  28350. // generate one and adjust offsets to match
  28351. sampleDependencyTable = sdtp(track);
  28352. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  28353. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  28354. };
  28355. /**
  28356. * Generate a track box.
  28357. * @param track {object} a track definition
  28358. * @return {Uint8Array} the track box
  28359. */
  28360. trak = function trak(track) {
  28361. track.duration = track.duration || 0xffffffff;
  28362. return box(types.trak, tkhd(track), mdia(track));
  28363. };
  28364. trex = function trex(track) {
  28365. var result = new Uint8Array([0x00, // version 0
  28366. 0x00, 0x00, 0x00, // flags
  28367. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  28368. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  28369. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  28370. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  28371. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  28372. ]); // the last two bytes of default_sample_flags is the sample
  28373. // degradation priority, a hint about the importance of this sample
  28374. // relative to others. Lower the degradation priority for all sample
  28375. // types other than video.
  28376. if (track.type !== 'video') {
  28377. result[result.length - 1] = 0x00;
  28378. }
  28379. return box(types.trex, result);
  28380. };
  28381. (function () {
  28382. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  28383. // duration is present for the first sample, it will be present for
  28384. // all subsequent samples.
  28385. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  28386. trunHeader = function trunHeader(samples, offset) {
  28387. var durationPresent = 0,
  28388. sizePresent = 0,
  28389. flagsPresent = 0,
  28390. compositionTimeOffset = 0; // trun flag constants
  28391. if (samples.length) {
  28392. if (samples[0].duration !== undefined) {
  28393. durationPresent = 0x1;
  28394. }
  28395. if (samples[0].size !== undefined) {
  28396. sizePresent = 0x2;
  28397. }
  28398. if (samples[0].flags !== undefined) {
  28399. flagsPresent = 0x4;
  28400. }
  28401. if (samples[0].compositionTimeOffset !== undefined) {
  28402. compositionTimeOffset = 0x8;
  28403. }
  28404. }
  28405. return [0x00, // version 0
  28406. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  28407. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  28408. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  28409. ];
  28410. };
  28411. videoTrun = function videoTrun(track, offset) {
  28412. var bytesOffest, bytes, header, samples, sample, i;
  28413. samples = track.samples || [];
  28414. offset += 8 + 12 + 16 * samples.length;
  28415. header = trunHeader(samples, offset);
  28416. bytes = new Uint8Array(header.length + samples.length * 16);
  28417. bytes.set(header);
  28418. bytesOffest = header.length;
  28419. for (i = 0; i < samples.length; i++) {
  28420. sample = samples[i];
  28421. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28422. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28423. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28424. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28425. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28426. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28427. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28428. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28429. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  28430. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  28431. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  28432. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  28433. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  28434. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  28435. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  28436. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  28437. }
  28438. return box(types.trun, bytes);
  28439. };
  28440. audioTrun = function audioTrun(track, offset) {
  28441. var bytes, bytesOffest, header, samples, sample, i;
  28442. samples = track.samples || [];
  28443. offset += 8 + 12 + 8 * samples.length;
  28444. header = trunHeader(samples, offset);
  28445. bytes = new Uint8Array(header.length + samples.length * 8);
  28446. bytes.set(header);
  28447. bytesOffest = header.length;
  28448. for (i = 0; i < samples.length; i++) {
  28449. sample = samples[i];
  28450. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  28451. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  28452. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  28453. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  28454. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  28455. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  28456. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  28457. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  28458. }
  28459. return box(types.trun, bytes);
  28460. };
  28461. trun$1 = function trun(track, offset) {
  28462. if (track.type === 'audio') {
  28463. return audioTrun(track, offset);
  28464. }
  28465. return videoTrun(track, offset);
  28466. };
  28467. })();
  28468. var mp4Generator = {
  28469. ftyp: ftyp,
  28470. mdat: mdat,
  28471. moof: moof,
  28472. moov: moov,
  28473. initSegment: function initSegment(tracks) {
  28474. var fileType = ftyp(),
  28475. movie = moov(tracks),
  28476. result;
  28477. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  28478. result.set(fileType);
  28479. result.set(movie, fileType.byteLength);
  28480. return result;
  28481. }
  28482. };
  28483. /**
  28484. * mux.js
  28485. *
  28486. * Copyright (c) Brightcove
  28487. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28488. */
  28489. // Convert an array of nal units into an array of frames with each frame being
  28490. // composed of the nal units that make up that frame
  28491. // Also keep track of cummulative data about the frame from the nal units such
  28492. // as the frame duration, starting pts, etc.
  28493. var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
  28494. var i,
  28495. currentNal,
  28496. currentFrame = [],
  28497. frames = []; // TODO added for LHLS, make sure this is OK
  28498. frames.byteLength = 0;
  28499. frames.nalCount = 0;
  28500. frames.duration = 0;
  28501. currentFrame.byteLength = 0;
  28502. for (i = 0; i < nalUnits.length; i++) {
  28503. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  28504. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  28505. // Since the very first nal unit is expected to be an AUD
  28506. // only push to the frames array when currentFrame is not empty
  28507. if (currentFrame.length) {
  28508. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  28509. frames.byteLength += currentFrame.byteLength;
  28510. frames.nalCount += currentFrame.length;
  28511. frames.duration += currentFrame.duration;
  28512. frames.push(currentFrame);
  28513. }
  28514. currentFrame = [currentNal];
  28515. currentFrame.byteLength = currentNal.data.byteLength;
  28516. currentFrame.pts = currentNal.pts;
  28517. currentFrame.dts = currentNal.dts;
  28518. } else {
  28519. // Specifically flag key frames for ease of use later
  28520. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  28521. currentFrame.keyFrame = true;
  28522. }
  28523. currentFrame.duration = currentNal.dts - currentFrame.dts;
  28524. currentFrame.byteLength += currentNal.data.byteLength;
  28525. currentFrame.push(currentNal);
  28526. }
  28527. } // For the last frame, use the duration of the previous frame if we
  28528. // have nothing better to go on
  28529. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  28530. currentFrame.duration = frames[frames.length - 1].duration;
  28531. } // Push the final frame
  28532. // TODO added for LHLS, make sure this is OK
  28533. frames.byteLength += currentFrame.byteLength;
  28534. frames.nalCount += currentFrame.length;
  28535. frames.duration += currentFrame.duration;
  28536. frames.push(currentFrame);
  28537. return frames;
  28538. }; // Convert an array of frames into an array of Gop with each Gop being composed
  28539. // of the frames that make up that Gop
  28540. // Also keep track of cummulative data about the Gop from the frames such as the
  28541. // Gop duration, starting pts, etc.
  28542. var groupFramesIntoGops = function groupFramesIntoGops(frames) {
  28543. var i,
  28544. currentFrame,
  28545. currentGop = [],
  28546. gops = []; // We must pre-set some of the values on the Gop since we
  28547. // keep running totals of these values
  28548. currentGop.byteLength = 0;
  28549. currentGop.nalCount = 0;
  28550. currentGop.duration = 0;
  28551. currentGop.pts = frames[0].pts;
  28552. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  28553. gops.byteLength = 0;
  28554. gops.nalCount = 0;
  28555. gops.duration = 0;
  28556. gops.pts = frames[0].pts;
  28557. gops.dts = frames[0].dts;
  28558. for (i = 0; i < frames.length; i++) {
  28559. currentFrame = frames[i];
  28560. if (currentFrame.keyFrame) {
  28561. // Since the very first frame is expected to be an keyframe
  28562. // only push to the gops array when currentGop is not empty
  28563. if (currentGop.length) {
  28564. gops.push(currentGop);
  28565. gops.byteLength += currentGop.byteLength;
  28566. gops.nalCount += currentGop.nalCount;
  28567. gops.duration += currentGop.duration;
  28568. }
  28569. currentGop = [currentFrame];
  28570. currentGop.nalCount = currentFrame.length;
  28571. currentGop.byteLength = currentFrame.byteLength;
  28572. currentGop.pts = currentFrame.pts;
  28573. currentGop.dts = currentFrame.dts;
  28574. currentGop.duration = currentFrame.duration;
  28575. } else {
  28576. currentGop.duration += currentFrame.duration;
  28577. currentGop.nalCount += currentFrame.length;
  28578. currentGop.byteLength += currentFrame.byteLength;
  28579. currentGop.push(currentFrame);
  28580. }
  28581. }
  28582. if (gops.length && currentGop.duration <= 0) {
  28583. currentGop.duration = gops[gops.length - 1].duration;
  28584. }
  28585. gops.byteLength += currentGop.byteLength;
  28586. gops.nalCount += currentGop.nalCount;
  28587. gops.duration += currentGop.duration; // push the final Gop
  28588. gops.push(currentGop);
  28589. return gops;
  28590. };
  28591. /*
  28592. * Search for the first keyframe in the GOPs and throw away all frames
  28593. * until that keyframe. Then extend the duration of the pulled keyframe
  28594. * and pull the PTS and DTS of the keyframe so that it covers the time
  28595. * range of the frames that were disposed.
  28596. *
  28597. * @param {Array} gops video GOPs
  28598. * @returns {Array} modified video GOPs
  28599. */
  28600. var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
  28601. var currentGop;
  28602. if (!gops[0][0].keyFrame && gops.length > 1) {
  28603. // Remove the first GOP
  28604. currentGop = gops.shift();
  28605. gops.byteLength -= currentGop.byteLength;
  28606. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  28607. // first gop to cover the time period of the
  28608. // frames we just removed
  28609. gops[0][0].dts = currentGop.dts;
  28610. gops[0][0].pts = currentGop.pts;
  28611. gops[0][0].duration += currentGop.duration;
  28612. }
  28613. return gops;
  28614. };
  28615. /**
  28616. * Default sample object
  28617. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  28618. */
  28619. var createDefaultSample = function createDefaultSample() {
  28620. return {
  28621. size: 0,
  28622. flags: {
  28623. isLeading: 0,
  28624. dependsOn: 1,
  28625. isDependedOn: 0,
  28626. hasRedundancy: 0,
  28627. degradationPriority: 0,
  28628. isNonSyncSample: 1
  28629. }
  28630. };
  28631. };
  28632. /*
  28633. * Collates information from a video frame into an object for eventual
  28634. * entry into an MP4 sample table.
  28635. *
  28636. * @param {Object} frame the video frame
  28637. * @param {Number} dataOffset the byte offset to position the sample
  28638. * @return {Object} object containing sample table info for a frame
  28639. */
  28640. var sampleForFrame = function sampleForFrame(frame, dataOffset) {
  28641. var sample = createDefaultSample();
  28642. sample.dataOffset = dataOffset;
  28643. sample.compositionTimeOffset = frame.pts - frame.dts;
  28644. sample.duration = frame.duration;
  28645. sample.size = 4 * frame.length; // Space for nal unit size
  28646. sample.size += frame.byteLength;
  28647. if (frame.keyFrame) {
  28648. sample.flags.dependsOn = 2;
  28649. sample.flags.isNonSyncSample = 0;
  28650. }
  28651. return sample;
  28652. }; // generate the track's sample table from an array of gops
  28653. var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
  28654. var h,
  28655. i,
  28656. sample,
  28657. currentGop,
  28658. currentFrame,
  28659. dataOffset = baseDataOffset || 0,
  28660. samples = [];
  28661. for (h = 0; h < gops.length; h++) {
  28662. currentGop = gops[h];
  28663. for (i = 0; i < currentGop.length; i++) {
  28664. currentFrame = currentGop[i];
  28665. sample = sampleForFrame(currentFrame, dataOffset);
  28666. dataOffset += sample.size;
  28667. samples.push(sample);
  28668. }
  28669. }
  28670. return samples;
  28671. }; // generate the track's raw mdat data from an array of gops
  28672. var concatenateNalData = function concatenateNalData(gops) {
  28673. var h,
  28674. i,
  28675. j,
  28676. currentGop,
  28677. currentFrame,
  28678. currentNal,
  28679. dataOffset = 0,
  28680. nalsByteLength = gops.byteLength,
  28681. numberOfNals = gops.nalCount,
  28682. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28683. data = new Uint8Array(totalByteLength),
  28684. view = new DataView(data.buffer); // For each Gop..
  28685. for (h = 0; h < gops.length; h++) {
  28686. currentGop = gops[h]; // For each Frame..
  28687. for (i = 0; i < currentGop.length; i++) {
  28688. currentFrame = currentGop[i]; // For each NAL..
  28689. for (j = 0; j < currentFrame.length; j++) {
  28690. currentNal = currentFrame[j];
  28691. view.setUint32(dataOffset, currentNal.data.byteLength);
  28692. dataOffset += 4;
  28693. data.set(currentNal.data, dataOffset);
  28694. dataOffset += currentNal.data.byteLength;
  28695. }
  28696. }
  28697. }
  28698. return data;
  28699. }; // generate the track's sample table from a frame
  28700. var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
  28701. var sample,
  28702. dataOffset = baseDataOffset || 0,
  28703. samples = [];
  28704. sample = sampleForFrame(frame, dataOffset);
  28705. samples.push(sample);
  28706. return samples;
  28707. }; // generate the track's raw mdat data from a frame
  28708. var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
  28709. var i,
  28710. currentNal,
  28711. dataOffset = 0,
  28712. nalsByteLength = frame.byteLength,
  28713. numberOfNals = frame.length,
  28714. totalByteLength = nalsByteLength + 4 * numberOfNals,
  28715. data = new Uint8Array(totalByteLength),
  28716. view = new DataView(data.buffer); // For each NAL..
  28717. for (i = 0; i < frame.length; i++) {
  28718. currentNal = frame[i];
  28719. view.setUint32(dataOffset, currentNal.data.byteLength);
  28720. dataOffset += 4;
  28721. data.set(currentNal.data, dataOffset);
  28722. dataOffset += currentNal.data.byteLength;
  28723. }
  28724. return data;
  28725. };
  28726. var frameUtils = {
  28727. groupNalsIntoFrames: groupNalsIntoFrames,
  28728. groupFramesIntoGops: groupFramesIntoGops,
  28729. extendFirstKeyFrame: extendFirstKeyFrame,
  28730. generateSampleTable: generateSampleTable$1,
  28731. concatenateNalData: concatenateNalData,
  28732. generateSampleTableForFrame: generateSampleTableForFrame,
  28733. concatenateNalDataForFrame: concatenateNalDataForFrame
  28734. };
  28735. /**
  28736. * mux.js
  28737. *
  28738. * Copyright (c) Brightcove
  28739. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28740. */
  28741. var highPrefix = [33, 16, 5, 32, 164, 27];
  28742. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  28743. var zeroFill = function zeroFill(count) {
  28744. var a = [];
  28745. while (count--) {
  28746. a.push(0);
  28747. }
  28748. return a;
  28749. };
  28750. var makeTable = function makeTable(metaTable) {
  28751. return Object.keys(metaTable).reduce(function (obj, key) {
  28752. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  28753. return arr.concat(part);
  28754. }, []));
  28755. return obj;
  28756. }, {});
  28757. };
  28758. var silence;
  28759. var silence_1 = function silence_1() {
  28760. if (!silence) {
  28761. // Frames-of-silence to use for filling in missing AAC frames
  28762. var coneOfSilence = {
  28763. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  28764. 88200: [highPrefix, [231], zeroFill(170), [56]],
  28765. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  28766. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  28767. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  28768. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  28769. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  28770. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  28771. 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]],
  28772. 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]],
  28773. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  28774. };
  28775. silence = makeTable(coneOfSilence);
  28776. }
  28777. return silence;
  28778. };
  28779. /**
  28780. * mux.js
  28781. *
  28782. * Copyright (c) Brightcove
  28783. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28784. */
  28785. var ONE_SECOND_IN_TS$4 = 90000,
  28786. // 90kHz clock
  28787. secondsToVideoTs,
  28788. secondsToAudioTs,
  28789. videoTsToSeconds,
  28790. audioTsToSeconds,
  28791. audioTsToVideoTs,
  28792. videoTsToAudioTs,
  28793. metadataTsToSeconds;
  28794. secondsToVideoTs = function secondsToVideoTs(seconds) {
  28795. return seconds * ONE_SECOND_IN_TS$4;
  28796. };
  28797. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  28798. return seconds * sampleRate;
  28799. };
  28800. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  28801. return timestamp / ONE_SECOND_IN_TS$4;
  28802. };
  28803. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  28804. return timestamp / sampleRate;
  28805. };
  28806. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  28807. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  28808. };
  28809. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  28810. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  28811. };
  28812. /**
  28813. * Adjust ID3 tag or caption timing information by the timeline pts values
  28814. * (if keepOriginalTimestamps is false) and convert to seconds
  28815. */
  28816. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  28817. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  28818. };
  28819. var clock = {
  28820. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  28821. secondsToVideoTs: secondsToVideoTs,
  28822. secondsToAudioTs: secondsToAudioTs,
  28823. videoTsToSeconds: videoTsToSeconds,
  28824. audioTsToSeconds: audioTsToSeconds,
  28825. audioTsToVideoTs: audioTsToVideoTs,
  28826. videoTsToAudioTs: videoTsToAudioTs,
  28827. metadataTsToSeconds: metadataTsToSeconds
  28828. };
  28829. /**
  28830. * mux.js
  28831. *
  28832. * Copyright (c) Brightcove
  28833. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28834. */
  28835. /**
  28836. * Sum the `byteLength` properties of the data in each AAC frame
  28837. */
  28838. var sumFrameByteLengths = function sumFrameByteLengths(array) {
  28839. var i,
  28840. currentObj,
  28841. sum = 0; // sum the byteLength's all each nal unit in the frame
  28842. for (i = 0; i < array.length; i++) {
  28843. currentObj = array[i];
  28844. sum += currentObj.data.byteLength;
  28845. }
  28846. return sum;
  28847. }; // Possibly pad (prefix) the audio track with silence if appending this track
  28848. // would lead to the introduction of a gap in the audio buffer
  28849. var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  28850. var baseMediaDecodeTimeTs,
  28851. frameDuration = 0,
  28852. audioGapDuration = 0,
  28853. audioFillFrameCount = 0,
  28854. audioFillDuration = 0,
  28855. silentFrame,
  28856. i,
  28857. firstFrame;
  28858. if (!frames.length) {
  28859. return;
  28860. }
  28861. baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  28862. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  28863. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  28864. // insert the shortest possible amount (audio gap or audio to video gap)
  28865. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  28866. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  28867. audioFillDuration = audioFillFrameCount * frameDuration;
  28868. } // don't attempt to fill gaps smaller than a single frame or larger
  28869. // than a half second
  28870. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  28871. return;
  28872. }
  28873. silentFrame = silence_1()[track.samplerate];
  28874. if (!silentFrame) {
  28875. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  28876. // from the content instead
  28877. silentFrame = frames[0].data;
  28878. }
  28879. for (i = 0; i < audioFillFrameCount; i++) {
  28880. firstFrame = frames[0];
  28881. frames.splice(0, 0, {
  28882. data: silentFrame,
  28883. dts: firstFrame.dts - frameDuration,
  28884. pts: firstFrame.pts - frameDuration
  28885. });
  28886. }
  28887. track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  28888. return audioFillDuration;
  28889. }; // If the audio segment extends before the earliest allowed dts
  28890. // value, remove AAC frames until starts at or after the earliest
  28891. // allowed DTS so that we don't end up with a negative baseMedia-
  28892. // DecodeTime for the audio track
  28893. var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
  28894. if (track.minSegmentDts >= earliestAllowedDts) {
  28895. return adtsFrames;
  28896. } // We will need to recalculate the earliest segment Dts
  28897. track.minSegmentDts = Infinity;
  28898. return adtsFrames.filter(function (currentFrame) {
  28899. // If this is an allowed frame, keep it and record it's Dts
  28900. if (currentFrame.dts >= earliestAllowedDts) {
  28901. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  28902. track.minSegmentPts = track.minSegmentDts;
  28903. return true;
  28904. } // Otherwise, discard it
  28905. return false;
  28906. });
  28907. }; // generate the track's raw mdat data from an array of frames
  28908. var generateSampleTable = function generateSampleTable(frames) {
  28909. var i,
  28910. currentFrame,
  28911. samples = [];
  28912. for (i = 0; i < frames.length; i++) {
  28913. currentFrame = frames[i];
  28914. samples.push({
  28915. size: currentFrame.data.byteLength,
  28916. duration: 1024 // For AAC audio, all samples contain 1024 samples
  28917. });
  28918. }
  28919. return samples;
  28920. }; // generate the track's sample table from an array of frames
  28921. var concatenateFrameData = function concatenateFrameData(frames) {
  28922. var i,
  28923. currentFrame,
  28924. dataOffset = 0,
  28925. data = new Uint8Array(sumFrameByteLengths(frames));
  28926. for (i = 0; i < frames.length; i++) {
  28927. currentFrame = frames[i];
  28928. data.set(currentFrame.data, dataOffset);
  28929. dataOffset += currentFrame.data.byteLength;
  28930. }
  28931. return data;
  28932. };
  28933. var audioFrameUtils = {
  28934. prefixWithSilence: prefixWithSilence,
  28935. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  28936. generateSampleTable: generateSampleTable,
  28937. concatenateFrameData: concatenateFrameData
  28938. };
  28939. /**
  28940. * mux.js
  28941. *
  28942. * Copyright (c) Brightcove
  28943. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  28944. */
  28945. var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
  28946. /**
  28947. * Store information about the start and end of the track and the
  28948. * duration for each frame/sample we process in order to calculate
  28949. * the baseMediaDecodeTime
  28950. */
  28951. var collectDtsInfo = function collectDtsInfo(track, data) {
  28952. if (typeof data.pts === 'number') {
  28953. if (track.timelineStartInfo.pts === undefined) {
  28954. track.timelineStartInfo.pts = data.pts;
  28955. }
  28956. if (track.minSegmentPts === undefined) {
  28957. track.minSegmentPts = data.pts;
  28958. } else {
  28959. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  28960. }
  28961. if (track.maxSegmentPts === undefined) {
  28962. track.maxSegmentPts = data.pts;
  28963. } else {
  28964. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  28965. }
  28966. }
  28967. if (typeof data.dts === 'number') {
  28968. if (track.timelineStartInfo.dts === undefined) {
  28969. track.timelineStartInfo.dts = data.dts;
  28970. }
  28971. if (track.minSegmentDts === undefined) {
  28972. track.minSegmentDts = data.dts;
  28973. } else {
  28974. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  28975. }
  28976. if (track.maxSegmentDts === undefined) {
  28977. track.maxSegmentDts = data.dts;
  28978. } else {
  28979. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  28980. }
  28981. }
  28982. };
  28983. /**
  28984. * Clear values used to calculate the baseMediaDecodeTime between
  28985. * tracks
  28986. */
  28987. var clearDtsInfo = function clearDtsInfo(track) {
  28988. delete track.minSegmentDts;
  28989. delete track.maxSegmentDts;
  28990. delete track.minSegmentPts;
  28991. delete track.maxSegmentPts;
  28992. };
  28993. /**
  28994. * Calculate the track's baseMediaDecodeTime based on the earliest
  28995. * DTS the transmuxer has ever seen and the minimum DTS for the
  28996. * current track
  28997. * @param track {object} track metadata configuration
  28998. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  28999. * in the source; false to adjust the first segment to start at 0.
  29000. */
  29001. var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
  29002. var baseMediaDecodeTime,
  29003. scale,
  29004. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  29005. if (!keepOriginalTimestamps) {
  29006. minSegmentDts -= track.timelineStartInfo.dts;
  29007. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  29008. // we want the start of the first segment to be placed
  29009. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  29010. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  29011. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  29012. if (track.type === 'audio') {
  29013. // Audio has a different clock equal to the sampling_rate so we need to
  29014. // scale the PTS values into the clock rate of the track
  29015. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  29016. baseMediaDecodeTime *= scale;
  29017. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  29018. }
  29019. return baseMediaDecodeTime;
  29020. };
  29021. var trackDecodeInfo = {
  29022. clearDtsInfo: clearDtsInfo,
  29023. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  29024. collectDtsInfo: collectDtsInfo
  29025. };
  29026. /**
  29027. * mux.js
  29028. *
  29029. * Copyright (c) Brightcove
  29030. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  29031. *
  29032. * Reads in-band caption information from a video elementary
  29033. * stream. Captions must follow the CEA-708 standard for injection
  29034. * into an MPEG-2 transport streams.
  29035. * @see https://en.wikipedia.org/wiki/CEA-708
  29036. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  29037. */
  29038. // payload type field to indicate how they are to be
  29039. // interpreted. CEAS-708 caption content is always transmitted with
  29040. // payload type 0x04.
  29041. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  29042. RBSP_TRAILING_BITS = 128;
  29043. /**
  29044. * Parse a supplemental enhancement information (SEI) NAL unit.
  29045. * Stops parsing once a message of type ITU T T35 has been found.
  29046. *
  29047. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  29048. * @return {object} the parsed SEI payload
  29049. * @see Rec. ITU-T H.264, 7.3.2.3.1
  29050. */
  29051. var parseSei = function parseSei(bytes) {
  29052. var i = 0,
  29053. result = {
  29054. payloadType: -1,
  29055. payloadSize: 0
  29056. },
  29057. payloadType = 0,
  29058. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  29059. while (i < bytes.byteLength) {
  29060. // stop once we have hit the end of the sei_rbsp
  29061. if (bytes[i] === RBSP_TRAILING_BITS) {
  29062. break;
  29063. } // Parse payload type
  29064. while (bytes[i] === 0xFF) {
  29065. payloadType += 255;
  29066. i++;
  29067. }
  29068. payloadType += bytes[i++]; // Parse payload size
  29069. while (bytes[i] === 0xFF) {
  29070. payloadSize += 255;
  29071. i++;
  29072. }
  29073. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  29074. // there can only ever be one caption message in a frame's sei
  29075. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  29076. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  29077. if (userIdentifier === 'GA94') {
  29078. result.payloadType = payloadType;
  29079. result.payloadSize = payloadSize;
  29080. result.payload = bytes.subarray(i, i + payloadSize);
  29081. break;
  29082. } else {
  29083. result.payload = void 0;
  29084. }
  29085. } // skip the payload and parse the next message
  29086. i += payloadSize;
  29087. payloadType = 0;
  29088. payloadSize = 0;
  29089. }
  29090. return result;
  29091. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  29092. var parseUserData = function parseUserData(sei) {
  29093. // itu_t_t35_contry_code must be 181 (United States) for
  29094. // captions
  29095. if (sei.payload[0] !== 181) {
  29096. return null;
  29097. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  29098. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  29099. return null;
  29100. } // the user_identifier should be "GA94" to indicate ATSC1 data
  29101. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  29102. return null;
  29103. } // finally, user_data_type_code should be 0x03 for caption data
  29104. if (sei.payload[7] !== 0x03) {
  29105. return null;
  29106. } // return the user_data_type_structure and strip the trailing
  29107. // marker bits
  29108. return sei.payload.subarray(8, sei.payload.length - 1);
  29109. }; // see CEA-708-D, section 4.4
  29110. var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
  29111. var results = [],
  29112. i,
  29113. count,
  29114. offset,
  29115. data; // if this is just filler, return immediately
  29116. if (!(userData[0] & 0x40)) {
  29117. return results;
  29118. } // parse out the cc_data_1 and cc_data_2 fields
  29119. count = userData[0] & 0x1f;
  29120. for (i = 0; i < count; i++) {
  29121. offset = i * 3;
  29122. data = {
  29123. type: userData[offset + 2] & 0x03,
  29124. pts: pts
  29125. }; // capture cc data when cc_valid is 1
  29126. if (userData[offset + 2] & 0x04) {
  29127. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  29128. results.push(data);
  29129. }
  29130. }
  29131. return results;
  29132. };
  29133. var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
  29134. var length = data.byteLength,
  29135. emulationPreventionBytesPositions = [],
  29136. i = 1,
  29137. newLength,
  29138. newData; // Find all `Emulation Prevention Bytes`
  29139. while (i < length - 2) {
  29140. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  29141. emulationPreventionBytesPositions.push(i + 2);
  29142. i += 2;
  29143. } else {
  29144. i++;
  29145. }
  29146. } // If no Emulation Prevention Bytes were found just return the original
  29147. // array
  29148. if (emulationPreventionBytesPositions.length === 0) {
  29149. return data;
  29150. } // Create a new array to hold the NAL unit data
  29151. newLength = length - emulationPreventionBytesPositions.length;
  29152. newData = new Uint8Array(newLength);
  29153. var sourceIndex = 0;
  29154. for (i = 0; i < newLength; sourceIndex++, i++) {
  29155. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  29156. // Skip this byte
  29157. sourceIndex++; // Remove this position index
  29158. emulationPreventionBytesPositions.shift();
  29159. }
  29160. newData[i] = data[sourceIndex];
  29161. }
  29162. return newData;
  29163. }; // exports
  29164. var captionPacketParser = {
  29165. parseSei: parseSei,
  29166. parseUserData: parseUserData,
  29167. parseCaptionPackets: parseCaptionPackets,
  29168. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  29169. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  29170. }; // Link To Transport
  29171. // -----------------
  29172. var CaptionStream$1 = function CaptionStream(options) {
  29173. options = options || {};
  29174. CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
  29175. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  29176. this.captionPackets_ = [];
  29177. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  29178. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  29179. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  29180. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  29181. ];
  29182. if (this.parse708captions_) {
  29183. this.cc708Stream_ = new Cea708Stream({
  29184. captionServices: options.captionServices
  29185. }); // eslint-disable-line no-use-before-define
  29186. }
  29187. this.reset(); // forward data and done events from CCs to this CaptionStream
  29188. this.ccStreams_.forEach(function (cc) {
  29189. cc.on('data', this.trigger.bind(this, 'data'));
  29190. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29191. cc.on('done', this.trigger.bind(this, 'done'));
  29192. }, this);
  29193. if (this.parse708captions_) {
  29194. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  29195. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  29196. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  29197. }
  29198. };
  29199. CaptionStream$1.prototype = new stream();
  29200. CaptionStream$1.prototype.push = function (event) {
  29201. var sei, userData, newCaptionPackets; // only examine SEI NALs
  29202. if (event.nalUnitType !== 'sei_rbsp') {
  29203. return;
  29204. } // parse the sei
  29205. sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
  29206. if (!sei.payload) {
  29207. return;
  29208. } // ignore everything but user_data_registered_itu_t_t35
  29209. if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
  29210. return;
  29211. } // parse out the user data payload
  29212. userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
  29213. if (!userData) {
  29214. return;
  29215. } // Sometimes, the same segment # will be downloaded twice. To stop the
  29216. // caption data from being processed twice, we track the latest dts we've
  29217. // received and ignore everything with a dts before that. However, since
  29218. // data for a specific dts can be split across packets on either side of
  29219. // a segment boundary, we need to make sure we *don't* ignore the packets
  29220. // from the *next* segment that have dts === this.latestDts_. By constantly
  29221. // tracking the number of packets received with dts === this.latestDts_, we
  29222. // know how many should be ignored once we start receiving duplicates.
  29223. if (event.dts < this.latestDts_) {
  29224. // We've started getting older data, so set the flag.
  29225. this.ignoreNextEqualDts_ = true;
  29226. return;
  29227. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  29228. this.numSameDts_--;
  29229. if (!this.numSameDts_) {
  29230. // We've received the last duplicate packet, time to start processing again
  29231. this.ignoreNextEqualDts_ = false;
  29232. }
  29233. return;
  29234. } // parse out CC data packets and save them for later
  29235. newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
  29236. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  29237. if (this.latestDts_ !== event.dts) {
  29238. this.numSameDts_ = 0;
  29239. }
  29240. this.numSameDts_++;
  29241. this.latestDts_ = event.dts;
  29242. };
  29243. CaptionStream$1.prototype.flushCCStreams = function (flushType) {
  29244. this.ccStreams_.forEach(function (cc) {
  29245. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  29246. }, this);
  29247. };
  29248. CaptionStream$1.prototype.flushStream = function (flushType) {
  29249. // make sure we actually parsed captions before proceeding
  29250. if (!this.captionPackets_.length) {
  29251. this.flushCCStreams(flushType);
  29252. return;
  29253. } // In Chrome, the Array#sort function is not stable so add a
  29254. // presortIndex that we can use to ensure we get a stable-sort
  29255. this.captionPackets_.forEach(function (elem, idx) {
  29256. elem.presortIndex = idx;
  29257. }); // sort caption byte-pairs based on their PTS values
  29258. this.captionPackets_.sort(function (a, b) {
  29259. if (a.pts === b.pts) {
  29260. return a.presortIndex - b.presortIndex;
  29261. }
  29262. return a.pts - b.pts;
  29263. });
  29264. this.captionPackets_.forEach(function (packet) {
  29265. if (packet.type < 2) {
  29266. // Dispatch packet to the right Cea608Stream
  29267. this.dispatchCea608Packet(packet);
  29268. } else {
  29269. // Dispatch packet to the Cea708Stream
  29270. this.dispatchCea708Packet(packet);
  29271. }
  29272. }, this);
  29273. this.captionPackets_.length = 0;
  29274. this.flushCCStreams(flushType);
  29275. };
  29276. CaptionStream$1.prototype.flush = function () {
  29277. return this.flushStream('flush');
  29278. }; // Only called if handling partial data
  29279. CaptionStream$1.prototype.partialFlush = function () {
  29280. return this.flushStream('partialFlush');
  29281. };
  29282. CaptionStream$1.prototype.reset = function () {
  29283. this.latestDts_ = null;
  29284. this.ignoreNextEqualDts_ = false;
  29285. this.numSameDts_ = 0;
  29286. this.activeCea608Channel_ = [null, null];
  29287. this.ccStreams_.forEach(function (ccStream) {
  29288. ccStream.reset();
  29289. });
  29290. }; // From the CEA-608 spec:
  29291. /*
  29292. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  29293. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  29294. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  29295. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  29296. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  29297. * to switch to captioning or Text.
  29298. */
  29299. // With that in mind, we ignore any data between an XDS control code and a
  29300. // subsequent closed-captioning control code.
  29301. CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
  29302. // NOTE: packet.type is the CEA608 field
  29303. if (this.setsTextOrXDSActive(packet)) {
  29304. this.activeCea608Channel_[packet.type] = null;
  29305. } else if (this.setsChannel1Active(packet)) {
  29306. this.activeCea608Channel_[packet.type] = 0;
  29307. } else if (this.setsChannel2Active(packet)) {
  29308. this.activeCea608Channel_[packet.type] = 1;
  29309. }
  29310. if (this.activeCea608Channel_[packet.type] === null) {
  29311. // If we haven't received anything to set the active channel, or the
  29312. // packets are Text/XDS data, discard the data; we don't want jumbled
  29313. // captions
  29314. return;
  29315. }
  29316. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  29317. };
  29318. CaptionStream$1.prototype.setsChannel1Active = function (packet) {
  29319. return (packet.ccData & 0x7800) === 0x1000;
  29320. };
  29321. CaptionStream$1.prototype.setsChannel2Active = function (packet) {
  29322. return (packet.ccData & 0x7800) === 0x1800;
  29323. };
  29324. CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
  29325. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  29326. };
  29327. CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
  29328. if (this.parse708captions_) {
  29329. this.cc708Stream_.push(packet);
  29330. }
  29331. }; // ----------------------
  29332. // Session to Application
  29333. // ----------------------
  29334. // This hash maps special and extended character codes to their
  29335. // proper Unicode equivalent. The first one-byte key is just a
  29336. // non-standard character code. The two-byte keys that follow are
  29337. // the extended CEA708 character codes, along with the preceding
  29338. // 0x10 extended character byte to distinguish these codes from
  29339. // non-extended character codes. Every CEA708 character code that
  29340. // is not in this object maps directly to a standard unicode
  29341. // character code.
  29342. // The transparent space and non-breaking transparent space are
  29343. // technically not fully supported since there is no code to
  29344. // make them transparent, so they have normal non-transparent
  29345. // stand-ins.
  29346. // The special closed caption (CC) character isn't a standard
  29347. // unicode character, so a fairly similar unicode character was
  29348. // chosen in it's place.
  29349. var CHARACTER_TRANSLATION_708 = {
  29350. 0x7f: 0x266a,
  29351. // ♪
  29352. 0x1020: 0x20,
  29353. // Transparent Space
  29354. 0x1021: 0xa0,
  29355. // Nob-breaking Transparent Space
  29356. 0x1025: 0x2026,
  29357. // …
  29358. 0x102a: 0x0160,
  29359. // Š
  29360. 0x102c: 0x0152,
  29361. // Œ
  29362. 0x1030: 0x2588,
  29363. // █
  29364. 0x1031: 0x2018,
  29365. // ‘
  29366. 0x1032: 0x2019,
  29367. // ’
  29368. 0x1033: 0x201c,
  29369. // “
  29370. 0x1034: 0x201d,
  29371. // ”
  29372. 0x1035: 0x2022,
  29373. // •
  29374. 0x1039: 0x2122,
  29375. // ™
  29376. 0x103a: 0x0161,
  29377. // š
  29378. 0x103c: 0x0153,
  29379. // œ
  29380. 0x103d: 0x2120,
  29381. // ℠
  29382. 0x103f: 0x0178,
  29383. // Ÿ
  29384. 0x1076: 0x215b,
  29385. // ⅛
  29386. 0x1077: 0x215c,
  29387. // ⅜
  29388. 0x1078: 0x215d,
  29389. // ⅝
  29390. 0x1079: 0x215e,
  29391. // ⅞
  29392. 0x107a: 0x23d0,
  29393. // ⏐
  29394. 0x107b: 0x23a4,
  29395. // ⎤
  29396. 0x107c: 0x23a3,
  29397. // ⎣
  29398. 0x107d: 0x23af,
  29399. // ⎯
  29400. 0x107e: 0x23a6,
  29401. // ⎦
  29402. 0x107f: 0x23a1,
  29403. // ⎡
  29404. 0x10a0: 0x3138 // ㄸ (CC char)
  29405. };
  29406. var get708CharFromCode = function get708CharFromCode(code) {
  29407. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  29408. if (code & 0x1000 && code === newCode) {
  29409. // Invalid extended code
  29410. return '';
  29411. }
  29412. return String.fromCharCode(newCode);
  29413. };
  29414. var within708TextBlock = function within708TextBlock(b) {
  29415. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  29416. };
  29417. var Cea708Window = function Cea708Window(windowNum) {
  29418. this.windowNum = windowNum;
  29419. this.reset();
  29420. };
  29421. Cea708Window.prototype.reset = function () {
  29422. this.clearText();
  29423. this.pendingNewLine = false;
  29424. this.winAttr = {};
  29425. this.penAttr = {};
  29426. this.penLoc = {};
  29427. this.penColor = {}; // These default values are arbitrary,
  29428. // defineWindow will usually override them
  29429. this.visible = 0;
  29430. this.rowLock = 0;
  29431. this.columnLock = 0;
  29432. this.priority = 0;
  29433. this.relativePositioning = 0;
  29434. this.anchorVertical = 0;
  29435. this.anchorHorizontal = 0;
  29436. this.anchorPoint = 0;
  29437. this.rowCount = 1;
  29438. this.virtualRowCount = this.rowCount + 1;
  29439. this.columnCount = 41;
  29440. this.windowStyle = 0;
  29441. this.penStyle = 0;
  29442. };
  29443. Cea708Window.prototype.getText = function () {
  29444. return this.rows.join('\n');
  29445. };
  29446. Cea708Window.prototype.clearText = function () {
  29447. this.rows = [''];
  29448. this.rowIdx = 0;
  29449. };
  29450. Cea708Window.prototype.newLine = function (pts) {
  29451. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  29452. this.beforeRowOverflow(pts);
  29453. }
  29454. if (this.rows.length > 0) {
  29455. this.rows.push('');
  29456. this.rowIdx++;
  29457. } // Show all virtual rows since there's no visible scrolling
  29458. while (this.rows.length > this.virtualRowCount) {
  29459. this.rows.shift();
  29460. this.rowIdx--;
  29461. }
  29462. };
  29463. Cea708Window.prototype.isEmpty = function () {
  29464. if (this.rows.length === 0) {
  29465. return true;
  29466. } else if (this.rows.length === 1) {
  29467. return this.rows[0] === '';
  29468. }
  29469. return false;
  29470. };
  29471. Cea708Window.prototype.addText = function (text) {
  29472. this.rows[this.rowIdx] += text;
  29473. };
  29474. Cea708Window.prototype.backspace = function () {
  29475. if (!this.isEmpty()) {
  29476. var row = this.rows[this.rowIdx];
  29477. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  29478. }
  29479. };
  29480. var Cea708Service = function Cea708Service(serviceNum, encoding, stream) {
  29481. this.serviceNum = serviceNum;
  29482. this.text = '';
  29483. this.currentWindow = new Cea708Window(-1);
  29484. this.windows = [];
  29485. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  29486. if (typeof encoding === 'string') {
  29487. this.createTextDecoder(encoding);
  29488. }
  29489. };
  29490. /**
  29491. * Initialize service windows
  29492. * Must be run before service use
  29493. *
  29494. * @param {Integer} pts PTS value
  29495. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  29496. */
  29497. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  29498. this.startPts = pts;
  29499. for (var win = 0; win < 8; win++) {
  29500. this.windows[win] = new Cea708Window(win);
  29501. if (typeof beforeRowOverflow === 'function') {
  29502. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  29503. }
  29504. }
  29505. };
  29506. /**
  29507. * Set current window of service to be affected by commands
  29508. *
  29509. * @param {Integer} windowNum Window number
  29510. */
  29511. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  29512. this.currentWindow = this.windows[windowNum];
  29513. };
  29514. /**
  29515. * Try to create a TextDecoder if it is natively supported
  29516. */
  29517. Cea708Service.prototype.createTextDecoder = function (encoding) {
  29518. if (typeof TextDecoder === 'undefined') {
  29519. this.stream.trigger('log', {
  29520. level: 'warn',
  29521. message: 'The `encoding` option is unsupported without TextDecoder support'
  29522. });
  29523. } else {
  29524. try {
  29525. this.textDecoder_ = new TextDecoder(encoding);
  29526. } catch (error) {
  29527. this.stream.trigger('log', {
  29528. level: 'warn',
  29529. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  29530. });
  29531. }
  29532. }
  29533. };
  29534. var Cea708Stream = function Cea708Stream(options) {
  29535. options = options || {};
  29536. Cea708Stream.prototype.init.call(this);
  29537. var self = this;
  29538. var captionServices = options.captionServices || {};
  29539. var captionServiceEncodings = {};
  29540. var serviceProps; // Get service encodings from captionServices option block
  29541. Object.keys(captionServices).forEach(function (serviceName) {
  29542. serviceProps = captionServices[serviceName];
  29543. if (/^SERVICE/.test(serviceName)) {
  29544. captionServiceEncodings[serviceName] = serviceProps.encoding;
  29545. }
  29546. });
  29547. this.serviceEncodings = captionServiceEncodings;
  29548. this.current708Packet = null;
  29549. this.services = {};
  29550. this.push = function (packet) {
  29551. if (packet.type === 3) {
  29552. // 708 packet start
  29553. self.new708Packet();
  29554. self.add708Bytes(packet);
  29555. } else {
  29556. if (self.current708Packet === null) {
  29557. // This should only happen at the start of a file if there's no packet start.
  29558. self.new708Packet();
  29559. }
  29560. self.add708Bytes(packet);
  29561. }
  29562. };
  29563. };
  29564. Cea708Stream.prototype = new stream();
  29565. /**
  29566. * Push current 708 packet, create new 708 packet.
  29567. */
  29568. Cea708Stream.prototype.new708Packet = function () {
  29569. if (this.current708Packet !== null) {
  29570. this.push708Packet();
  29571. }
  29572. this.current708Packet = {
  29573. data: [],
  29574. ptsVals: []
  29575. };
  29576. };
  29577. /**
  29578. * Add pts and both bytes from packet into current 708 packet.
  29579. */
  29580. Cea708Stream.prototype.add708Bytes = function (packet) {
  29581. var data = packet.ccData;
  29582. var byte0 = data >>> 8;
  29583. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  29584. // that service blocks will always line up with byte pairs.
  29585. this.current708Packet.ptsVals.push(packet.pts);
  29586. this.current708Packet.data.push(byte0);
  29587. this.current708Packet.data.push(byte1);
  29588. };
  29589. /**
  29590. * Parse completed 708 packet into service blocks and push each service block.
  29591. */
  29592. Cea708Stream.prototype.push708Packet = function () {
  29593. var packet708 = this.current708Packet;
  29594. var packetData = packet708.data;
  29595. var serviceNum = null;
  29596. var blockSize = null;
  29597. var i = 0;
  29598. var b = packetData[i++];
  29599. packet708.seq = b >> 6;
  29600. packet708.sizeCode = b & 0x3f; // 0b00111111;
  29601. for (; i < packetData.length; i++) {
  29602. b = packetData[i++];
  29603. serviceNum = b >> 5;
  29604. blockSize = b & 0x1f; // 0b00011111
  29605. if (serviceNum === 7 && blockSize > 0) {
  29606. // Extended service num
  29607. b = packetData[i++];
  29608. serviceNum = b;
  29609. }
  29610. this.pushServiceBlock(serviceNum, i, blockSize);
  29611. if (blockSize > 0) {
  29612. i += blockSize - 1;
  29613. }
  29614. }
  29615. };
  29616. /**
  29617. * Parse service block, execute commands, read text.
  29618. *
  29619. * Note: While many of these commands serve important purposes,
  29620. * many others just parse out the parameters or attributes, but
  29621. * nothing is done with them because this is not a full and complete
  29622. * implementation of the entire 708 spec.
  29623. *
  29624. * @param {Integer} serviceNum Service number
  29625. * @param {Integer} start Start index of the 708 packet data
  29626. * @param {Integer} size Block size
  29627. */
  29628. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  29629. var b;
  29630. var i = start;
  29631. var packetData = this.current708Packet.data;
  29632. var service = this.services[serviceNum];
  29633. if (!service) {
  29634. service = this.initService(serviceNum, i);
  29635. }
  29636. for (; i < start + size && i < packetData.length; i++) {
  29637. b = packetData[i];
  29638. if (within708TextBlock(b)) {
  29639. i = this.handleText(i, service);
  29640. } else if (b === 0x18) {
  29641. i = this.multiByteCharacter(i, service);
  29642. } else if (b === 0x10) {
  29643. i = this.extendedCommands(i, service);
  29644. } else if (0x80 <= b && b <= 0x87) {
  29645. i = this.setCurrentWindow(i, service);
  29646. } else if (0x98 <= b && b <= 0x9f) {
  29647. i = this.defineWindow(i, service);
  29648. } else if (b === 0x88) {
  29649. i = this.clearWindows(i, service);
  29650. } else if (b === 0x8c) {
  29651. i = this.deleteWindows(i, service);
  29652. } else if (b === 0x89) {
  29653. i = this.displayWindows(i, service);
  29654. } else if (b === 0x8a) {
  29655. i = this.hideWindows(i, service);
  29656. } else if (b === 0x8b) {
  29657. i = this.toggleWindows(i, service);
  29658. } else if (b === 0x97) {
  29659. i = this.setWindowAttributes(i, service);
  29660. } else if (b === 0x90) {
  29661. i = this.setPenAttributes(i, service);
  29662. } else if (b === 0x91) {
  29663. i = this.setPenColor(i, service);
  29664. } else if (b === 0x92) {
  29665. i = this.setPenLocation(i, service);
  29666. } else if (b === 0x8f) {
  29667. service = this.reset(i, service);
  29668. } else if (b === 0x08) {
  29669. // BS: Backspace
  29670. service.currentWindow.backspace();
  29671. } else if (b === 0x0c) {
  29672. // FF: Form feed
  29673. service.currentWindow.clearText();
  29674. } else if (b === 0x0d) {
  29675. // CR: Carriage return
  29676. service.currentWindow.pendingNewLine = true;
  29677. } else if (b === 0x0e) {
  29678. // HCR: Horizontal carriage return
  29679. service.currentWindow.clearText();
  29680. } else if (b === 0x8d) {
  29681. // DLY: Delay, nothing to do
  29682. i++;
  29683. } else ;
  29684. }
  29685. };
  29686. /**
  29687. * Execute an extended command
  29688. *
  29689. * @param {Integer} i Current index in the 708 packet
  29690. * @param {Service} service The service object to be affected
  29691. * @return {Integer} New index after parsing
  29692. */
  29693. Cea708Stream.prototype.extendedCommands = function (i, service) {
  29694. var packetData = this.current708Packet.data;
  29695. var b = packetData[++i];
  29696. if (within708TextBlock(b)) {
  29697. i = this.handleText(i, service, {
  29698. isExtended: true
  29699. });
  29700. }
  29701. return i;
  29702. };
  29703. /**
  29704. * Get PTS value of a given byte index
  29705. *
  29706. * @param {Integer} byteIndex Index of the byte
  29707. * @return {Integer} PTS
  29708. */
  29709. Cea708Stream.prototype.getPts = function (byteIndex) {
  29710. // There's 1 pts value per 2 bytes
  29711. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  29712. };
  29713. /**
  29714. * Initializes a service
  29715. *
  29716. * @param {Integer} serviceNum Service number
  29717. * @return {Service} Initialized service object
  29718. */
  29719. Cea708Stream.prototype.initService = function (serviceNum, i) {
  29720. var serviceName = 'SERVICE' + serviceNum;
  29721. var self = this;
  29722. var serviceName;
  29723. var encoding;
  29724. if (serviceName in this.serviceEncodings) {
  29725. encoding = this.serviceEncodings[serviceName];
  29726. }
  29727. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  29728. this.services[serviceNum].init(this.getPts(i), function (pts) {
  29729. self.flushDisplayed(pts, self.services[serviceNum]);
  29730. });
  29731. return this.services[serviceNum];
  29732. };
  29733. /**
  29734. * Execute text writing to current window
  29735. *
  29736. * @param {Integer} i Current index in the 708 packet
  29737. * @param {Service} service The service object to be affected
  29738. * @return {Integer} New index after parsing
  29739. */
  29740. Cea708Stream.prototype.handleText = function (i, service, options) {
  29741. var isExtended = options && options.isExtended;
  29742. var isMultiByte = options && options.isMultiByte;
  29743. var packetData = this.current708Packet.data;
  29744. var extended = isExtended ? 0x1000 : 0x0000;
  29745. var currentByte = packetData[i];
  29746. var nextByte = packetData[i + 1];
  29747. var win = service.currentWindow;
  29748. var _char;
  29749. var charCodeArray; // Use the TextDecoder if one was created for this service
  29750. if (service.textDecoder_ && !isExtended) {
  29751. if (isMultiByte) {
  29752. charCodeArray = [currentByte, nextByte];
  29753. i++;
  29754. } else {
  29755. charCodeArray = [currentByte];
  29756. }
  29757. _char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  29758. } else {
  29759. _char = get708CharFromCode(extended | currentByte);
  29760. }
  29761. if (win.pendingNewLine && !win.isEmpty()) {
  29762. win.newLine(this.getPts(i));
  29763. }
  29764. win.pendingNewLine = false;
  29765. win.addText(_char);
  29766. return i;
  29767. };
  29768. /**
  29769. * Handle decoding of multibyte character
  29770. *
  29771. * @param {Integer} i Current index in the 708 packet
  29772. * @param {Service} service The service object to be affected
  29773. * @return {Integer} New index after parsing
  29774. */
  29775. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  29776. var packetData = this.current708Packet.data;
  29777. var firstByte = packetData[i + 1];
  29778. var secondByte = packetData[i + 2];
  29779. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  29780. i = this.handleText(++i, service, {
  29781. isMultiByte: true
  29782. });
  29783. }
  29784. return i;
  29785. };
  29786. /**
  29787. * Parse and execute the CW# command.
  29788. *
  29789. * Set the current window.
  29790. *
  29791. * @param {Integer} i Current index in the 708 packet
  29792. * @param {Service} service The service object to be affected
  29793. * @return {Integer} New index after parsing
  29794. */
  29795. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  29796. var packetData = this.current708Packet.data;
  29797. var b = packetData[i];
  29798. var windowNum = b & 0x07;
  29799. service.setCurrentWindow(windowNum);
  29800. return i;
  29801. };
  29802. /**
  29803. * Parse and execute the DF# command.
  29804. *
  29805. * Define a window and set it as the current window.
  29806. *
  29807. * @param {Integer} i Current index in the 708 packet
  29808. * @param {Service} service The service object to be affected
  29809. * @return {Integer} New index after parsing
  29810. */
  29811. Cea708Stream.prototype.defineWindow = function (i, service) {
  29812. var packetData = this.current708Packet.data;
  29813. var b = packetData[i];
  29814. var windowNum = b & 0x07;
  29815. service.setCurrentWindow(windowNum);
  29816. var win = service.currentWindow;
  29817. b = packetData[++i];
  29818. win.visible = (b & 0x20) >> 5; // v
  29819. win.rowLock = (b & 0x10) >> 4; // rl
  29820. win.columnLock = (b & 0x08) >> 3; // cl
  29821. win.priority = b & 0x07; // p
  29822. b = packetData[++i];
  29823. win.relativePositioning = (b & 0x80) >> 7; // rp
  29824. win.anchorVertical = b & 0x7f; // av
  29825. b = packetData[++i];
  29826. win.anchorHorizontal = b; // ah
  29827. b = packetData[++i];
  29828. win.anchorPoint = (b & 0xf0) >> 4; // ap
  29829. win.rowCount = b & 0x0f; // rc
  29830. b = packetData[++i];
  29831. win.columnCount = b & 0x3f; // cc
  29832. b = packetData[++i];
  29833. win.windowStyle = (b & 0x38) >> 3; // ws
  29834. win.penStyle = b & 0x07; // ps
  29835. // The spec says there are (rowCount+1) "virtual rows"
  29836. win.virtualRowCount = win.rowCount + 1;
  29837. return i;
  29838. };
  29839. /**
  29840. * Parse and execute the SWA command.
  29841. *
  29842. * Set attributes of the current window.
  29843. *
  29844. * @param {Integer} i Current index in the 708 packet
  29845. * @param {Service} service The service object to be affected
  29846. * @return {Integer} New index after parsing
  29847. */
  29848. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  29849. var packetData = this.current708Packet.data;
  29850. var b = packetData[i];
  29851. var winAttr = service.currentWindow.winAttr;
  29852. b = packetData[++i];
  29853. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  29854. winAttr.fillRed = (b & 0x30) >> 4; // fr
  29855. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  29856. winAttr.fillBlue = b & 0x03; // fb
  29857. b = packetData[++i];
  29858. winAttr.borderType = (b & 0xc0) >> 6; // bt
  29859. winAttr.borderRed = (b & 0x30) >> 4; // br
  29860. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  29861. winAttr.borderBlue = b & 0x03; // bb
  29862. b = packetData[++i];
  29863. winAttr.borderType += (b & 0x80) >> 5; // bt
  29864. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  29865. winAttr.printDirection = (b & 0x30) >> 4; // pd
  29866. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  29867. winAttr.justify = b & 0x03; // j
  29868. b = packetData[++i];
  29869. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  29870. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  29871. winAttr.displayEffect = b & 0x03; // de
  29872. return i;
  29873. };
  29874. /**
  29875. * Gather text from all displayed windows and push a caption to output.
  29876. *
  29877. * @param {Integer} i Current index in the 708 packet
  29878. * @param {Service} service The service object to be affected
  29879. */
  29880. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  29881. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  29882. // display text in the correct order, but sample files so far have not shown any issue.
  29883. for (var winId = 0; winId < 8; winId++) {
  29884. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  29885. displayedText.push(service.windows[winId].getText());
  29886. }
  29887. }
  29888. service.endPts = pts;
  29889. service.text = displayedText.join('\n\n');
  29890. this.pushCaption(service);
  29891. service.startPts = pts;
  29892. };
  29893. /**
  29894. * Push a caption to output if the caption contains text.
  29895. *
  29896. * @param {Service} service The service object to be affected
  29897. */
  29898. Cea708Stream.prototype.pushCaption = function (service) {
  29899. if (service.text !== '') {
  29900. this.trigger('data', {
  29901. startPts: service.startPts,
  29902. endPts: service.endPts,
  29903. text: service.text,
  29904. stream: 'cc708_' + service.serviceNum
  29905. });
  29906. service.text = '';
  29907. service.startPts = service.endPts;
  29908. }
  29909. };
  29910. /**
  29911. * Parse and execute the DSW command.
  29912. *
  29913. * Set visible property of windows based on the parsed bitmask.
  29914. *
  29915. * @param {Integer} i Current index in the 708 packet
  29916. * @param {Service} service The service object to be affected
  29917. * @return {Integer} New index after parsing
  29918. */
  29919. Cea708Stream.prototype.displayWindows = function (i, service) {
  29920. var packetData = this.current708Packet.data;
  29921. var b = packetData[++i];
  29922. var pts = this.getPts(i);
  29923. this.flushDisplayed(pts, service);
  29924. for (var winId = 0; winId < 8; winId++) {
  29925. if (b & 0x01 << winId) {
  29926. service.windows[winId].visible = 1;
  29927. }
  29928. }
  29929. return i;
  29930. };
  29931. /**
  29932. * Parse and execute the HDW command.
  29933. *
  29934. * Set visible property of windows based on the parsed bitmask.
  29935. *
  29936. * @param {Integer} i Current index in the 708 packet
  29937. * @param {Service} service The service object to be affected
  29938. * @return {Integer} New index after parsing
  29939. */
  29940. Cea708Stream.prototype.hideWindows = function (i, service) {
  29941. var packetData = this.current708Packet.data;
  29942. var b = packetData[++i];
  29943. var pts = this.getPts(i);
  29944. this.flushDisplayed(pts, service);
  29945. for (var winId = 0; winId < 8; winId++) {
  29946. if (b & 0x01 << winId) {
  29947. service.windows[winId].visible = 0;
  29948. }
  29949. }
  29950. return i;
  29951. };
  29952. /**
  29953. * Parse and execute the TGW command.
  29954. *
  29955. * Set visible property of windows based on the parsed bitmask.
  29956. *
  29957. * @param {Integer} i Current index in the 708 packet
  29958. * @param {Service} service The service object to be affected
  29959. * @return {Integer} New index after parsing
  29960. */
  29961. Cea708Stream.prototype.toggleWindows = function (i, service) {
  29962. var packetData = this.current708Packet.data;
  29963. var b = packetData[++i];
  29964. var pts = this.getPts(i);
  29965. this.flushDisplayed(pts, service);
  29966. for (var winId = 0; winId < 8; winId++) {
  29967. if (b & 0x01 << winId) {
  29968. service.windows[winId].visible ^= 1;
  29969. }
  29970. }
  29971. return i;
  29972. };
  29973. /**
  29974. * Parse and execute the CLW command.
  29975. *
  29976. * Clear text of windows based on the parsed bitmask.
  29977. *
  29978. * @param {Integer} i Current index in the 708 packet
  29979. * @param {Service} service The service object to be affected
  29980. * @return {Integer} New index after parsing
  29981. */
  29982. Cea708Stream.prototype.clearWindows = function (i, service) {
  29983. var packetData = this.current708Packet.data;
  29984. var b = packetData[++i];
  29985. var pts = this.getPts(i);
  29986. this.flushDisplayed(pts, service);
  29987. for (var winId = 0; winId < 8; winId++) {
  29988. if (b & 0x01 << winId) {
  29989. service.windows[winId].clearText();
  29990. }
  29991. }
  29992. return i;
  29993. };
  29994. /**
  29995. * Parse and execute the DLW command.
  29996. *
  29997. * Re-initialize windows based on the parsed bitmask.
  29998. *
  29999. * @param {Integer} i Current index in the 708 packet
  30000. * @param {Service} service The service object to be affected
  30001. * @return {Integer} New index after parsing
  30002. */
  30003. Cea708Stream.prototype.deleteWindows = function (i, service) {
  30004. var packetData = this.current708Packet.data;
  30005. var b = packetData[++i];
  30006. var pts = this.getPts(i);
  30007. this.flushDisplayed(pts, service);
  30008. for (var winId = 0; winId < 8; winId++) {
  30009. if (b & 0x01 << winId) {
  30010. service.windows[winId].reset();
  30011. }
  30012. }
  30013. return i;
  30014. };
  30015. /**
  30016. * Parse and execute the SPA command.
  30017. *
  30018. * Set pen attributes of the current window.
  30019. *
  30020. * @param {Integer} i Current index in the 708 packet
  30021. * @param {Service} service The service object to be affected
  30022. * @return {Integer} New index after parsing
  30023. */
  30024. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  30025. var packetData = this.current708Packet.data;
  30026. var b = packetData[i];
  30027. var penAttr = service.currentWindow.penAttr;
  30028. b = packetData[++i];
  30029. penAttr.textTag = (b & 0xf0) >> 4; // tt
  30030. penAttr.offset = (b & 0x0c) >> 2; // o
  30031. penAttr.penSize = b & 0x03; // s
  30032. b = packetData[++i];
  30033. penAttr.italics = (b & 0x80) >> 7; // i
  30034. penAttr.underline = (b & 0x40) >> 6; // u
  30035. penAttr.edgeType = (b & 0x38) >> 3; // et
  30036. penAttr.fontStyle = b & 0x07; // fs
  30037. return i;
  30038. };
  30039. /**
  30040. * Parse and execute the SPC command.
  30041. *
  30042. * Set pen color of the current window.
  30043. *
  30044. * @param {Integer} i Current index in the 708 packet
  30045. * @param {Service} service The service object to be affected
  30046. * @return {Integer} New index after parsing
  30047. */
  30048. Cea708Stream.prototype.setPenColor = function (i, service) {
  30049. var packetData = this.current708Packet.data;
  30050. var b = packetData[i];
  30051. var penColor = service.currentWindow.penColor;
  30052. b = packetData[++i];
  30053. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  30054. penColor.fgRed = (b & 0x30) >> 4; // fr
  30055. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  30056. penColor.fgBlue = b & 0x03; // fb
  30057. b = packetData[++i];
  30058. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  30059. penColor.bgRed = (b & 0x30) >> 4; // br
  30060. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  30061. penColor.bgBlue = b & 0x03; // bb
  30062. b = packetData[++i];
  30063. penColor.edgeRed = (b & 0x30) >> 4; // er
  30064. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  30065. penColor.edgeBlue = b & 0x03; // eb
  30066. return i;
  30067. };
  30068. /**
  30069. * Parse and execute the SPL command.
  30070. *
  30071. * Set pen location of the current window.
  30072. *
  30073. * @param {Integer} i Current index in the 708 packet
  30074. * @param {Service} service The service object to be affected
  30075. * @return {Integer} New index after parsing
  30076. */
  30077. Cea708Stream.prototype.setPenLocation = function (i, service) {
  30078. var packetData = this.current708Packet.data;
  30079. var b = packetData[i];
  30080. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  30081. service.currentWindow.pendingNewLine = true;
  30082. b = packetData[++i];
  30083. penLoc.row = b & 0x0f; // r
  30084. b = packetData[++i];
  30085. penLoc.column = b & 0x3f; // c
  30086. return i;
  30087. };
  30088. /**
  30089. * Execute the RST command.
  30090. *
  30091. * Reset service to a clean slate. Re-initialize.
  30092. *
  30093. * @param {Integer} i Current index in the 708 packet
  30094. * @param {Service} service The service object to be affected
  30095. * @return {Service} Re-initialized service
  30096. */
  30097. Cea708Stream.prototype.reset = function (i, service) {
  30098. var pts = this.getPts(i);
  30099. this.flushDisplayed(pts, service);
  30100. return this.initService(service.serviceNum, i);
  30101. }; // This hash maps non-ASCII, special, and extended character codes to their
  30102. // proper Unicode equivalent. The first keys that are only a single byte
  30103. // are the non-standard ASCII characters, which simply map the CEA608 byte
  30104. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  30105. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  30106. // can be performed regardless of the field and data channel on which the
  30107. // character code was received.
  30108. var CHARACTER_TRANSLATION = {
  30109. 0x2a: 0xe1,
  30110. // á
  30111. 0x5c: 0xe9,
  30112. // é
  30113. 0x5e: 0xed,
  30114. // í
  30115. 0x5f: 0xf3,
  30116. // ó
  30117. 0x60: 0xfa,
  30118. // ú
  30119. 0x7b: 0xe7,
  30120. // ç
  30121. 0x7c: 0xf7,
  30122. // ÷
  30123. 0x7d: 0xd1,
  30124. // Ñ
  30125. 0x7e: 0xf1,
  30126. // ñ
  30127. 0x7f: 0x2588,
  30128. // █
  30129. 0x0130: 0xae,
  30130. // ®
  30131. 0x0131: 0xb0,
  30132. // °
  30133. 0x0132: 0xbd,
  30134. // ½
  30135. 0x0133: 0xbf,
  30136. // ¿
  30137. 0x0134: 0x2122,
  30138. // ™
  30139. 0x0135: 0xa2,
  30140. // ¢
  30141. 0x0136: 0xa3,
  30142. // £
  30143. 0x0137: 0x266a,
  30144. // ♪
  30145. 0x0138: 0xe0,
  30146. // à
  30147. 0x0139: 0xa0,
  30148. //
  30149. 0x013a: 0xe8,
  30150. // è
  30151. 0x013b: 0xe2,
  30152. // â
  30153. 0x013c: 0xea,
  30154. // ê
  30155. 0x013d: 0xee,
  30156. // î
  30157. 0x013e: 0xf4,
  30158. // ô
  30159. 0x013f: 0xfb,
  30160. // û
  30161. 0x0220: 0xc1,
  30162. // Á
  30163. 0x0221: 0xc9,
  30164. // É
  30165. 0x0222: 0xd3,
  30166. // Ó
  30167. 0x0223: 0xda,
  30168. // Ú
  30169. 0x0224: 0xdc,
  30170. // Ü
  30171. 0x0225: 0xfc,
  30172. // ü
  30173. 0x0226: 0x2018,
  30174. // ‘
  30175. 0x0227: 0xa1,
  30176. // ¡
  30177. 0x0228: 0x2a,
  30178. // *
  30179. 0x0229: 0x27,
  30180. // '
  30181. 0x022a: 0x2014,
  30182. // —
  30183. 0x022b: 0xa9,
  30184. // ©
  30185. 0x022c: 0x2120,
  30186. // ℠
  30187. 0x022d: 0x2022,
  30188. // •
  30189. 0x022e: 0x201c,
  30190. // “
  30191. 0x022f: 0x201d,
  30192. // ”
  30193. 0x0230: 0xc0,
  30194. // À
  30195. 0x0231: 0xc2,
  30196. // Â
  30197. 0x0232: 0xc7,
  30198. // Ç
  30199. 0x0233: 0xc8,
  30200. // È
  30201. 0x0234: 0xca,
  30202. // Ê
  30203. 0x0235: 0xcb,
  30204. // Ë
  30205. 0x0236: 0xeb,
  30206. // ë
  30207. 0x0237: 0xce,
  30208. // Î
  30209. 0x0238: 0xcf,
  30210. // Ï
  30211. 0x0239: 0xef,
  30212. // ï
  30213. 0x023a: 0xd4,
  30214. // Ô
  30215. 0x023b: 0xd9,
  30216. // Ù
  30217. 0x023c: 0xf9,
  30218. // ù
  30219. 0x023d: 0xdb,
  30220. // Û
  30221. 0x023e: 0xab,
  30222. // «
  30223. 0x023f: 0xbb,
  30224. // »
  30225. 0x0320: 0xc3,
  30226. // Ã
  30227. 0x0321: 0xe3,
  30228. // ã
  30229. 0x0322: 0xcd,
  30230. // Í
  30231. 0x0323: 0xcc,
  30232. // Ì
  30233. 0x0324: 0xec,
  30234. // ì
  30235. 0x0325: 0xd2,
  30236. // Ò
  30237. 0x0326: 0xf2,
  30238. // ò
  30239. 0x0327: 0xd5,
  30240. // Õ
  30241. 0x0328: 0xf5,
  30242. // õ
  30243. 0x0329: 0x7b,
  30244. // {
  30245. 0x032a: 0x7d,
  30246. // }
  30247. 0x032b: 0x5c,
  30248. // \
  30249. 0x032c: 0x5e,
  30250. // ^
  30251. 0x032d: 0x5f,
  30252. // _
  30253. 0x032e: 0x7c,
  30254. // |
  30255. 0x032f: 0x7e,
  30256. // ~
  30257. 0x0330: 0xc4,
  30258. // Ä
  30259. 0x0331: 0xe4,
  30260. // ä
  30261. 0x0332: 0xd6,
  30262. // Ö
  30263. 0x0333: 0xf6,
  30264. // ö
  30265. 0x0334: 0xdf,
  30266. // ß
  30267. 0x0335: 0xa5,
  30268. // ¥
  30269. 0x0336: 0xa4,
  30270. // ¤
  30271. 0x0337: 0x2502,
  30272. // │
  30273. 0x0338: 0xc5,
  30274. // Å
  30275. 0x0339: 0xe5,
  30276. // å
  30277. 0x033a: 0xd8,
  30278. // Ø
  30279. 0x033b: 0xf8,
  30280. // ø
  30281. 0x033c: 0x250c,
  30282. // ┌
  30283. 0x033d: 0x2510,
  30284. // ┐
  30285. 0x033e: 0x2514,
  30286. // └
  30287. 0x033f: 0x2518 // ┘
  30288. };
  30289. var getCharFromCode = function getCharFromCode(code) {
  30290. if (code === null) {
  30291. return '';
  30292. }
  30293. code = CHARACTER_TRANSLATION[code] || code;
  30294. return String.fromCharCode(code);
  30295. }; // the index of the last row in a CEA-608 display buffer
  30296. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  30297. // getting it through bit logic.
  30298. 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
  30299. // cells. The "bottom" row is the last element in the outer array.
  30300. var createDisplayBuffer = function createDisplayBuffer() {
  30301. var result = [],
  30302. i = BOTTOM_ROW + 1;
  30303. while (i--) {
  30304. result.push('');
  30305. }
  30306. return result;
  30307. };
  30308. var Cea608Stream = function Cea608Stream(field, dataChannel) {
  30309. Cea608Stream.prototype.init.call(this);
  30310. this.field_ = field || 0;
  30311. this.dataChannel_ = dataChannel || 0;
  30312. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  30313. this.setConstants();
  30314. this.reset();
  30315. this.push = function (packet) {
  30316. var data, swap, char0, char1, text; // remove the parity bits
  30317. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  30318. if (data === this.lastControlCode_) {
  30319. this.lastControlCode_ = null;
  30320. return;
  30321. } // Store control codes
  30322. if ((data & 0xf000) === 0x1000) {
  30323. this.lastControlCode_ = data;
  30324. } else if (data !== this.PADDING_) {
  30325. this.lastControlCode_ = null;
  30326. }
  30327. char0 = data >>> 8;
  30328. char1 = data & 0xff;
  30329. if (data === this.PADDING_) {
  30330. return;
  30331. } else if (data === this.RESUME_CAPTION_LOADING_) {
  30332. this.mode_ = 'popOn';
  30333. } else if (data === this.END_OF_CAPTION_) {
  30334. // If an EOC is received while in paint-on mode, the displayed caption
  30335. // text should be swapped to non-displayed memory as if it was a pop-on
  30336. // caption. Because of that, we should explicitly switch back to pop-on
  30337. // mode
  30338. this.mode_ = 'popOn';
  30339. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  30340. this.flushDisplayed(packet.pts); // flip memory
  30341. swap = this.displayed_;
  30342. this.displayed_ = this.nonDisplayed_;
  30343. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  30344. this.startPts_ = packet.pts;
  30345. } else if (data === this.ROLL_UP_2_ROWS_) {
  30346. this.rollUpRows_ = 2;
  30347. this.setRollUp(packet.pts);
  30348. } else if (data === this.ROLL_UP_3_ROWS_) {
  30349. this.rollUpRows_ = 3;
  30350. this.setRollUp(packet.pts);
  30351. } else if (data === this.ROLL_UP_4_ROWS_) {
  30352. this.rollUpRows_ = 4;
  30353. this.setRollUp(packet.pts);
  30354. } else if (data === this.CARRIAGE_RETURN_) {
  30355. this.clearFormatting(packet.pts);
  30356. this.flushDisplayed(packet.pts);
  30357. this.shiftRowsUp_();
  30358. this.startPts_ = packet.pts;
  30359. } else if (data === this.BACKSPACE_) {
  30360. if (this.mode_ === 'popOn') {
  30361. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30362. } else {
  30363. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30364. }
  30365. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  30366. this.flushDisplayed(packet.pts);
  30367. this.displayed_ = createDisplayBuffer();
  30368. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  30369. this.nonDisplayed_ = createDisplayBuffer();
  30370. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  30371. if (this.mode_ !== 'paintOn') {
  30372. // NOTE: This should be removed when proper caption positioning is
  30373. // implemented
  30374. this.flushDisplayed(packet.pts);
  30375. this.displayed_ = createDisplayBuffer();
  30376. }
  30377. this.mode_ = 'paintOn';
  30378. this.startPts_ = packet.pts; // Append special characters to caption text
  30379. } else if (this.isSpecialCharacter(char0, char1)) {
  30380. // Bitmask char0 so that we can apply character transformations
  30381. // regardless of field and data channel.
  30382. // Then byte-shift to the left and OR with char1 so we can pass the
  30383. // entire character code to `getCharFromCode`.
  30384. char0 = (char0 & 0x03) << 8;
  30385. text = getCharFromCode(char0 | char1);
  30386. this[this.mode_](packet.pts, text);
  30387. this.column_++; // Append extended characters to caption text
  30388. } else if (this.isExtCharacter(char0, char1)) {
  30389. // Extended characters always follow their "non-extended" equivalents.
  30390. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  30391. // decoders are supposed to drop the "è", while compliant decoders
  30392. // backspace the "e" and insert "è".
  30393. // Delete the previous character
  30394. if (this.mode_ === 'popOn') {
  30395. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  30396. } else {
  30397. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  30398. } // Bitmask char0 so that we can apply character transformations
  30399. // regardless of field and data channel.
  30400. // Then byte-shift to the left and OR with char1 so we can pass the
  30401. // entire character code to `getCharFromCode`.
  30402. char0 = (char0 & 0x03) << 8;
  30403. text = getCharFromCode(char0 | char1);
  30404. this[this.mode_](packet.pts, text);
  30405. this.column_++; // Process mid-row codes
  30406. } else if (this.isMidRowCode(char0, char1)) {
  30407. // Attributes are not additive, so clear all formatting
  30408. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  30409. // should be replaced with spaces, so add one now
  30410. this[this.mode_](packet.pts, ' ');
  30411. this.column_++;
  30412. if ((char1 & 0xe) === 0xe) {
  30413. this.addFormatting(packet.pts, ['i']);
  30414. }
  30415. if ((char1 & 0x1) === 0x1) {
  30416. this.addFormatting(packet.pts, ['u']);
  30417. } // Detect offset control codes and adjust cursor
  30418. } else if (this.isOffsetControlCode(char0, char1)) {
  30419. // Cursor position is set by indent PAC (see below) in 4-column
  30420. // increments, with an additional offset code of 1-3 to reach any
  30421. // of the 32 columns specified by CEA-608. So all we need to do
  30422. // here is increment the column cursor by the given offset.
  30423. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  30424. } else if (this.isPAC(char0, char1)) {
  30425. // There's no logic for PAC -> row mapping, so we have to just
  30426. // find the row code in an array and use its index :(
  30427. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  30428. if (this.mode_ === 'rollUp') {
  30429. // This implies that the base row is incorrectly set.
  30430. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  30431. // of roll-up rows set.
  30432. if (row - this.rollUpRows_ + 1 < 0) {
  30433. row = this.rollUpRows_ - 1;
  30434. }
  30435. this.setRollUp(packet.pts, row);
  30436. }
  30437. if (row !== this.row_) {
  30438. // formatting is only persistent for current row
  30439. this.clearFormatting(packet.pts);
  30440. this.row_ = row;
  30441. } // All PACs can apply underline, so detect and apply
  30442. // (All odd-numbered second bytes set underline)
  30443. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  30444. this.addFormatting(packet.pts, ['u']);
  30445. }
  30446. if ((data & 0x10) === 0x10) {
  30447. // We've got an indent level code. Each successive even number
  30448. // increments the column cursor by 4, so we can get the desired
  30449. // column position by bit-shifting to the right (to get n/2)
  30450. // and multiplying by 4.
  30451. this.column_ = ((data & 0xe) >> 1) * 4;
  30452. }
  30453. if (this.isColorPAC(char1)) {
  30454. // it's a color code, though we only support white, which
  30455. // can be either normal or italicized. white italics can be
  30456. // either 0x4e or 0x6e depending on the row, so we just
  30457. // bitwise-and with 0xe to see if italics should be turned on
  30458. if ((char1 & 0xe) === 0xe) {
  30459. this.addFormatting(packet.pts, ['i']);
  30460. }
  30461. } // We have a normal character in char0, and possibly one in char1
  30462. } else if (this.isNormalChar(char0)) {
  30463. if (char1 === 0x00) {
  30464. char1 = null;
  30465. }
  30466. text = getCharFromCode(char0);
  30467. text += getCharFromCode(char1);
  30468. this[this.mode_](packet.pts, text);
  30469. this.column_ += text.length;
  30470. } // finish data processing
  30471. };
  30472. };
  30473. Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
  30474. // display buffer
  30475. Cea608Stream.prototype.flushDisplayed = function (pts) {
  30476. var content = this.displayed_ // remove spaces from the start and end of the string
  30477. .map(function (row, index) {
  30478. try {
  30479. return row.trim();
  30480. } catch (e) {
  30481. // Ordinarily, this shouldn't happen. However, caption
  30482. // parsing errors should not throw exceptions and
  30483. // break playback.
  30484. this.trigger('log', {
  30485. level: 'warn',
  30486. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  30487. });
  30488. return '';
  30489. }
  30490. }, this) // combine all text rows to display in one cue
  30491. .join('\n') // and remove blank rows from the start and end, but not the middle
  30492. .replace(/^\n+|\n+$/g, '');
  30493. if (content.length) {
  30494. this.trigger('data', {
  30495. startPts: this.startPts_,
  30496. endPts: pts,
  30497. text: content,
  30498. stream: this.name_
  30499. });
  30500. }
  30501. };
  30502. /**
  30503. * Zero out the data, used for startup and on seek
  30504. */
  30505. Cea608Stream.prototype.reset = function () {
  30506. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  30507. // actually display captions. If a caption is shifted to a row
  30508. // with a lower index than this, it is cleared from the display
  30509. // buffer
  30510. this.topRow_ = 0;
  30511. this.startPts_ = 0;
  30512. this.displayed_ = createDisplayBuffer();
  30513. this.nonDisplayed_ = createDisplayBuffer();
  30514. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  30515. this.column_ = 0;
  30516. this.row_ = BOTTOM_ROW;
  30517. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  30518. this.formatting_ = [];
  30519. };
  30520. /**
  30521. * Sets up control code and related constants for this instance
  30522. */
  30523. Cea608Stream.prototype.setConstants = function () {
  30524. // The following attributes have these uses:
  30525. // ext_ : char0 for mid-row codes, and the base for extended
  30526. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  30527. // extended codes)
  30528. // control_: char0 for control codes, except byte-shifted to the
  30529. // left so that we can do this.control_ | CONTROL_CODE
  30530. // offset_: char0 for tab offset codes
  30531. //
  30532. // It's also worth noting that control codes, and _only_ control codes,
  30533. // differ between field 1 and field2. Field 2 control codes are always
  30534. // their field 1 value plus 1. That's why there's the "| field" on the
  30535. // control value.
  30536. if (this.dataChannel_ === 0) {
  30537. this.BASE_ = 0x10;
  30538. this.EXT_ = 0x11;
  30539. this.CONTROL_ = (0x14 | this.field_) << 8;
  30540. this.OFFSET_ = 0x17;
  30541. } else if (this.dataChannel_ === 1) {
  30542. this.BASE_ = 0x18;
  30543. this.EXT_ = 0x19;
  30544. this.CONTROL_ = (0x1c | this.field_) << 8;
  30545. this.OFFSET_ = 0x1f;
  30546. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  30547. // list is not exhaustive. For a more comprehensive listing and semantics see
  30548. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  30549. // Padding
  30550. this.PADDING_ = 0x0000; // Pop-on Mode
  30551. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  30552. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  30553. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  30554. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  30555. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  30556. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  30557. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  30558. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  30559. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  30560. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  30561. };
  30562. /**
  30563. * Detects if the 2-byte packet data is a special character
  30564. *
  30565. * Special characters have a second byte in the range 0x30 to 0x3f,
  30566. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  30567. * data channel 2).
  30568. *
  30569. * @param {Integer} char0 The first byte
  30570. * @param {Integer} char1 The second byte
  30571. * @return {Boolean} Whether the 2 bytes are an special character
  30572. */
  30573. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  30574. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  30575. };
  30576. /**
  30577. * Detects if the 2-byte packet data is an extended character
  30578. *
  30579. * Extended characters have a second byte in the range 0x20 to 0x3f,
  30580. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  30581. * 0x1a or 0x1b (for data channel 2).
  30582. *
  30583. * @param {Integer} char0 The first byte
  30584. * @param {Integer} char1 The second byte
  30585. * @return {Boolean} Whether the 2 bytes are an extended character
  30586. */
  30587. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  30588. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  30589. };
  30590. /**
  30591. * Detects if the 2-byte packet is a mid-row code
  30592. *
  30593. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  30594. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  30595. * channel 2).
  30596. *
  30597. * @param {Integer} char0 The first byte
  30598. * @param {Integer} char1 The second byte
  30599. * @return {Boolean} Whether the 2 bytes are a mid-row code
  30600. */
  30601. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  30602. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  30603. };
  30604. /**
  30605. * Detects if the 2-byte packet is an offset control code
  30606. *
  30607. * Offset control codes have a second byte in the range 0x21 to 0x23,
  30608. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  30609. * data channel 2).
  30610. *
  30611. * @param {Integer} char0 The first byte
  30612. * @param {Integer} char1 The second byte
  30613. * @return {Boolean} Whether the 2 bytes are an offset control code
  30614. */
  30615. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  30616. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  30617. };
  30618. /**
  30619. * Detects if the 2-byte packet is a Preamble Address Code
  30620. *
  30621. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  30622. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  30623. * range 0x40 to 0x7f.
  30624. *
  30625. * @param {Integer} char0 The first byte
  30626. * @param {Integer} char1 The second byte
  30627. * @return {Boolean} Whether the 2 bytes are a PAC
  30628. */
  30629. Cea608Stream.prototype.isPAC = function (char0, char1) {
  30630. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  30631. };
  30632. /**
  30633. * Detects if a packet's second byte is in the range of a PAC color code
  30634. *
  30635. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  30636. * 0x60 to 0x6f.
  30637. *
  30638. * @param {Integer} char1 The second byte
  30639. * @return {Boolean} Whether the byte is a color PAC
  30640. */
  30641. Cea608Stream.prototype.isColorPAC = function (char1) {
  30642. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  30643. };
  30644. /**
  30645. * Detects if a single byte is in the range of a normal character
  30646. *
  30647. * Normal text bytes are in the range 0x20 to 0x7f.
  30648. *
  30649. * @param {Integer} char The byte
  30650. * @return {Boolean} Whether the byte is a normal character
  30651. */
  30652. Cea608Stream.prototype.isNormalChar = function (_char2) {
  30653. return _char2 >= 0x20 && _char2 <= 0x7f;
  30654. };
  30655. /**
  30656. * Configures roll-up
  30657. *
  30658. * @param {Integer} pts Current PTS
  30659. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  30660. * a new position
  30661. */
  30662. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  30663. // Reset the base row to the bottom row when switching modes
  30664. if (this.mode_ !== 'rollUp') {
  30665. this.row_ = BOTTOM_ROW;
  30666. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  30667. this.flushDisplayed(pts);
  30668. this.nonDisplayed_ = createDisplayBuffer();
  30669. this.displayed_ = createDisplayBuffer();
  30670. }
  30671. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  30672. // move currently displayed captions (up or down) to the new base row
  30673. for (var i = 0; i < this.rollUpRows_; i++) {
  30674. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  30675. this.displayed_[this.row_ - i] = '';
  30676. }
  30677. }
  30678. if (newBaseRow === undefined) {
  30679. newBaseRow = this.row_;
  30680. }
  30681. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  30682. }; // Adds the opening HTML tag for the passed character to the caption text,
  30683. // and keeps track of it for later closing
  30684. Cea608Stream.prototype.addFormatting = function (pts, format) {
  30685. this.formatting_ = this.formatting_.concat(format);
  30686. var text = format.reduce(function (text, format) {
  30687. return text + '<' + format + '>';
  30688. }, '');
  30689. this[this.mode_](pts, text);
  30690. }; // Adds HTML closing tags for current formatting to caption text and
  30691. // clears remembered formatting
  30692. Cea608Stream.prototype.clearFormatting = function (pts) {
  30693. if (!this.formatting_.length) {
  30694. return;
  30695. }
  30696. var text = this.formatting_.reverse().reduce(function (text, format) {
  30697. return text + '</' + format + '>';
  30698. }, '');
  30699. this.formatting_ = [];
  30700. this[this.mode_](pts, text);
  30701. }; // Mode Implementations
  30702. Cea608Stream.prototype.popOn = function (pts, text) {
  30703. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  30704. baseRow += text;
  30705. this.nonDisplayed_[this.row_] = baseRow;
  30706. };
  30707. Cea608Stream.prototype.rollUp = function (pts, text) {
  30708. var baseRow = this.displayed_[this.row_];
  30709. baseRow += text;
  30710. this.displayed_[this.row_] = baseRow;
  30711. };
  30712. Cea608Stream.prototype.shiftRowsUp_ = function () {
  30713. var i; // clear out inactive rows
  30714. for (i = 0; i < this.topRow_; i++) {
  30715. this.displayed_[i] = '';
  30716. }
  30717. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  30718. this.displayed_[i] = '';
  30719. } // shift displayed rows up
  30720. for (i = this.topRow_; i < this.row_; i++) {
  30721. this.displayed_[i] = this.displayed_[i + 1];
  30722. } // clear out the bottom row
  30723. this.displayed_[this.row_] = '';
  30724. };
  30725. Cea608Stream.prototype.paintOn = function (pts, text) {
  30726. var baseRow = this.displayed_[this.row_];
  30727. baseRow += text;
  30728. this.displayed_[this.row_] = baseRow;
  30729. }; // exports
  30730. var captionStream = {
  30731. CaptionStream: CaptionStream$1,
  30732. Cea608Stream: Cea608Stream,
  30733. Cea708Stream: Cea708Stream
  30734. };
  30735. /**
  30736. * mux.js
  30737. *
  30738. * Copyright (c) Brightcove
  30739. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  30740. */
  30741. var streamTypes = {
  30742. H264_STREAM_TYPE: 0x1B,
  30743. ADTS_STREAM_TYPE: 0x0F,
  30744. METADATA_STREAM_TYPE: 0x15
  30745. };
  30746. var MAX_TS = 8589934592;
  30747. var RO_THRESH = 4294967296;
  30748. var TYPE_SHARED = 'shared';
  30749. var handleRollover$1 = function handleRollover(value, reference) {
  30750. var direction = 1;
  30751. if (value > reference) {
  30752. // If the current timestamp value is greater than our reference timestamp and we detect a
  30753. // timestamp rollover, this means the roll over is happening in the opposite direction.
  30754. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  30755. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  30756. // rollover point. In loading this segment, the timestamp values will be very large,
  30757. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  30758. // the time stamp to be `value - 2^33`.
  30759. direction = -1;
  30760. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  30761. // cause an incorrect adjustment.
  30762. while (Math.abs(reference - value) > RO_THRESH) {
  30763. value += direction * MAX_TS;
  30764. }
  30765. return value;
  30766. };
  30767. var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
  30768. var lastDTS, referenceDTS;
  30769. TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  30770. // video and audio. We could use `undefined` here, but having a string
  30771. // makes debugging a little clearer.
  30772. this.type_ = type || TYPE_SHARED;
  30773. this.push = function (data) {
  30774. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  30775. // streams will only accept data that matches their type.
  30776. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  30777. return;
  30778. }
  30779. if (referenceDTS === undefined) {
  30780. referenceDTS = data.dts;
  30781. }
  30782. data.dts = handleRollover$1(data.dts, referenceDTS);
  30783. data.pts = handleRollover$1(data.pts, referenceDTS);
  30784. lastDTS = data.dts;
  30785. this.trigger('data', data);
  30786. };
  30787. this.flush = function () {
  30788. referenceDTS = lastDTS;
  30789. this.trigger('done');
  30790. };
  30791. this.endTimeline = function () {
  30792. this.flush();
  30793. this.trigger('endedtimeline');
  30794. };
  30795. this.discontinuity = function () {
  30796. referenceDTS = void 0;
  30797. lastDTS = void 0;
  30798. };
  30799. this.reset = function () {
  30800. this.discontinuity();
  30801. this.trigger('reset');
  30802. };
  30803. };
  30804. TimestampRolloverStream$1.prototype = new stream();
  30805. var timestampRolloverStream = {
  30806. TimestampRolloverStream: TimestampRolloverStream$1,
  30807. handleRollover: handleRollover$1
  30808. };
  30809. var percentEncode$1 = function percentEncode(bytes, start, end) {
  30810. var i,
  30811. result = '';
  30812. for (i = start; i < end; i++) {
  30813. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  30814. }
  30815. return result;
  30816. },
  30817. // return the string representation of the specified byte range,
  30818. // interpreted as UTf-8.
  30819. parseUtf8 = function parseUtf8(bytes, start, end) {
  30820. return decodeURIComponent(percentEncode$1(bytes, start, end));
  30821. },
  30822. // return the string representation of the specified byte range,
  30823. // interpreted as ISO-8859-1.
  30824. parseIso88591$1 = function parseIso88591(bytes, start, end) {
  30825. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  30826. },
  30827. parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
  30828. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  30829. },
  30830. tagParsers = {
  30831. TXXX: function TXXX(tag) {
  30832. var i;
  30833. if (tag.data[0] !== 3) {
  30834. // ignore frames with unrecognized character encodings
  30835. return;
  30836. }
  30837. for (i = 1; i < tag.data.length; i++) {
  30838. if (tag.data[i] === 0) {
  30839. // parse the text fields
  30840. tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
  30841. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  30842. break;
  30843. }
  30844. }
  30845. tag.data = tag.value;
  30846. },
  30847. WXXX: function WXXX(tag) {
  30848. var i;
  30849. if (tag.data[0] !== 3) {
  30850. // ignore frames with unrecognized character encodings
  30851. return;
  30852. }
  30853. for (i = 1; i < tag.data.length; i++) {
  30854. if (tag.data[i] === 0) {
  30855. // parse the description and URL fields
  30856. tag.description = parseUtf8(tag.data, 1, i);
  30857. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  30858. break;
  30859. }
  30860. }
  30861. },
  30862. PRIV: function PRIV(tag) {
  30863. var i;
  30864. for (i = 0; i < tag.data.length; i++) {
  30865. if (tag.data[i] === 0) {
  30866. // parse the description and URL fields
  30867. tag.owner = parseIso88591$1(tag.data, 0, i);
  30868. break;
  30869. }
  30870. }
  30871. tag.privateData = tag.data.subarray(i + 1);
  30872. tag.data = tag.privateData;
  30873. }
  30874. },
  30875. _MetadataStream;
  30876. _MetadataStream = function MetadataStream(options) {
  30877. var settings = {
  30878. // the bytes of the program-level descriptor field in MP2T
  30879. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  30880. // program element descriptors"
  30881. descriptor: options && options.descriptor
  30882. },
  30883. // the total size in bytes of the ID3 tag being parsed
  30884. tagSize = 0,
  30885. // tag data that is not complete enough to be parsed
  30886. buffer = [],
  30887. // the total number of bytes currently in the buffer
  30888. bufferSize = 0,
  30889. i;
  30890. _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  30891. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  30892. this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
  30893. if (settings.descriptor) {
  30894. for (i = 0; i < settings.descriptor.length; i++) {
  30895. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  30896. }
  30897. }
  30898. this.push = function (chunk) {
  30899. var tag, frameStart, frameSize, frame, i, frameHeader;
  30900. if (chunk.type !== 'timed-metadata') {
  30901. return;
  30902. } // if data_alignment_indicator is set in the PES header,
  30903. // we must have the start of a new ID3 tag. Assume anything
  30904. // remaining in the buffer was malformed and throw it out
  30905. if (chunk.dataAlignmentIndicator) {
  30906. bufferSize = 0;
  30907. buffer.length = 0;
  30908. } // ignore events that don't look like ID3 data
  30909. 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))) {
  30910. this.trigger('log', {
  30911. level: 'warn',
  30912. message: 'Skipping unrecognized metadata packet'
  30913. });
  30914. return;
  30915. } // add this chunk to the data we've collected so far
  30916. buffer.push(chunk);
  30917. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  30918. if (buffer.length === 1) {
  30919. // the frame size is transmitted as a 28-bit integer in the
  30920. // last four bytes of the ID3 header.
  30921. // The most significant bit of each byte is dropped and the
  30922. // results concatenated to recover the actual value.
  30923. tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  30924. // convenient for our comparisons to include it
  30925. tagSize += 10;
  30926. } // if the entire frame has not arrived, wait for more data
  30927. if (bufferSize < tagSize) {
  30928. return;
  30929. } // collect the entire frame so it can be parsed
  30930. tag = {
  30931. data: new Uint8Array(tagSize),
  30932. frames: [],
  30933. pts: buffer[0].pts,
  30934. dts: buffer[0].dts
  30935. };
  30936. for (i = 0; i < tagSize;) {
  30937. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  30938. i += buffer[0].data.byteLength;
  30939. bufferSize -= buffer[0].data.byteLength;
  30940. buffer.shift();
  30941. } // find the start of the first frame and the end of the tag
  30942. frameStart = 10;
  30943. if (tag.data[5] & 0x40) {
  30944. // advance the frame start past the extended header
  30945. frameStart += 4; // header size field
  30946. frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
  30947. tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
  30948. } // parse one or more ID3 frames
  30949. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  30950. do {
  30951. // determine the number of bytes in this frame
  30952. frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
  30953. if (frameSize < 1) {
  30954. this.trigger('log', {
  30955. level: 'warn',
  30956. message: 'Malformed ID3 frame encountered. Skipping metadata parsing.'
  30957. });
  30958. return;
  30959. }
  30960. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  30961. frame = {
  30962. id: frameHeader,
  30963. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  30964. };
  30965. frame.key = frame.id;
  30966. if (tagParsers[frame.id]) {
  30967. tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
  30968. // time for raw AAC data
  30969. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  30970. var d = frame.data,
  30971. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  30972. size *= 4;
  30973. size += d[7] & 0x03;
  30974. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  30975. // on the value of this frame
  30976. // we couldn't have known the appropriate pts and dts before
  30977. // parsing this ID3 tag so set those values now
  30978. if (tag.pts === undefined && tag.dts === undefined) {
  30979. tag.pts = frame.timeStamp;
  30980. tag.dts = frame.timeStamp;
  30981. }
  30982. this.trigger('timestamp', frame);
  30983. }
  30984. }
  30985. tag.frames.push(frame);
  30986. frameStart += 10; // advance past the frame header
  30987. frameStart += frameSize; // advance past the frame body
  30988. } while (frameStart < tagSize);
  30989. this.trigger('data', tag);
  30990. };
  30991. };
  30992. _MetadataStream.prototype = new stream();
  30993. var metadataStream = _MetadataStream;
  30994. var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  30995. var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
  30996. var MP2T_PACKET_LENGTH$1 = 188,
  30997. // bytes
  30998. SYNC_BYTE$1 = 0x47;
  30999. /**
  31000. * Splits an incoming stream of binary data into MPEG-2 Transport
  31001. * Stream packets.
  31002. */
  31003. _TransportPacketStream = function TransportPacketStream() {
  31004. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  31005. bytesInBuffer = 0;
  31006. _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  31007. /**
  31008. * Split a stream of data into M2TS packets
  31009. **/
  31010. this.push = function (bytes) {
  31011. var startIndex = 0,
  31012. endIndex = MP2T_PACKET_LENGTH$1,
  31013. everything; // If there are bytes remaining from the last segment, prepend them to the
  31014. // bytes that were pushed in
  31015. if (bytesInBuffer) {
  31016. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  31017. everything.set(buffer.subarray(0, bytesInBuffer));
  31018. everything.set(bytes, bytesInBuffer);
  31019. bytesInBuffer = 0;
  31020. } else {
  31021. everything = bytes;
  31022. } // While we have enough data for a packet
  31023. while (endIndex < everything.byteLength) {
  31024. // Look for a pair of start and end sync bytes in the data..
  31025. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  31026. // We found a packet so emit it and jump one whole packet forward in
  31027. // the stream
  31028. this.trigger('data', everything.subarray(startIndex, endIndex));
  31029. startIndex += MP2T_PACKET_LENGTH$1;
  31030. endIndex += MP2T_PACKET_LENGTH$1;
  31031. continue;
  31032. } // If we get here, we have somehow become de-synchronized and we need to step
  31033. // forward one byte at a time until we find a pair of sync bytes that denote
  31034. // a packet
  31035. startIndex++;
  31036. endIndex++;
  31037. } // If there was some data left over at the end of the segment that couldn't
  31038. // possibly be a whole packet, keep it because it might be the start of a packet
  31039. // that continues in the next segment
  31040. if (startIndex < everything.byteLength) {
  31041. buffer.set(everything.subarray(startIndex), 0);
  31042. bytesInBuffer = everything.byteLength - startIndex;
  31043. }
  31044. };
  31045. /**
  31046. * Passes identified M2TS packets to the TransportParseStream to be parsed
  31047. **/
  31048. this.flush = function () {
  31049. // If the buffer contains a whole packet when we are being flushed, emit it
  31050. // and empty the buffer. Otherwise hold onto the data because it may be
  31051. // important for decoding the next segment
  31052. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  31053. this.trigger('data', buffer);
  31054. bytesInBuffer = 0;
  31055. }
  31056. this.trigger('done');
  31057. };
  31058. this.endTimeline = function () {
  31059. this.flush();
  31060. this.trigger('endedtimeline');
  31061. };
  31062. this.reset = function () {
  31063. bytesInBuffer = 0;
  31064. this.trigger('reset');
  31065. };
  31066. };
  31067. _TransportPacketStream.prototype = new stream();
  31068. /**
  31069. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  31070. * forms of the individual transport stream packets.
  31071. */
  31072. _TransportParseStream = function TransportParseStream() {
  31073. var parsePsi, parsePat, parsePmt, self;
  31074. _TransportParseStream.prototype.init.call(this);
  31075. self = this;
  31076. this.packetsWaitingForPmt = [];
  31077. this.programMapTable = undefined;
  31078. parsePsi = function parsePsi(payload, psi) {
  31079. var offset = 0; // PSI packets may be split into multiple sections and those
  31080. // sections may be split into multiple packets. If a PSI
  31081. // section starts in this packet, the payload_unit_start_indicator
  31082. // will be true and the first byte of the payload will indicate
  31083. // the offset from the current position to the start of the
  31084. // section.
  31085. if (psi.payloadUnitStartIndicator) {
  31086. offset += payload[offset] + 1;
  31087. }
  31088. if (psi.type === 'pat') {
  31089. parsePat(payload.subarray(offset), psi);
  31090. } else {
  31091. parsePmt(payload.subarray(offset), psi);
  31092. }
  31093. };
  31094. parsePat = function parsePat(payload, pat) {
  31095. pat.section_number = payload[7]; // eslint-disable-line camelcase
  31096. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  31097. // skip the PSI header and parse the first PMT entry
  31098. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  31099. pat.pmtPid = self.pmtPid;
  31100. };
  31101. /**
  31102. * Parse out the relevant fields of a Program Map Table (PMT).
  31103. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  31104. * packet. The first byte in this array should be the table_id
  31105. * field.
  31106. * @param pmt {object} the object that should be decorated with
  31107. * fields parsed from the PMT.
  31108. */
  31109. parsePmt = function parsePmt(payload, pmt) {
  31110. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  31111. // take effect. We don't believe this should ever be the case
  31112. // for HLS but we'll ignore "forward" PMT declarations if we see
  31113. // them. Future PMT declarations have the current_next_indicator
  31114. // set to zero.
  31115. if (!(payload[5] & 0x01)) {
  31116. return;
  31117. } // overwrite any existing program map table
  31118. self.programMapTable = {
  31119. video: null,
  31120. audio: null,
  31121. 'timed-metadata': {}
  31122. }; // the mapping table ends at the end of the current section
  31123. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  31124. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  31125. // long the program info descriptors are
  31126. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  31127. offset = 12 + programInfoLength;
  31128. while (offset < tableEnd) {
  31129. var streamType = payload[offset];
  31130. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  31131. // TODO: should this be done for metadata too? for now maintain behavior of
  31132. // multiple metadata streams
  31133. if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
  31134. self.programMapTable.video = pid;
  31135. } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  31136. self.programMapTable.audio = pid;
  31137. } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
  31138. // map pid to stream type for metadata streams
  31139. self.programMapTable['timed-metadata'][pid] = streamType;
  31140. } // move to the next table entry
  31141. // skip past the elementary stream descriptors, if present
  31142. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  31143. } // record the map on the packet as well
  31144. pmt.programMapTable = self.programMapTable;
  31145. };
  31146. /**
  31147. * Deliver a new MP2T packet to the next stream in the pipeline.
  31148. */
  31149. this.push = function (packet) {
  31150. var result = {},
  31151. offset = 4;
  31152. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  31153. result.pid = packet[1] & 0x1f;
  31154. result.pid <<= 8;
  31155. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  31156. // fifth byte of the TS packet header. The adaptation field is
  31157. // used to add stuffing to PES packets that don't fill a complete
  31158. // TS packet, and to specify some forms of timing and control data
  31159. // that we do not currently use.
  31160. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  31161. offset += packet[offset] + 1;
  31162. } // parse the rest of the packet based on the type
  31163. if (result.pid === 0) {
  31164. result.type = 'pat';
  31165. parsePsi(packet.subarray(offset), result);
  31166. this.trigger('data', result);
  31167. } else if (result.pid === this.pmtPid) {
  31168. result.type = 'pmt';
  31169. parsePsi(packet.subarray(offset), result);
  31170. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  31171. while (this.packetsWaitingForPmt.length) {
  31172. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  31173. }
  31174. } else if (this.programMapTable === undefined) {
  31175. // When we have not seen a PMT yet, defer further processing of
  31176. // PES packets until one has been parsed
  31177. this.packetsWaitingForPmt.push([packet, offset, result]);
  31178. } else {
  31179. this.processPes_(packet, offset, result);
  31180. }
  31181. };
  31182. this.processPes_ = function (packet, offset, result) {
  31183. // set the appropriate stream type
  31184. if (result.pid === this.programMapTable.video) {
  31185. result.streamType = streamTypes.H264_STREAM_TYPE;
  31186. } else if (result.pid === this.programMapTable.audio) {
  31187. result.streamType = streamTypes.ADTS_STREAM_TYPE;
  31188. } else {
  31189. // if not video or audio, it is timed-metadata or unknown
  31190. // if unknown, streamType will be undefined
  31191. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  31192. }
  31193. result.type = 'pes';
  31194. result.data = packet.subarray(offset);
  31195. this.trigger('data', result);
  31196. };
  31197. };
  31198. _TransportParseStream.prototype = new stream();
  31199. _TransportParseStream.STREAM_TYPES = {
  31200. h264: 0x1b,
  31201. adts: 0x0f
  31202. };
  31203. /**
  31204. * Reconsistutes program elementary stream (PES) packets from parsed
  31205. * transport stream packets. That is, if you pipe an
  31206. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  31207. * events will be events which capture the bytes for individual PES
  31208. * packets plus relevant metadata that has been extracted from the
  31209. * container.
  31210. */
  31211. _ElementaryStream = function ElementaryStream() {
  31212. var self = this,
  31213. segmentHadPmt = false,
  31214. // PES packet fragments
  31215. video = {
  31216. data: [],
  31217. size: 0
  31218. },
  31219. audio = {
  31220. data: [],
  31221. size: 0
  31222. },
  31223. timedMetadata = {
  31224. data: [],
  31225. size: 0
  31226. },
  31227. programMapTable,
  31228. parsePes = function parsePes(payload, pes) {
  31229. var ptsDtsFlags;
  31230. var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  31231. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  31232. // that are frame data that is continuing from the previous fragment. This
  31233. // is to check that the pes data is the start of a new pes payload
  31234. if (startPrefix !== 1) {
  31235. return;
  31236. } // get the packet length, this will be 0 for video
  31237. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  31238. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  31239. // and a DTS value. Determine what combination of values is
  31240. // available to work with.
  31241. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  31242. // performs all bitwise operations on 32-bit integers but javascript
  31243. // supports a much greater range (52-bits) of integer using standard
  31244. // mathematical operations.
  31245. // We construct a 31-bit value using bitwise operators over the 31
  31246. // most significant bits and then multiply by 4 (equal to a left-shift
  31247. // of 2) before we add the final 2 least significant bits of the
  31248. // timestamp (equal to an OR.)
  31249. if (ptsDtsFlags & 0xC0) {
  31250. // the PTS and DTS are not written out directly. For information
  31251. // on how they are encoded, see
  31252. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  31253. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  31254. pes.pts *= 4; // Left shift by 2
  31255. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  31256. pes.dts = pes.pts;
  31257. if (ptsDtsFlags & 0x40) {
  31258. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  31259. pes.dts *= 4; // Left shift by 2
  31260. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  31261. }
  31262. } // the data section starts immediately after the PES header.
  31263. // pes_header_data_length specifies the number of header bytes
  31264. // that follow the last byte of the field.
  31265. pes.data = payload.subarray(9 + payload[8]);
  31266. },
  31267. /**
  31268. * Pass completely parsed PES packets to the next stream in the pipeline
  31269. **/
  31270. flushStream = function flushStream(stream, type, forceFlush) {
  31271. var packetData = new Uint8Array(stream.size),
  31272. event = {
  31273. type: type
  31274. },
  31275. i = 0,
  31276. offset = 0,
  31277. packetFlushable = false,
  31278. fragment; // do nothing if there is not enough buffered data for a complete
  31279. // PES header
  31280. if (!stream.data.length || stream.size < 9) {
  31281. return;
  31282. }
  31283. event.trackId = stream.data[0].pid; // reassemble the packet
  31284. for (i = 0; i < stream.data.length; i++) {
  31285. fragment = stream.data[i];
  31286. packetData.set(fragment.data, offset);
  31287. offset += fragment.data.byteLength;
  31288. } // parse assembled packet's PES header
  31289. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  31290. // check that there is enough stream data to fill the packet
  31291. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  31292. if (forceFlush || packetFlushable) {
  31293. stream.size = 0;
  31294. stream.data.length = 0;
  31295. } // only emit packets that are complete. this is to avoid assembling
  31296. // incomplete PES packets due to poor segmentation
  31297. if (packetFlushable) {
  31298. self.trigger('data', event);
  31299. }
  31300. };
  31301. _ElementaryStream.prototype.init.call(this);
  31302. /**
  31303. * Identifies M2TS packet types and parses PES packets using metadata
  31304. * parsed from the PMT
  31305. **/
  31306. this.push = function (data) {
  31307. ({
  31308. pat: function pat() {// we have to wait for the PMT to arrive as well before we
  31309. // have any meaningful metadata
  31310. },
  31311. pes: function pes() {
  31312. var stream, streamType;
  31313. switch (data.streamType) {
  31314. case streamTypes.H264_STREAM_TYPE:
  31315. stream = video;
  31316. streamType = 'video';
  31317. break;
  31318. case streamTypes.ADTS_STREAM_TYPE:
  31319. stream = audio;
  31320. streamType = 'audio';
  31321. break;
  31322. case streamTypes.METADATA_STREAM_TYPE:
  31323. stream = timedMetadata;
  31324. streamType = 'timed-metadata';
  31325. break;
  31326. default:
  31327. // ignore unknown stream types
  31328. return;
  31329. } // if a new packet is starting, we can flush the completed
  31330. // packet
  31331. if (data.payloadUnitStartIndicator) {
  31332. flushStream(stream, streamType, true);
  31333. } // buffer this fragment until we are sure we've received the
  31334. // complete payload
  31335. stream.data.push(data);
  31336. stream.size += data.data.byteLength;
  31337. },
  31338. pmt: function pmt() {
  31339. var event = {
  31340. type: 'metadata',
  31341. tracks: []
  31342. };
  31343. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  31344. if (programMapTable.video !== null) {
  31345. event.tracks.push({
  31346. timelineStartInfo: {
  31347. baseMediaDecodeTime: 0
  31348. },
  31349. id: +programMapTable.video,
  31350. codec: 'avc',
  31351. type: 'video'
  31352. });
  31353. }
  31354. if (programMapTable.audio !== null) {
  31355. event.tracks.push({
  31356. timelineStartInfo: {
  31357. baseMediaDecodeTime: 0
  31358. },
  31359. id: +programMapTable.audio,
  31360. codec: 'adts',
  31361. type: 'audio'
  31362. });
  31363. }
  31364. segmentHadPmt = true;
  31365. self.trigger('data', event);
  31366. }
  31367. })[data.type]();
  31368. };
  31369. this.reset = function () {
  31370. video.size = 0;
  31371. video.data.length = 0;
  31372. audio.size = 0;
  31373. audio.data.length = 0;
  31374. this.trigger('reset');
  31375. };
  31376. /**
  31377. * Flush any remaining input. Video PES packets may be of variable
  31378. * length. Normally, the start of a new video packet can trigger the
  31379. * finalization of the previous packet. That is not possible if no
  31380. * more video is forthcoming, however. In that case, some other
  31381. * mechanism (like the end of the file) has to be employed. When it is
  31382. * clear that no additional data is forthcoming, calling this method
  31383. * will flush the buffered packets.
  31384. */
  31385. this.flushStreams_ = function () {
  31386. // !!THIS ORDER IS IMPORTANT!!
  31387. // video first then audio
  31388. flushStream(video, 'video');
  31389. flushStream(audio, 'audio');
  31390. flushStream(timedMetadata, 'timed-metadata');
  31391. };
  31392. this.flush = function () {
  31393. // if on flush we haven't had a pmt emitted
  31394. // and we have a pmt to emit. emit the pmt
  31395. // so that we trigger a trackinfo downstream.
  31396. if (!segmentHadPmt && programMapTable) {
  31397. var pmt = {
  31398. type: 'metadata',
  31399. tracks: []
  31400. }; // translate audio and video streams to tracks
  31401. if (programMapTable.video !== null) {
  31402. pmt.tracks.push({
  31403. timelineStartInfo: {
  31404. baseMediaDecodeTime: 0
  31405. },
  31406. id: +programMapTable.video,
  31407. codec: 'avc',
  31408. type: 'video'
  31409. });
  31410. }
  31411. if (programMapTable.audio !== null) {
  31412. pmt.tracks.push({
  31413. timelineStartInfo: {
  31414. baseMediaDecodeTime: 0
  31415. },
  31416. id: +programMapTable.audio,
  31417. codec: 'adts',
  31418. type: 'audio'
  31419. });
  31420. }
  31421. self.trigger('data', pmt);
  31422. }
  31423. segmentHadPmt = false;
  31424. this.flushStreams_();
  31425. this.trigger('done');
  31426. };
  31427. };
  31428. _ElementaryStream.prototype = new stream();
  31429. var m2ts = {
  31430. PAT_PID: 0x0000,
  31431. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  31432. TransportPacketStream: _TransportPacketStream,
  31433. TransportParseStream: _TransportParseStream,
  31434. ElementaryStream: _ElementaryStream,
  31435. TimestampRolloverStream: TimestampRolloverStream,
  31436. CaptionStream: captionStream.CaptionStream,
  31437. Cea608Stream: captionStream.Cea608Stream,
  31438. Cea708Stream: captionStream.Cea708Stream,
  31439. MetadataStream: metadataStream
  31440. };
  31441. for (var type in streamTypes) {
  31442. if (streamTypes.hasOwnProperty(type)) {
  31443. m2ts[type] = streamTypes[type];
  31444. }
  31445. }
  31446. var m2ts_1 = m2ts;
  31447. var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
  31448. var _AdtsStream;
  31449. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  31450. /*
  31451. * Accepts a ElementaryStream and emits data events with parsed
  31452. * AAC Audio Frames of the individual packets. Input audio in ADTS
  31453. * format is unpacked and re-emitted as AAC frames.
  31454. *
  31455. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  31456. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  31457. */
  31458. _AdtsStream = function AdtsStream(handlePartialSegments) {
  31459. var buffer,
  31460. frameNum = 0;
  31461. _AdtsStream.prototype.init.call(this);
  31462. this.skipWarn_ = function (start, end) {
  31463. this.trigger('log', {
  31464. level: 'warn',
  31465. message: "adts skiping bytes " + start + " to " + end + " in frame " + frameNum + " outside syncword"
  31466. });
  31467. };
  31468. this.push = function (packet) {
  31469. var i = 0,
  31470. frameLength,
  31471. protectionSkipBytes,
  31472. oldBuffer,
  31473. sampleCount,
  31474. adtsFrameDuration;
  31475. if (!handlePartialSegments) {
  31476. frameNum = 0;
  31477. }
  31478. if (packet.type !== 'audio') {
  31479. // ignore non-audio data
  31480. return;
  31481. } // Prepend any data in the buffer to the input data so that we can parse
  31482. // aac frames the cross a PES packet boundary
  31483. if (buffer && buffer.length) {
  31484. oldBuffer = buffer;
  31485. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  31486. buffer.set(oldBuffer);
  31487. buffer.set(packet.data, oldBuffer.byteLength);
  31488. } else {
  31489. buffer = packet.data;
  31490. } // unpack any ADTS frames which have been fully received
  31491. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  31492. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  31493. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  31494. while (i + 7 < buffer.length) {
  31495. // Look for the start of an ADTS header..
  31496. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  31497. if (typeof skip !== 'number') {
  31498. skip = i;
  31499. } // If a valid header was not found, jump one forward and attempt to
  31500. // find a valid ADTS header starting at the next byte
  31501. i++;
  31502. continue;
  31503. }
  31504. if (typeof skip === 'number') {
  31505. this.skipWarn_(skip, i);
  31506. skip = null;
  31507. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  31508. // end of the ADTS header
  31509. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  31510. // end of the sync sequence
  31511. // NOTE: frame length includes the size of the header
  31512. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  31513. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  31514. 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,
  31515. // then we have to wait for more data
  31516. if (buffer.byteLength - i < frameLength) {
  31517. break;
  31518. } // Otherwise, deliver the complete AAC frame
  31519. this.trigger('data', {
  31520. pts: packet.pts + frameNum * adtsFrameDuration,
  31521. dts: packet.dts + frameNum * adtsFrameDuration,
  31522. sampleCount: sampleCount,
  31523. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  31524. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  31525. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  31526. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  31527. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  31528. samplesize: 16,
  31529. // data is the frame without it's header
  31530. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  31531. });
  31532. frameNum++;
  31533. i += frameLength;
  31534. }
  31535. if (typeof skip === 'number') {
  31536. this.skipWarn_(skip, i);
  31537. skip = null;
  31538. } // remove processed bytes from the buffer.
  31539. buffer = buffer.subarray(i);
  31540. };
  31541. this.flush = function () {
  31542. frameNum = 0;
  31543. this.trigger('done');
  31544. };
  31545. this.reset = function () {
  31546. buffer = void 0;
  31547. this.trigger('reset');
  31548. };
  31549. this.endTimeline = function () {
  31550. buffer = void 0;
  31551. this.trigger('endedtimeline');
  31552. };
  31553. };
  31554. _AdtsStream.prototype = new stream();
  31555. var adts = _AdtsStream;
  31556. /**
  31557. * mux.js
  31558. *
  31559. * Copyright (c) Brightcove
  31560. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  31561. */
  31562. var ExpGolomb;
  31563. /**
  31564. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  31565. * scheme used by h264.
  31566. */
  31567. ExpGolomb = function ExpGolomb(workingData) {
  31568. var // the number of bytes left to examine in workingData
  31569. workingBytesAvailable = workingData.byteLength,
  31570. // the current word being examined
  31571. workingWord = 0,
  31572. // :uint
  31573. // the number of bits left to examine in the current word
  31574. workingBitsAvailable = 0; // :uint;
  31575. // ():uint
  31576. this.length = function () {
  31577. return 8 * workingBytesAvailable;
  31578. }; // ():uint
  31579. this.bitsAvailable = function () {
  31580. return 8 * workingBytesAvailable + workingBitsAvailable;
  31581. }; // ():void
  31582. this.loadWord = function () {
  31583. var position = workingData.byteLength - workingBytesAvailable,
  31584. workingBytes = new Uint8Array(4),
  31585. availableBytes = Math.min(4, workingBytesAvailable);
  31586. if (availableBytes === 0) {
  31587. throw new Error('no bytes available');
  31588. }
  31589. workingBytes.set(workingData.subarray(position, position + availableBytes));
  31590. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  31591. workingBitsAvailable = availableBytes * 8;
  31592. workingBytesAvailable -= availableBytes;
  31593. }; // (count:int):void
  31594. this.skipBits = function (count) {
  31595. var skipBytes; // :int
  31596. if (workingBitsAvailable > count) {
  31597. workingWord <<= count;
  31598. workingBitsAvailable -= count;
  31599. } else {
  31600. count -= workingBitsAvailable;
  31601. skipBytes = Math.floor(count / 8);
  31602. count -= skipBytes * 8;
  31603. workingBytesAvailable -= skipBytes;
  31604. this.loadWord();
  31605. workingWord <<= count;
  31606. workingBitsAvailable -= count;
  31607. }
  31608. }; // (size:int):uint
  31609. this.readBits = function (size) {
  31610. var bits = Math.min(workingBitsAvailable, size),
  31611. // :uint
  31612. valu = workingWord >>> 32 - bits; // :uint
  31613. // if size > 31, handle error
  31614. workingBitsAvailable -= bits;
  31615. if (workingBitsAvailable > 0) {
  31616. workingWord <<= bits;
  31617. } else if (workingBytesAvailable > 0) {
  31618. this.loadWord();
  31619. }
  31620. bits = size - bits;
  31621. if (bits > 0) {
  31622. return valu << bits | this.readBits(bits);
  31623. }
  31624. return valu;
  31625. }; // ():uint
  31626. this.skipLeadingZeros = function () {
  31627. var leadingZeroCount; // :uint
  31628. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  31629. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  31630. // the first bit of working word is 1
  31631. workingWord <<= leadingZeroCount;
  31632. workingBitsAvailable -= leadingZeroCount;
  31633. return leadingZeroCount;
  31634. }
  31635. } // we exhausted workingWord and still have not found a 1
  31636. this.loadWord();
  31637. return leadingZeroCount + this.skipLeadingZeros();
  31638. }; // ():void
  31639. this.skipUnsignedExpGolomb = function () {
  31640. this.skipBits(1 + this.skipLeadingZeros());
  31641. }; // ():void
  31642. this.skipExpGolomb = function () {
  31643. this.skipBits(1 + this.skipLeadingZeros());
  31644. }; // ():uint
  31645. this.readUnsignedExpGolomb = function () {
  31646. var clz = this.skipLeadingZeros(); // :uint
  31647. return this.readBits(clz + 1) - 1;
  31648. }; // ():int
  31649. this.readExpGolomb = function () {
  31650. var valu = this.readUnsignedExpGolomb(); // :int
  31651. if (0x01 & valu) {
  31652. // the number is odd if the low order bit is set
  31653. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  31654. }
  31655. return -1 * (valu >>> 1); // divide by two then make it negative
  31656. }; // Some convenience functions
  31657. // :Boolean
  31658. this.readBoolean = function () {
  31659. return this.readBits(1) === 1;
  31660. }; // ():int
  31661. this.readUnsignedByte = function () {
  31662. return this.readBits(8);
  31663. };
  31664. this.loadWord();
  31665. };
  31666. var expGolomb = ExpGolomb;
  31667. var _H264Stream, _NalByteStream;
  31668. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  31669. /**
  31670. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  31671. */
  31672. _NalByteStream = function NalByteStream() {
  31673. var syncPoint = 0,
  31674. i,
  31675. buffer;
  31676. _NalByteStream.prototype.init.call(this);
  31677. /*
  31678. * Scans a byte stream and triggers a data event with the NAL units found.
  31679. * @param {Object} data Event received from H264Stream
  31680. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  31681. *
  31682. * @see H264Stream.push
  31683. */
  31684. this.push = function (data) {
  31685. var swapBuffer;
  31686. if (!buffer) {
  31687. buffer = data.data;
  31688. } else {
  31689. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  31690. swapBuffer.set(buffer);
  31691. swapBuffer.set(data.data, buffer.byteLength);
  31692. buffer = swapBuffer;
  31693. }
  31694. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  31695. // scan for NAL unit boundaries
  31696. // a match looks like this:
  31697. // 0 0 1 .. NAL .. 0 0 1
  31698. // ^ sync point ^ i
  31699. // or this:
  31700. // 0 0 1 .. NAL .. 0 0 0
  31701. // ^ sync point ^ i
  31702. // advance the sync point to a NAL start, if necessary
  31703. for (; syncPoint < len - 3; syncPoint++) {
  31704. if (buffer[syncPoint + 2] === 1) {
  31705. // the sync point is properly aligned
  31706. i = syncPoint + 5;
  31707. break;
  31708. }
  31709. }
  31710. while (i < len) {
  31711. // look at the current byte to determine if we've hit the end of
  31712. // a NAL unit boundary
  31713. switch (buffer[i]) {
  31714. case 0:
  31715. // skip past non-sync sequences
  31716. if (buffer[i - 1] !== 0) {
  31717. i += 2;
  31718. break;
  31719. } else if (buffer[i - 2] !== 0) {
  31720. i++;
  31721. break;
  31722. } // deliver the NAL unit if it isn't empty
  31723. if (syncPoint + 3 !== i - 2) {
  31724. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31725. } // drop trailing zeroes
  31726. do {
  31727. i++;
  31728. } while (buffer[i] !== 1 && i < len);
  31729. syncPoint = i - 2;
  31730. i += 3;
  31731. break;
  31732. case 1:
  31733. // skip past non-sync sequences
  31734. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  31735. i += 3;
  31736. break;
  31737. } // deliver the NAL unit
  31738. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  31739. syncPoint = i - 2;
  31740. i += 3;
  31741. break;
  31742. default:
  31743. // the current byte isn't a one or zero, so it cannot be part
  31744. // of a sync sequence
  31745. i += 3;
  31746. break;
  31747. }
  31748. } // filter out the NAL units that were delivered
  31749. buffer = buffer.subarray(syncPoint);
  31750. i -= syncPoint;
  31751. syncPoint = 0;
  31752. };
  31753. this.reset = function () {
  31754. buffer = null;
  31755. syncPoint = 0;
  31756. this.trigger('reset');
  31757. };
  31758. this.flush = function () {
  31759. // deliver the last buffered NAL unit
  31760. if (buffer && buffer.byteLength > 3) {
  31761. this.trigger('data', buffer.subarray(syncPoint + 3));
  31762. } // reset the stream state
  31763. buffer = null;
  31764. syncPoint = 0;
  31765. this.trigger('done');
  31766. };
  31767. this.endTimeline = function () {
  31768. this.flush();
  31769. this.trigger('endedtimeline');
  31770. };
  31771. };
  31772. _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
  31773. // see Recommendation ITU-T H.264 (4/2013),
  31774. // 7.3.2.1.1 Sequence parameter set data syntax
  31775. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  31776. 100: true,
  31777. 110: true,
  31778. 122: true,
  31779. 244: true,
  31780. 44: true,
  31781. 83: true,
  31782. 86: true,
  31783. 118: true,
  31784. 128: true,
  31785. // TODO: the three profiles below don't
  31786. // appear to have sps data in the specificiation anymore?
  31787. 138: true,
  31788. 139: true,
  31789. 134: true
  31790. };
  31791. /**
  31792. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  31793. * events.
  31794. */
  31795. _H264Stream = function H264Stream() {
  31796. var nalByteStream = new _NalByteStream(),
  31797. self,
  31798. trackId,
  31799. currentPts,
  31800. currentDts,
  31801. discardEmulationPreventionBytes,
  31802. readSequenceParameterSet,
  31803. skipScalingList;
  31804. _H264Stream.prototype.init.call(this);
  31805. self = this;
  31806. /*
  31807. * Pushes a packet from a stream onto the NalByteStream
  31808. *
  31809. * @param {Object} packet - A packet received from a stream
  31810. * @param {Uint8Array} packet.data - The raw bytes of the packet
  31811. * @param {Number} packet.dts - Decode timestamp of the packet
  31812. * @param {Number} packet.pts - Presentation timestamp of the packet
  31813. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  31814. * @param {('video'|'audio')} packet.type - The type of packet
  31815. *
  31816. */
  31817. this.push = function (packet) {
  31818. if (packet.type !== 'video') {
  31819. return;
  31820. }
  31821. trackId = packet.trackId;
  31822. currentPts = packet.pts;
  31823. currentDts = packet.dts;
  31824. nalByteStream.push(packet);
  31825. };
  31826. /*
  31827. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  31828. * for the NALUs to the next stream component.
  31829. * Also, preprocess caption and sequence parameter NALUs.
  31830. *
  31831. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  31832. * @see NalByteStream.push
  31833. */
  31834. nalByteStream.on('data', function (data) {
  31835. var event = {
  31836. trackId: trackId,
  31837. pts: currentPts,
  31838. dts: currentDts,
  31839. data: data,
  31840. nalUnitTypeCode: data[0] & 0x1f
  31841. };
  31842. switch (event.nalUnitTypeCode) {
  31843. case 0x05:
  31844. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  31845. break;
  31846. case 0x06:
  31847. event.nalUnitType = 'sei_rbsp';
  31848. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31849. break;
  31850. case 0x07:
  31851. event.nalUnitType = 'seq_parameter_set_rbsp';
  31852. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  31853. event.config = readSequenceParameterSet(event.escapedRBSP);
  31854. break;
  31855. case 0x08:
  31856. event.nalUnitType = 'pic_parameter_set_rbsp';
  31857. break;
  31858. case 0x09:
  31859. event.nalUnitType = 'access_unit_delimiter_rbsp';
  31860. break;
  31861. } // This triggers data on the H264Stream
  31862. self.trigger('data', event);
  31863. });
  31864. nalByteStream.on('done', function () {
  31865. self.trigger('done');
  31866. });
  31867. nalByteStream.on('partialdone', function () {
  31868. self.trigger('partialdone');
  31869. });
  31870. nalByteStream.on('reset', function () {
  31871. self.trigger('reset');
  31872. });
  31873. nalByteStream.on('endedtimeline', function () {
  31874. self.trigger('endedtimeline');
  31875. });
  31876. this.flush = function () {
  31877. nalByteStream.flush();
  31878. };
  31879. this.partialFlush = function () {
  31880. nalByteStream.partialFlush();
  31881. };
  31882. this.reset = function () {
  31883. nalByteStream.reset();
  31884. };
  31885. this.endTimeline = function () {
  31886. nalByteStream.endTimeline();
  31887. };
  31888. /**
  31889. * Advance the ExpGolomb decoder past a scaling list. The scaling
  31890. * list is optionally transmitted as part of a sequence parameter
  31891. * set and is not relevant to transmuxing.
  31892. * @param count {number} the number of entries in this scaling list
  31893. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  31894. * start of a scaling list
  31895. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  31896. */
  31897. skipScalingList = function skipScalingList(count, expGolombDecoder) {
  31898. var lastScale = 8,
  31899. nextScale = 8,
  31900. j,
  31901. deltaScale;
  31902. for (j = 0; j < count; j++) {
  31903. if (nextScale !== 0) {
  31904. deltaScale = expGolombDecoder.readExpGolomb();
  31905. nextScale = (lastScale + deltaScale + 256) % 256;
  31906. }
  31907. lastScale = nextScale === 0 ? lastScale : nextScale;
  31908. }
  31909. };
  31910. /**
  31911. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  31912. * Sequence Payload"
  31913. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  31914. * unit
  31915. * @return {Uint8Array} the RBSP without any Emulation
  31916. * Prevention Bytes
  31917. */
  31918. discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
  31919. var length = data.byteLength,
  31920. emulationPreventionBytesPositions = [],
  31921. i = 1,
  31922. newLength,
  31923. newData; // Find all `Emulation Prevention Bytes`
  31924. while (i < length - 2) {
  31925. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  31926. emulationPreventionBytesPositions.push(i + 2);
  31927. i += 2;
  31928. } else {
  31929. i++;
  31930. }
  31931. } // If no Emulation Prevention Bytes were found just return the original
  31932. // array
  31933. if (emulationPreventionBytesPositions.length === 0) {
  31934. return data;
  31935. } // Create a new array to hold the NAL unit data
  31936. newLength = length - emulationPreventionBytesPositions.length;
  31937. newData = new Uint8Array(newLength);
  31938. var sourceIndex = 0;
  31939. for (i = 0; i < newLength; sourceIndex++, i++) {
  31940. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  31941. // Skip this byte
  31942. sourceIndex++; // Remove this position index
  31943. emulationPreventionBytesPositions.shift();
  31944. }
  31945. newData[i] = data[sourceIndex];
  31946. }
  31947. return newData;
  31948. };
  31949. /**
  31950. * Read a sequence parameter set and return some interesting video
  31951. * properties. A sequence parameter set is the H264 metadata that
  31952. * describes the properties of upcoming video frames.
  31953. * @param data {Uint8Array} the bytes of a sequence parameter set
  31954. * @return {object} an object with configuration parsed from the
  31955. * sequence parameter set, including the dimensions of the
  31956. * associated video frames.
  31957. */
  31958. readSequenceParameterSet = function readSequenceParameterSet(data) {
  31959. var frameCropLeftOffset = 0,
  31960. frameCropRightOffset = 0,
  31961. frameCropTopOffset = 0,
  31962. frameCropBottomOffset = 0,
  31963. expGolombDecoder,
  31964. profileIdc,
  31965. levelIdc,
  31966. profileCompatibility,
  31967. chromaFormatIdc,
  31968. picOrderCntType,
  31969. numRefFramesInPicOrderCntCycle,
  31970. picWidthInMbsMinus1,
  31971. picHeightInMapUnitsMinus1,
  31972. frameMbsOnlyFlag,
  31973. scalingListCount,
  31974. sarRatio = [1, 1],
  31975. aspectRatioIdc,
  31976. i;
  31977. expGolombDecoder = new expGolomb(data);
  31978. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  31979. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  31980. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  31981. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  31982. // some profiles have more optional data we don't need
  31983. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  31984. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  31985. if (chromaFormatIdc === 3) {
  31986. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  31987. }
  31988. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  31989. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  31990. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  31991. if (expGolombDecoder.readBoolean()) {
  31992. // seq_scaling_matrix_present_flag
  31993. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  31994. for (i = 0; i < scalingListCount; i++) {
  31995. if (expGolombDecoder.readBoolean()) {
  31996. // seq_scaling_list_present_flag[ i ]
  31997. if (i < 6) {
  31998. skipScalingList(16, expGolombDecoder);
  31999. } else {
  32000. skipScalingList(64, expGolombDecoder);
  32001. }
  32002. }
  32003. }
  32004. }
  32005. }
  32006. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  32007. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  32008. if (picOrderCntType === 0) {
  32009. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  32010. } else if (picOrderCntType === 1) {
  32011. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  32012. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  32013. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  32014. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  32015. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  32016. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  32017. }
  32018. }
  32019. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  32020. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  32021. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32022. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  32023. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  32024. if (frameMbsOnlyFlag === 0) {
  32025. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  32026. }
  32027. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  32028. if (expGolombDecoder.readBoolean()) {
  32029. // frame_cropping_flag
  32030. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  32031. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  32032. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  32033. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  32034. }
  32035. if (expGolombDecoder.readBoolean()) {
  32036. // vui_parameters_present_flag
  32037. if (expGolombDecoder.readBoolean()) {
  32038. // aspect_ratio_info_present_flag
  32039. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  32040. switch (aspectRatioIdc) {
  32041. case 1:
  32042. sarRatio = [1, 1];
  32043. break;
  32044. case 2:
  32045. sarRatio = [12, 11];
  32046. break;
  32047. case 3:
  32048. sarRatio = [10, 11];
  32049. break;
  32050. case 4:
  32051. sarRatio = [16, 11];
  32052. break;
  32053. case 5:
  32054. sarRatio = [40, 33];
  32055. break;
  32056. case 6:
  32057. sarRatio = [24, 11];
  32058. break;
  32059. case 7:
  32060. sarRatio = [20, 11];
  32061. break;
  32062. case 8:
  32063. sarRatio = [32, 11];
  32064. break;
  32065. case 9:
  32066. sarRatio = [80, 33];
  32067. break;
  32068. case 10:
  32069. sarRatio = [18, 11];
  32070. break;
  32071. case 11:
  32072. sarRatio = [15, 11];
  32073. break;
  32074. case 12:
  32075. sarRatio = [64, 33];
  32076. break;
  32077. case 13:
  32078. sarRatio = [160, 99];
  32079. break;
  32080. case 14:
  32081. sarRatio = [4, 3];
  32082. break;
  32083. case 15:
  32084. sarRatio = [3, 2];
  32085. break;
  32086. case 16:
  32087. sarRatio = [2, 1];
  32088. break;
  32089. case 255:
  32090. {
  32091. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  32092. break;
  32093. }
  32094. }
  32095. if (sarRatio) {
  32096. sarRatio[0] / sarRatio[1];
  32097. }
  32098. }
  32099. }
  32100. return {
  32101. profileIdc: profileIdc,
  32102. levelIdc: levelIdc,
  32103. profileCompatibility: profileCompatibility,
  32104. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  32105. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  32106. // sar is sample aspect ratio
  32107. sarRatio: sarRatio
  32108. };
  32109. };
  32110. };
  32111. _H264Stream.prototype = new stream();
  32112. var h264 = {
  32113. H264Stream: _H264Stream,
  32114. NalByteStream: _NalByteStream
  32115. };
  32116. /**
  32117. * mux.js
  32118. *
  32119. * Copyright (c) Brightcove
  32120. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32121. *
  32122. * Utilities to detect basic properties and metadata about Aac data.
  32123. */
  32124. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  32125. var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
  32126. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  32127. flags = header[byteIndex + 5],
  32128. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  32129. returnSize = returnSize >= 0 ? returnSize : 0;
  32130. if (footerPresent) {
  32131. return returnSize + 20;
  32132. }
  32133. return returnSize + 10;
  32134. };
  32135. var getId3Offset = function getId3Offset(data, offset) {
  32136. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  32137. return offset;
  32138. }
  32139. offset += parseId3TagSize(data, offset);
  32140. return getId3Offset(data, offset);
  32141. }; // TODO: use vhs-utils
  32142. var isLikelyAacData$1 = function isLikelyAacData(data) {
  32143. var offset = getId3Offset(data, 0);
  32144. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  32145. // is not mp3 data but aac data.
  32146. (data[offset + 1] & 0x16) === 0x10;
  32147. };
  32148. var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
  32149. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  32150. }; // return a percent-encoded representation of the specified byte range
  32151. // @see http://en.wikipedia.org/wiki/Percent-encoding
  32152. var percentEncode = function percentEncode(bytes, start, end) {
  32153. var i,
  32154. result = '';
  32155. for (i = start; i < end; i++) {
  32156. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  32157. }
  32158. return result;
  32159. }; // return the string representation of the specified byte range,
  32160. // interpreted as ISO-8859-1.
  32161. var parseIso88591 = function parseIso88591(bytes, start, end) {
  32162. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  32163. };
  32164. var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
  32165. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  32166. middle = header[byteIndex + 4] << 3,
  32167. highTwo = header[byteIndex + 3] & 0x3 << 11;
  32168. return highTwo | middle | lowThree;
  32169. };
  32170. var parseType$2 = function parseType(header, byteIndex) {
  32171. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  32172. return 'timed-metadata';
  32173. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  32174. return 'audio';
  32175. }
  32176. return null;
  32177. };
  32178. var parseSampleRate = function parseSampleRate(packet) {
  32179. var i = 0;
  32180. while (i + 5 < packet.length) {
  32181. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  32182. // If a valid header was not found, jump one forward and attempt to
  32183. // find a valid ADTS header starting at the next byte
  32184. i++;
  32185. continue;
  32186. }
  32187. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  32188. }
  32189. return null;
  32190. };
  32191. var parseAacTimestamp = function parseAacTimestamp(packet) {
  32192. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  32193. frameStart = 10;
  32194. if (packet[5] & 0x40) {
  32195. // advance the frame start past the extended header
  32196. frameStart += 4; // header size field
  32197. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  32198. } // parse one or more ID3 frames
  32199. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  32200. do {
  32201. // determine the number of bytes in this frame
  32202. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  32203. if (frameSize < 1) {
  32204. return null;
  32205. }
  32206. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  32207. if (frameHeader === 'PRIV') {
  32208. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  32209. for (var i = 0; i < frame.byteLength; i++) {
  32210. if (frame[i] === 0) {
  32211. var owner = parseIso88591(frame, 0, i);
  32212. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  32213. var d = frame.subarray(i + 1);
  32214. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  32215. size *= 4;
  32216. size += d[7] & 0x03;
  32217. return size;
  32218. }
  32219. break;
  32220. }
  32221. }
  32222. }
  32223. frameStart += 10; // advance past the frame header
  32224. frameStart += frameSize; // advance past the frame body
  32225. } while (frameStart < packet.byteLength);
  32226. return null;
  32227. };
  32228. var utils = {
  32229. isLikelyAacData: isLikelyAacData$1,
  32230. parseId3TagSize: parseId3TagSize,
  32231. parseAdtsSize: parseAdtsSize,
  32232. parseType: parseType$2,
  32233. parseSampleRate: parseSampleRate,
  32234. parseAacTimestamp: parseAacTimestamp
  32235. };
  32236. var _AacStream;
  32237. /**
  32238. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  32239. */
  32240. _AacStream = function AacStream() {
  32241. var everything = new Uint8Array(),
  32242. timeStamp = 0;
  32243. _AacStream.prototype.init.call(this);
  32244. this.setTimestamp = function (timestamp) {
  32245. timeStamp = timestamp;
  32246. };
  32247. this.push = function (bytes) {
  32248. var frameSize = 0,
  32249. byteIndex = 0,
  32250. bytesLeft,
  32251. chunk,
  32252. packet,
  32253. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  32254. // bytes that were pushed in
  32255. if (everything.length) {
  32256. tempLength = everything.length;
  32257. everything = new Uint8Array(bytes.byteLength + tempLength);
  32258. everything.set(everything.subarray(0, tempLength));
  32259. everything.set(bytes, tempLength);
  32260. } else {
  32261. everything = bytes;
  32262. }
  32263. while (everything.length - byteIndex >= 3) {
  32264. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  32265. // Exit early because we don't have enough to parse
  32266. // the ID3 tag header
  32267. if (everything.length - byteIndex < 10) {
  32268. break;
  32269. } // check framesize
  32270. frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32271. // to emit a full packet
  32272. // Add to byteIndex to support multiple ID3 tags in sequence
  32273. if (byteIndex + frameSize > everything.length) {
  32274. break;
  32275. }
  32276. chunk = {
  32277. type: 'timed-metadata',
  32278. data: everything.subarray(byteIndex, byteIndex + frameSize)
  32279. };
  32280. this.trigger('data', chunk);
  32281. byteIndex += frameSize;
  32282. continue;
  32283. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  32284. // Exit early because we don't have enough to parse
  32285. // the ADTS frame header
  32286. if (everything.length - byteIndex < 7) {
  32287. break;
  32288. }
  32289. frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  32290. // to emit a full packet
  32291. if (byteIndex + frameSize > everything.length) {
  32292. break;
  32293. }
  32294. packet = {
  32295. type: 'audio',
  32296. data: everything.subarray(byteIndex, byteIndex + frameSize),
  32297. pts: timeStamp,
  32298. dts: timeStamp
  32299. };
  32300. this.trigger('data', packet);
  32301. byteIndex += frameSize;
  32302. continue;
  32303. }
  32304. byteIndex++;
  32305. }
  32306. bytesLeft = everything.length - byteIndex;
  32307. if (bytesLeft > 0) {
  32308. everything = everything.subarray(byteIndex);
  32309. } else {
  32310. everything = new Uint8Array();
  32311. }
  32312. };
  32313. this.reset = function () {
  32314. everything = new Uint8Array();
  32315. this.trigger('reset');
  32316. };
  32317. this.endTimeline = function () {
  32318. everything = new Uint8Array();
  32319. this.trigger('endedtimeline');
  32320. };
  32321. };
  32322. _AacStream.prototype = new stream();
  32323. var aac = _AacStream; // constants
  32324. var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  32325. var audioProperties = AUDIO_PROPERTIES;
  32326. var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  32327. var videoProperties = VIDEO_PROPERTIES;
  32328. var H264Stream = h264.H264Stream;
  32329. var isLikelyAacData = utils.isLikelyAacData;
  32330. var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
  32331. var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
  32332. var retriggerForStream = function retriggerForStream(key, event) {
  32333. event.stream = key;
  32334. this.trigger('log', event);
  32335. };
  32336. var addPipelineLogRetriggers = function addPipelineLogRetriggers(transmuxer, pipeline) {
  32337. var keys = Object.keys(pipeline);
  32338. for (var i = 0; i < keys.length; i++) {
  32339. var key = keys[i]; // skip non-stream keys and headOfPipeline
  32340. // which is just a duplicate
  32341. if (key === 'headOfPipeline' || !pipeline[key].on) {
  32342. continue;
  32343. }
  32344. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  32345. }
  32346. };
  32347. /**
  32348. * Compare two arrays (even typed) for same-ness
  32349. */
  32350. var arrayEquals = function arrayEquals(a, b) {
  32351. var i;
  32352. if (a.length !== b.length) {
  32353. return false;
  32354. } // compare the value of each element in the array
  32355. for (i = 0; i < a.length; i++) {
  32356. if (a[i] !== b[i]) {
  32357. return false;
  32358. }
  32359. }
  32360. return true;
  32361. };
  32362. var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  32363. var ptsOffsetFromDts = startPts - startDts,
  32364. decodeDuration = endDts - startDts,
  32365. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  32366. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  32367. // In order to provide relevant values for the player times, base timing info on the
  32368. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  32369. return {
  32370. start: {
  32371. dts: baseMediaDecodeTime,
  32372. pts: baseMediaDecodeTime + ptsOffsetFromDts
  32373. },
  32374. end: {
  32375. dts: baseMediaDecodeTime + decodeDuration,
  32376. pts: baseMediaDecodeTime + presentationDuration
  32377. },
  32378. prependedContentDuration: prependedContentDuration,
  32379. baseMediaDecodeTime: baseMediaDecodeTime
  32380. };
  32381. };
  32382. /**
  32383. * Constructs a single-track, ISO BMFF media segment from AAC data
  32384. * events. The output of this stream can be fed to a SourceBuffer
  32385. * configured with a suitable initialization segment.
  32386. * @param track {object} track metadata configuration
  32387. * @param options {object} transmuxer options object
  32388. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32389. * in the source; false to adjust the first segment to start at 0.
  32390. */
  32391. _AudioSegmentStream = function AudioSegmentStream(track, options) {
  32392. var adtsFrames = [],
  32393. sequenceNumber,
  32394. earliestAllowedDts = 0,
  32395. audioAppendStartTs = 0,
  32396. videoBaseMediaDecodeTime = Infinity;
  32397. options = options || {};
  32398. sequenceNumber = options.firstSequenceNumber || 0;
  32399. _AudioSegmentStream.prototype.init.call(this);
  32400. this.push = function (data) {
  32401. trackDecodeInfo.collectDtsInfo(track, data);
  32402. if (track) {
  32403. audioProperties.forEach(function (prop) {
  32404. track[prop] = data[prop];
  32405. });
  32406. } // buffer audio data until end() is called
  32407. adtsFrames.push(data);
  32408. };
  32409. this.setEarliestDts = function (earliestDts) {
  32410. earliestAllowedDts = earliestDts;
  32411. };
  32412. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  32413. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  32414. };
  32415. this.setAudioAppendStart = function (timestamp) {
  32416. audioAppendStartTs = timestamp;
  32417. };
  32418. this.flush = function () {
  32419. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  32420. if (adtsFrames.length === 0) {
  32421. this.trigger('done', 'AudioSegmentStream');
  32422. return;
  32423. }
  32424. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  32425. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  32426. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  32427. // samples (that is, adts frames) in the audio data
  32428. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  32429. mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
  32430. adtsFrames = [];
  32431. moof = mp4Generator.moof(sequenceNumber, [track]);
  32432. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  32433. sequenceNumber++;
  32434. boxes.set(moof);
  32435. boxes.set(mdat, moof.byteLength);
  32436. trackDecodeInfo.clearDtsInfo(track);
  32437. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  32438. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  32439. // valid use-case where an init segment/data should be triggered without associated
  32440. // frames. Leaving for now, but should be looked into.
  32441. if (frames.length) {
  32442. segmentDuration = frames.length * frameDuration;
  32443. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  32444. // frame info is in video clock cycles. Convert to match expectation of
  32445. // listeners (that all timestamps will be based on video clock cycles).
  32446. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  32447. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  32448. this.trigger('timingInfo', {
  32449. start: frames[0].pts,
  32450. end: frames[0].pts + segmentDuration
  32451. });
  32452. }
  32453. this.trigger('data', {
  32454. track: track,
  32455. boxes: boxes
  32456. });
  32457. this.trigger('done', 'AudioSegmentStream');
  32458. };
  32459. this.reset = function () {
  32460. trackDecodeInfo.clearDtsInfo(track);
  32461. adtsFrames = [];
  32462. this.trigger('reset');
  32463. };
  32464. };
  32465. _AudioSegmentStream.prototype = new stream();
  32466. /**
  32467. * Constructs a single-track, ISO BMFF media segment from H264 data
  32468. * events. The output of this stream can be fed to a SourceBuffer
  32469. * configured with a suitable initialization segment.
  32470. * @param track {object} track metadata configuration
  32471. * @param options {object} transmuxer options object
  32472. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  32473. * gopsToAlignWith list when attempting to align gop pts
  32474. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32475. * in the source; false to adjust the first segment to start at 0.
  32476. */
  32477. _VideoSegmentStream = function VideoSegmentStream(track, options) {
  32478. var sequenceNumber,
  32479. nalUnits = [],
  32480. gopsToAlignWith = [],
  32481. config,
  32482. pps;
  32483. options = options || {};
  32484. sequenceNumber = options.firstSequenceNumber || 0;
  32485. _VideoSegmentStream.prototype.init.call(this);
  32486. delete track.minPTS;
  32487. this.gopCache_ = [];
  32488. /**
  32489. * Constructs a ISO BMFF segment given H264 nalUnits
  32490. * @param {Object} nalUnit A data event representing a nalUnit
  32491. * @param {String} nalUnit.nalUnitType
  32492. * @param {Object} nalUnit.config Properties for a mp4 track
  32493. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  32494. * @see lib/codecs/h264.js
  32495. **/
  32496. this.push = function (nalUnit) {
  32497. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  32498. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  32499. config = nalUnit.config;
  32500. track.sps = [nalUnit.data];
  32501. videoProperties.forEach(function (prop) {
  32502. track[prop] = config[prop];
  32503. }, this);
  32504. }
  32505. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  32506. pps = nalUnit.data;
  32507. track.pps = [nalUnit.data];
  32508. } // buffer video until flush() is called
  32509. nalUnits.push(nalUnit);
  32510. };
  32511. /**
  32512. * Pass constructed ISO BMFF track and boxes on to the
  32513. * next stream in the pipeline
  32514. **/
  32515. this.flush = function () {
  32516. var frames,
  32517. gopForFusion,
  32518. gops,
  32519. moof,
  32520. mdat,
  32521. boxes,
  32522. prependedContentDuration = 0,
  32523. firstGop,
  32524. lastGop; // Throw away nalUnits at the start of the byte stream until
  32525. // we find the first AUD
  32526. while (nalUnits.length) {
  32527. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  32528. break;
  32529. }
  32530. nalUnits.shift();
  32531. } // Return early if no video data has been observed
  32532. if (nalUnits.length === 0) {
  32533. this.resetStream_();
  32534. this.trigger('done', 'VideoSegmentStream');
  32535. return;
  32536. } // Organize the raw nal-units into arrays that represent
  32537. // higher-level constructs such as frames and gops
  32538. // (group-of-pictures)
  32539. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  32540. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  32541. // a problem since MSE (on Chrome) requires a leading keyframe.
  32542. //
  32543. // We have two approaches to repairing this situation:
  32544. // 1) GOP-FUSION:
  32545. // This is where we keep track of the GOPS (group-of-pictures)
  32546. // from previous fragments and attempt to find one that we can
  32547. // prepend to the current fragment in order to create a valid
  32548. // fragment.
  32549. // 2) KEYFRAME-PULLING:
  32550. // Here we search for the first keyframe in the fragment and
  32551. // throw away all the frames between the start of the fragment
  32552. // and that keyframe. We then extend the duration and pull the
  32553. // PTS of the keyframe forward so that it covers the time range
  32554. // of the frames that were disposed of.
  32555. //
  32556. // #1 is far prefereable over #2 which can cause "stuttering" but
  32557. // requires more things to be just right.
  32558. if (!gops[0][0].keyFrame) {
  32559. // Search for a gop for fusion from our gopCache
  32560. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  32561. if (gopForFusion) {
  32562. // in order to provide more accurate timing information about the segment, save
  32563. // the number of seconds prepended to the original segment due to GOP fusion
  32564. prependedContentDuration = gopForFusion.duration;
  32565. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  32566. // new gop at the beginning
  32567. gops.byteLength += gopForFusion.byteLength;
  32568. gops.nalCount += gopForFusion.nalCount;
  32569. gops.pts = gopForFusion.pts;
  32570. gops.dts = gopForFusion.dts;
  32571. gops.duration += gopForFusion.duration;
  32572. } else {
  32573. // If we didn't find a candidate gop fall back to keyframe-pulling
  32574. gops = frameUtils.extendFirstKeyFrame(gops);
  32575. }
  32576. } // Trim gops to align with gopsToAlignWith
  32577. if (gopsToAlignWith.length) {
  32578. var alignedGops;
  32579. if (options.alignGopsAtEnd) {
  32580. alignedGops = this.alignGopsAtEnd_(gops);
  32581. } else {
  32582. alignedGops = this.alignGopsAtStart_(gops);
  32583. }
  32584. if (!alignedGops) {
  32585. // save all the nals in the last GOP into the gop cache
  32586. this.gopCache_.unshift({
  32587. gop: gops.pop(),
  32588. pps: track.pps,
  32589. sps: track.sps
  32590. }); // Keep a maximum of 6 GOPs in the cache
  32591. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32592. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  32593. this.resetStream_();
  32594. this.trigger('done', 'VideoSegmentStream');
  32595. return;
  32596. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  32597. // when recalculated before sending off to CoalesceStream
  32598. trackDecodeInfo.clearDtsInfo(track);
  32599. gops = alignedGops;
  32600. }
  32601. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  32602. // samples (that is, frames) in the video data
  32603. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  32604. mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
  32605. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  32606. this.trigger('processedGopsInfo', gops.map(function (gop) {
  32607. return {
  32608. pts: gop.pts,
  32609. dts: gop.dts,
  32610. byteLength: gop.byteLength
  32611. };
  32612. }));
  32613. firstGop = gops[0];
  32614. lastGop = gops[gops.length - 1];
  32615. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  32616. this.trigger('timingInfo', {
  32617. start: gops[0].pts,
  32618. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  32619. }); // save all the nals in the last GOP into the gop cache
  32620. this.gopCache_.unshift({
  32621. gop: gops.pop(),
  32622. pps: track.pps,
  32623. sps: track.sps
  32624. }); // Keep a maximum of 6 GOPs in the cache
  32625. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  32626. nalUnits = [];
  32627. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  32628. this.trigger('timelineStartInfo', track.timelineStartInfo);
  32629. moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  32630. // throwing away hundreds of media segment fragments
  32631. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  32632. sequenceNumber++;
  32633. boxes.set(moof);
  32634. boxes.set(mdat, moof.byteLength);
  32635. this.trigger('data', {
  32636. track: track,
  32637. boxes: boxes
  32638. });
  32639. this.resetStream_(); // Continue with the flush process now
  32640. this.trigger('done', 'VideoSegmentStream');
  32641. };
  32642. this.reset = function () {
  32643. this.resetStream_();
  32644. nalUnits = [];
  32645. this.gopCache_.length = 0;
  32646. gopsToAlignWith.length = 0;
  32647. this.trigger('reset');
  32648. };
  32649. this.resetStream_ = function () {
  32650. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  32651. // for instance, when we are rendition switching
  32652. config = undefined;
  32653. pps = undefined;
  32654. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  32655. // return it or return null if no good candidate was found
  32656. this.getGopForFusion_ = function (nalUnit) {
  32657. var halfSecond = 45000,
  32658. // Half-a-second in a 90khz clock
  32659. allowableOverlap = 10000,
  32660. // About 3 frames @ 30fps
  32661. nearestDistance = Infinity,
  32662. dtsDistance,
  32663. nearestGopObj,
  32664. currentGop,
  32665. currentGopObj,
  32666. i; // Search for the GOP nearest to the beginning of this nal unit
  32667. for (i = 0; i < this.gopCache_.length; i++) {
  32668. currentGopObj = this.gopCache_[i];
  32669. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  32670. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  32671. continue;
  32672. } // Reject Gops that would require a negative baseMediaDecodeTime
  32673. if (currentGop.dts < track.timelineStartInfo.dts) {
  32674. continue;
  32675. } // The distance between the end of the gop and the start of the nalUnit
  32676. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  32677. // a half-second of the nal unit
  32678. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  32679. // Always use the closest GOP we found if there is more than
  32680. // one candidate
  32681. if (!nearestGopObj || nearestDistance > dtsDistance) {
  32682. nearestGopObj = currentGopObj;
  32683. nearestDistance = dtsDistance;
  32684. }
  32685. }
  32686. }
  32687. if (nearestGopObj) {
  32688. return nearestGopObj.gop;
  32689. }
  32690. return null;
  32691. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32692. // of gopsToAlignWith starting from the START of the list
  32693. this.alignGopsAtStart_ = function (gops) {
  32694. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  32695. byteLength = gops.byteLength;
  32696. nalCount = gops.nalCount;
  32697. duration = gops.duration;
  32698. alignIndex = gopIndex = 0;
  32699. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  32700. align = gopsToAlignWith[alignIndex];
  32701. gop = gops[gopIndex];
  32702. if (align.pts === gop.pts) {
  32703. break;
  32704. }
  32705. if (gop.pts > align.pts) {
  32706. // this current gop starts after the current gop we want to align on, so increment
  32707. // align index
  32708. alignIndex++;
  32709. continue;
  32710. } // current gop starts before the current gop we want to align on. so increment gop
  32711. // index
  32712. gopIndex++;
  32713. byteLength -= gop.byteLength;
  32714. nalCount -= gop.nalCount;
  32715. duration -= gop.duration;
  32716. }
  32717. if (gopIndex === 0) {
  32718. // no gops to trim
  32719. return gops;
  32720. }
  32721. if (gopIndex === gops.length) {
  32722. // all gops trimmed, skip appending all gops
  32723. return null;
  32724. }
  32725. alignedGops = gops.slice(gopIndex);
  32726. alignedGops.byteLength = byteLength;
  32727. alignedGops.duration = duration;
  32728. alignedGops.nalCount = nalCount;
  32729. alignedGops.pts = alignedGops[0].pts;
  32730. alignedGops.dts = alignedGops[0].dts;
  32731. return alignedGops;
  32732. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  32733. // of gopsToAlignWith starting from the END of the list
  32734. this.alignGopsAtEnd_ = function (gops) {
  32735. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  32736. alignIndex = gopsToAlignWith.length - 1;
  32737. gopIndex = gops.length - 1;
  32738. alignEndIndex = null;
  32739. matchFound = false;
  32740. while (alignIndex >= 0 && gopIndex >= 0) {
  32741. align = gopsToAlignWith[alignIndex];
  32742. gop = gops[gopIndex];
  32743. if (align.pts === gop.pts) {
  32744. matchFound = true;
  32745. break;
  32746. }
  32747. if (align.pts > gop.pts) {
  32748. alignIndex--;
  32749. continue;
  32750. }
  32751. if (alignIndex === gopsToAlignWith.length - 1) {
  32752. // gop.pts is greater than the last alignment candidate. If no match is found
  32753. // by the end of this loop, we still want to append gops that come after this
  32754. // point
  32755. alignEndIndex = gopIndex;
  32756. }
  32757. gopIndex--;
  32758. }
  32759. if (!matchFound && alignEndIndex === null) {
  32760. return null;
  32761. }
  32762. var trimIndex;
  32763. if (matchFound) {
  32764. trimIndex = gopIndex;
  32765. } else {
  32766. trimIndex = alignEndIndex;
  32767. }
  32768. if (trimIndex === 0) {
  32769. return gops;
  32770. }
  32771. var alignedGops = gops.slice(trimIndex);
  32772. var metadata = alignedGops.reduce(function (total, gop) {
  32773. total.byteLength += gop.byteLength;
  32774. total.duration += gop.duration;
  32775. total.nalCount += gop.nalCount;
  32776. return total;
  32777. }, {
  32778. byteLength: 0,
  32779. duration: 0,
  32780. nalCount: 0
  32781. });
  32782. alignedGops.byteLength = metadata.byteLength;
  32783. alignedGops.duration = metadata.duration;
  32784. alignedGops.nalCount = metadata.nalCount;
  32785. alignedGops.pts = alignedGops[0].pts;
  32786. alignedGops.dts = alignedGops[0].dts;
  32787. return alignedGops;
  32788. };
  32789. this.alignGopsWith = function (newGopsToAlignWith) {
  32790. gopsToAlignWith = newGopsToAlignWith;
  32791. };
  32792. };
  32793. _VideoSegmentStream.prototype = new stream();
  32794. /**
  32795. * A Stream that can combine multiple streams (ie. audio & video)
  32796. * into a single output segment for MSE. Also supports audio-only
  32797. * and video-only streams.
  32798. * @param options {object} transmuxer options object
  32799. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  32800. * in the source; false to adjust the first segment to start at media timeline start.
  32801. */
  32802. _CoalesceStream = function CoalesceStream(options, metadataStream) {
  32803. // Number of Tracks per output segment
  32804. // If greater than 1, we combine multiple
  32805. // tracks into a single segment
  32806. this.numberOfTracks = 0;
  32807. this.metadataStream = metadataStream;
  32808. options = options || {};
  32809. if (typeof options.remux !== 'undefined') {
  32810. this.remuxTracks = !!options.remux;
  32811. } else {
  32812. this.remuxTracks = true;
  32813. }
  32814. if (typeof options.keepOriginalTimestamps === 'boolean') {
  32815. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  32816. } else {
  32817. this.keepOriginalTimestamps = false;
  32818. }
  32819. this.pendingTracks = [];
  32820. this.videoTrack = null;
  32821. this.pendingBoxes = [];
  32822. this.pendingCaptions = [];
  32823. this.pendingMetadata = [];
  32824. this.pendingBytes = 0;
  32825. this.emittedTracks = 0;
  32826. _CoalesceStream.prototype.init.call(this); // Take output from multiple
  32827. this.push = function (output) {
  32828. // buffer incoming captions until the associated video segment
  32829. // finishes
  32830. if (output.text) {
  32831. return this.pendingCaptions.push(output);
  32832. } // buffer incoming id3 tags until the final flush
  32833. if (output.frames) {
  32834. return this.pendingMetadata.push(output);
  32835. } // Add this track to the list of pending tracks and store
  32836. // important information required for the construction of
  32837. // the final segment
  32838. this.pendingTracks.push(output.track);
  32839. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  32840. // We unshift audio and push video because
  32841. // as of Chrome 75 when switching from
  32842. // one init segment to another if the video
  32843. // mdat does not appear after the audio mdat
  32844. // only audio will play for the duration of our transmux.
  32845. if (output.track.type === 'video') {
  32846. this.videoTrack = output.track;
  32847. this.pendingBoxes.push(output.boxes);
  32848. }
  32849. if (output.track.type === 'audio') {
  32850. this.audioTrack = output.track;
  32851. this.pendingBoxes.unshift(output.boxes);
  32852. }
  32853. };
  32854. };
  32855. _CoalesceStream.prototype = new stream();
  32856. _CoalesceStream.prototype.flush = function (flushSource) {
  32857. var offset = 0,
  32858. event = {
  32859. captions: [],
  32860. captionStreams: {},
  32861. metadata: [],
  32862. info: {}
  32863. },
  32864. caption,
  32865. id3,
  32866. initSegment,
  32867. timelineStartPts = 0,
  32868. i;
  32869. if (this.pendingTracks.length < this.numberOfTracks) {
  32870. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  32871. // Return because we haven't received a flush from a data-generating
  32872. // portion of the segment (meaning that we have only recieved meta-data
  32873. // or captions.)
  32874. return;
  32875. } else if (this.remuxTracks) {
  32876. // Return until we have enough tracks from the pipeline to remux (if we
  32877. // are remuxing audio and video into a single MP4)
  32878. return;
  32879. } else if (this.pendingTracks.length === 0) {
  32880. // In the case where we receive a flush without any data having been
  32881. // received we consider it an emitted track for the purposes of coalescing
  32882. // `done` events.
  32883. // We do this for the case where there is an audio and video track in the
  32884. // segment but no audio data. (seen in several playlists with alternate
  32885. // audio tracks and no audio present in the main TS segments.)
  32886. this.emittedTracks++;
  32887. if (this.emittedTracks >= this.numberOfTracks) {
  32888. this.trigger('done');
  32889. this.emittedTracks = 0;
  32890. }
  32891. return;
  32892. }
  32893. }
  32894. if (this.videoTrack) {
  32895. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  32896. videoProperties.forEach(function (prop) {
  32897. event.info[prop] = this.videoTrack[prop];
  32898. }, this);
  32899. } else if (this.audioTrack) {
  32900. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  32901. audioProperties.forEach(function (prop) {
  32902. event.info[prop] = this.audioTrack[prop];
  32903. }, this);
  32904. }
  32905. if (this.videoTrack || this.audioTrack) {
  32906. if (this.pendingTracks.length === 1) {
  32907. event.type = this.pendingTracks[0].type;
  32908. } else {
  32909. event.type = 'combined';
  32910. }
  32911. this.emittedTracks += this.pendingTracks.length;
  32912. initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  32913. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  32914. // and track definitions
  32915. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  32916. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  32917. for (i = 0; i < this.pendingBoxes.length; i++) {
  32918. event.data.set(this.pendingBoxes[i], offset);
  32919. offset += this.pendingBoxes[i].byteLength;
  32920. } // Translate caption PTS times into second offsets to match the
  32921. // video timeline for the segment, and add track info
  32922. for (i = 0; i < this.pendingCaptions.length; i++) {
  32923. caption = this.pendingCaptions[i];
  32924. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  32925. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  32926. event.captionStreams[caption.stream] = true;
  32927. event.captions.push(caption);
  32928. } // Translate ID3 frame PTS times into second offsets to match the
  32929. // video timeline for the segment
  32930. for (i = 0; i < this.pendingMetadata.length; i++) {
  32931. id3 = this.pendingMetadata[i];
  32932. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  32933. event.metadata.push(id3);
  32934. } // We add this to every single emitted segment even though we only need
  32935. // it for the first
  32936. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  32937. this.pendingTracks.length = 0;
  32938. this.videoTrack = null;
  32939. this.pendingBoxes.length = 0;
  32940. this.pendingCaptions.length = 0;
  32941. this.pendingBytes = 0;
  32942. this.pendingMetadata.length = 0; // Emit the built segment
  32943. // We include captions and ID3 tags for backwards compatibility,
  32944. // ideally we should send only video and audio in the data event
  32945. this.trigger('data', event); // Emit each caption to the outside world
  32946. // Ideally, this would happen immediately on parsing captions,
  32947. // but we need to ensure that video data is sent back first
  32948. // so that caption timing can be adjusted to match video timing
  32949. for (i = 0; i < event.captions.length; i++) {
  32950. caption = event.captions[i];
  32951. this.trigger('caption', caption);
  32952. } // Emit each id3 tag to the outside world
  32953. // Ideally, this would happen immediately on parsing the tag,
  32954. // but we need to ensure that video data is sent back first
  32955. // so that ID3 frame timing can be adjusted to match video timing
  32956. for (i = 0; i < event.metadata.length; i++) {
  32957. id3 = event.metadata[i];
  32958. this.trigger('id3Frame', id3);
  32959. }
  32960. } // Only emit `done` if all tracks have been flushed and emitted
  32961. if (this.emittedTracks >= this.numberOfTracks) {
  32962. this.trigger('done');
  32963. this.emittedTracks = 0;
  32964. }
  32965. };
  32966. _CoalesceStream.prototype.setRemux = function (val) {
  32967. this.remuxTracks = val;
  32968. };
  32969. /**
  32970. * A Stream that expects MP2T binary data as input and produces
  32971. * corresponding media segments, suitable for use with Media Source
  32972. * Extension (MSE) implementations that support the ISO BMFF byte
  32973. * stream format, like Chrome.
  32974. */
  32975. _Transmuxer = function Transmuxer(options) {
  32976. var self = this,
  32977. hasFlushed = true,
  32978. videoTrack,
  32979. audioTrack;
  32980. _Transmuxer.prototype.init.call(this);
  32981. options = options || {};
  32982. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  32983. this.transmuxPipeline_ = {};
  32984. this.setupAacPipeline = function () {
  32985. var pipeline = {};
  32986. this.transmuxPipeline_ = pipeline;
  32987. pipeline.type = 'aac';
  32988. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  32989. pipeline.aacStream = new aac();
  32990. pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
  32991. pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
  32992. pipeline.adtsStream = new adts();
  32993. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  32994. pipeline.headOfPipeline = pipeline.aacStream;
  32995. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  32996. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  32997. pipeline.metadataStream.on('timestamp', function (frame) {
  32998. pipeline.aacStream.setTimestamp(frame.timeStamp);
  32999. });
  33000. pipeline.aacStream.on('data', function (data) {
  33001. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  33002. return;
  33003. }
  33004. audioTrack = audioTrack || {
  33005. timelineStartInfo: {
  33006. baseMediaDecodeTime: self.baseMediaDecodeTime
  33007. },
  33008. codec: 'adts',
  33009. type: 'audio'
  33010. }; // hook up the audio segment stream to the first track with aac data
  33011. pipeline.coalesceStream.numberOfTracks++;
  33012. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  33013. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33014. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  33015. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  33016. self.trigger('trackinfo', {
  33017. hasAudio: !!audioTrack,
  33018. hasVideo: !!videoTrack
  33019. });
  33020. }); // Re-emit any data coming from the coalesce stream to the outside world
  33021. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  33022. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33023. addPipelineLogRetriggers(this, pipeline);
  33024. };
  33025. this.setupTsPipeline = function () {
  33026. var pipeline = {};
  33027. this.transmuxPipeline_ = pipeline;
  33028. pipeline.type = 'ts';
  33029. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  33030. pipeline.packetStream = new m2ts_1.TransportPacketStream();
  33031. pipeline.parseStream = new m2ts_1.TransportParseStream();
  33032. pipeline.elementaryStream = new m2ts_1.ElementaryStream();
  33033. pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
  33034. pipeline.adtsStream = new adts();
  33035. pipeline.h264Stream = new H264Stream();
  33036. pipeline.captionStream = new m2ts_1.CaptionStream(options);
  33037. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  33038. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  33039. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  33040. // demux the streams
  33041. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  33042. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  33043. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  33044. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  33045. pipeline.elementaryStream.on('data', function (data) {
  33046. var i;
  33047. if (data.type === 'metadata') {
  33048. i = data.tracks.length; // scan the tracks listed in the metadata
  33049. while (i--) {
  33050. if (!videoTrack && data.tracks[i].type === 'video') {
  33051. videoTrack = data.tracks[i];
  33052. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33053. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  33054. audioTrack = data.tracks[i];
  33055. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  33056. }
  33057. } // hook up the video segment stream to the first track with h264 data
  33058. if (videoTrack && !pipeline.videoSegmentStream) {
  33059. pipeline.coalesceStream.numberOfTracks++;
  33060. pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
  33061. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  33062. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  33063. // When video emits timelineStartInfo data after a flush, we forward that
  33064. // info to the AudioSegmentStream, if it exists, because video timeline
  33065. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  33066. // because this is a particularly subtle form of timestamp alteration.
  33067. if (audioTrack && !options.keepOriginalTimestamps) {
  33068. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  33069. // very earliest DTS we have seen in video because Chrome will
  33070. // interpret any video track with a baseMediaDecodeTime that is
  33071. // non-zero as a gap.
  33072. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  33073. }
  33074. });
  33075. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  33076. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  33077. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  33078. if (audioTrack) {
  33079. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  33080. }
  33081. });
  33082. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  33083. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  33084. }
  33085. if (audioTrack && !pipeline.audioSegmentStream) {
  33086. // hook up the audio segment stream to the first track with aac data
  33087. pipeline.coalesceStream.numberOfTracks++;
  33088. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  33089. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  33090. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  33091. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  33092. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  33093. } // emit pmt info
  33094. self.trigger('trackinfo', {
  33095. hasAudio: !!audioTrack,
  33096. hasVideo: !!videoTrack
  33097. });
  33098. }
  33099. }); // Re-emit any data coming from the coalesce stream to the outside world
  33100. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  33101. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  33102. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  33103. self.trigger('id3Frame', id3Frame);
  33104. });
  33105. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  33106. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  33107. addPipelineLogRetriggers(this, pipeline);
  33108. }; // hook up the segment streams once track metadata is delivered
  33109. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  33110. var pipeline = this.transmuxPipeline_;
  33111. if (!options.keepOriginalTimestamps) {
  33112. this.baseMediaDecodeTime = baseMediaDecodeTime;
  33113. }
  33114. if (audioTrack) {
  33115. audioTrack.timelineStartInfo.dts = undefined;
  33116. audioTrack.timelineStartInfo.pts = undefined;
  33117. trackDecodeInfo.clearDtsInfo(audioTrack);
  33118. if (pipeline.audioTimestampRolloverStream) {
  33119. pipeline.audioTimestampRolloverStream.discontinuity();
  33120. }
  33121. }
  33122. if (videoTrack) {
  33123. if (pipeline.videoSegmentStream) {
  33124. pipeline.videoSegmentStream.gopCache_ = [];
  33125. }
  33126. videoTrack.timelineStartInfo.dts = undefined;
  33127. videoTrack.timelineStartInfo.pts = undefined;
  33128. trackDecodeInfo.clearDtsInfo(videoTrack);
  33129. pipeline.captionStream.reset();
  33130. }
  33131. if (pipeline.timestampRolloverStream) {
  33132. pipeline.timestampRolloverStream.discontinuity();
  33133. }
  33134. };
  33135. this.setAudioAppendStart = function (timestamp) {
  33136. if (audioTrack) {
  33137. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  33138. }
  33139. };
  33140. this.setRemux = function (val) {
  33141. var pipeline = this.transmuxPipeline_;
  33142. options.remux = val;
  33143. if (pipeline && pipeline.coalesceStream) {
  33144. pipeline.coalesceStream.setRemux(val);
  33145. }
  33146. };
  33147. this.alignGopsWith = function (gopsToAlignWith) {
  33148. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  33149. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  33150. }
  33151. };
  33152. this.getLogTrigger_ = function (key) {
  33153. var self = this;
  33154. return function (event) {
  33155. event.stream = key;
  33156. self.trigger('log', event);
  33157. };
  33158. }; // feed incoming data to the front of the parsing pipeline
  33159. this.push = function (data) {
  33160. if (hasFlushed) {
  33161. var isAac = isLikelyAacData(data);
  33162. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  33163. this.setupAacPipeline();
  33164. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  33165. this.setupTsPipeline();
  33166. }
  33167. hasFlushed = false;
  33168. }
  33169. this.transmuxPipeline_.headOfPipeline.push(data);
  33170. }; // flush any buffered data
  33171. this.flush = function () {
  33172. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  33173. this.transmuxPipeline_.headOfPipeline.flush();
  33174. };
  33175. this.endTimeline = function () {
  33176. this.transmuxPipeline_.headOfPipeline.endTimeline();
  33177. };
  33178. this.reset = function () {
  33179. if (this.transmuxPipeline_.headOfPipeline) {
  33180. this.transmuxPipeline_.headOfPipeline.reset();
  33181. }
  33182. }; // Caption data has to be reset when seeking outside buffered range
  33183. this.resetCaptions = function () {
  33184. if (this.transmuxPipeline_.captionStream) {
  33185. this.transmuxPipeline_.captionStream.reset();
  33186. }
  33187. };
  33188. };
  33189. _Transmuxer.prototype = new stream();
  33190. var transmuxer = {
  33191. Transmuxer: _Transmuxer,
  33192. VideoSegmentStream: _VideoSegmentStream,
  33193. AudioSegmentStream: _AudioSegmentStream,
  33194. AUDIO_PROPERTIES: audioProperties,
  33195. VIDEO_PROPERTIES: videoProperties,
  33196. // exported for testing
  33197. generateSegmentTimingInfo: generateSegmentTimingInfo
  33198. };
  33199. /**
  33200. * mux.js
  33201. *
  33202. * Copyright (c) Brightcove
  33203. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  33204. */
  33205. var toUnsigned$3 = function toUnsigned(value) {
  33206. return value >>> 0;
  33207. };
  33208. var toHexString$1 = function toHexString(value) {
  33209. return ('00' + value.toString(16)).slice(-2);
  33210. };
  33211. var bin = {
  33212. toUnsigned: toUnsigned$3,
  33213. toHexString: toHexString$1
  33214. };
  33215. var parseType$1 = function parseType(buffer) {
  33216. var result = '';
  33217. result += String.fromCharCode(buffer[0]);
  33218. result += String.fromCharCode(buffer[1]);
  33219. result += String.fromCharCode(buffer[2]);
  33220. result += String.fromCharCode(buffer[3]);
  33221. return result;
  33222. };
  33223. var parseType_1 = parseType$1;
  33224. var toUnsigned$2 = bin.toUnsigned;
  33225. var findBox = function findBox(data, path) {
  33226. var results = [],
  33227. i,
  33228. size,
  33229. type,
  33230. end,
  33231. subresults;
  33232. if (!path.length) {
  33233. // short-circuit the search for empty paths
  33234. return null;
  33235. }
  33236. for (i = 0; i < data.byteLength;) {
  33237. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  33238. type = parseType_1(data.subarray(i + 4, i + 8));
  33239. end = size > 1 ? i + size : data.byteLength;
  33240. if (type === path[0]) {
  33241. if (path.length === 1) {
  33242. // this is the end of the path and we've found the box we were
  33243. // looking for
  33244. results.push(data.subarray(i + 8, end));
  33245. } else {
  33246. // recursively search for the next box along the path
  33247. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  33248. if (subresults.length) {
  33249. results = results.concat(subresults);
  33250. }
  33251. }
  33252. }
  33253. i = end;
  33254. } // we've finished searching all of data
  33255. return results;
  33256. };
  33257. var findBox_1 = findBox;
  33258. var toUnsigned$1 = bin.toUnsigned;
  33259. var getUint64$1 = numbers.getUint64;
  33260. var tfdt = function tfdt(data) {
  33261. var result = {
  33262. version: data[0],
  33263. flags: new Uint8Array(data.subarray(1, 4))
  33264. };
  33265. if (result.version === 1) {
  33266. result.baseMediaDecodeTime = getUint64$1(data.subarray(4));
  33267. } else {
  33268. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  33269. }
  33270. return result;
  33271. };
  33272. var parseTfdt = tfdt;
  33273. var parseSampleFlags = function parseSampleFlags(flags) {
  33274. return {
  33275. isLeading: (flags[0] & 0x0c) >>> 2,
  33276. dependsOn: flags[0] & 0x03,
  33277. isDependedOn: (flags[1] & 0xc0) >>> 6,
  33278. hasRedundancy: (flags[1] & 0x30) >>> 4,
  33279. paddingValue: (flags[1] & 0x0e) >>> 1,
  33280. isNonSyncSample: flags[1] & 0x01,
  33281. degradationPriority: flags[2] << 8 | flags[3]
  33282. };
  33283. };
  33284. var parseSampleFlags_1 = parseSampleFlags;
  33285. var trun = function trun(data) {
  33286. var result = {
  33287. version: data[0],
  33288. flags: new Uint8Array(data.subarray(1, 4)),
  33289. samples: []
  33290. },
  33291. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33292. // Flag interpretation
  33293. dataOffsetPresent = result.flags[2] & 0x01,
  33294. // compare with 2nd byte of 0x1
  33295. firstSampleFlagsPresent = result.flags[2] & 0x04,
  33296. // compare with 2nd byte of 0x4
  33297. sampleDurationPresent = result.flags[1] & 0x01,
  33298. // compare with 2nd byte of 0x100
  33299. sampleSizePresent = result.flags[1] & 0x02,
  33300. // compare with 2nd byte of 0x200
  33301. sampleFlagsPresent = result.flags[1] & 0x04,
  33302. // compare with 2nd byte of 0x400
  33303. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  33304. // compare with 2nd byte of 0x800
  33305. sampleCount = view.getUint32(4),
  33306. offset = 8,
  33307. sample;
  33308. if (dataOffsetPresent) {
  33309. // 32 bit signed integer
  33310. result.dataOffset = view.getInt32(offset);
  33311. offset += 4;
  33312. } // Overrides the flags for the first sample only. The order of
  33313. // optional values will be: duration, size, compositionTimeOffset
  33314. if (firstSampleFlagsPresent && sampleCount) {
  33315. sample = {
  33316. flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
  33317. };
  33318. offset += 4;
  33319. if (sampleDurationPresent) {
  33320. sample.duration = view.getUint32(offset);
  33321. offset += 4;
  33322. }
  33323. if (sampleSizePresent) {
  33324. sample.size = view.getUint32(offset);
  33325. offset += 4;
  33326. }
  33327. if (sampleCompositionTimeOffsetPresent) {
  33328. if (result.version === 1) {
  33329. sample.compositionTimeOffset = view.getInt32(offset);
  33330. } else {
  33331. sample.compositionTimeOffset = view.getUint32(offset);
  33332. }
  33333. offset += 4;
  33334. }
  33335. result.samples.push(sample);
  33336. sampleCount--;
  33337. }
  33338. while (sampleCount--) {
  33339. sample = {};
  33340. if (sampleDurationPresent) {
  33341. sample.duration = view.getUint32(offset);
  33342. offset += 4;
  33343. }
  33344. if (sampleSizePresent) {
  33345. sample.size = view.getUint32(offset);
  33346. offset += 4;
  33347. }
  33348. if (sampleFlagsPresent) {
  33349. sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
  33350. offset += 4;
  33351. }
  33352. if (sampleCompositionTimeOffsetPresent) {
  33353. if (result.version === 1) {
  33354. sample.compositionTimeOffset = view.getInt32(offset);
  33355. } else {
  33356. sample.compositionTimeOffset = view.getUint32(offset);
  33357. }
  33358. offset += 4;
  33359. }
  33360. result.samples.push(sample);
  33361. }
  33362. return result;
  33363. };
  33364. var parseTrun = trun;
  33365. var tfhd = function tfhd(data) {
  33366. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33367. result = {
  33368. version: data[0],
  33369. flags: new Uint8Array(data.subarray(1, 4)),
  33370. trackId: view.getUint32(4)
  33371. },
  33372. baseDataOffsetPresent = result.flags[2] & 0x01,
  33373. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  33374. defaultSampleDurationPresent = result.flags[2] & 0x08,
  33375. defaultSampleSizePresent = result.flags[2] & 0x10,
  33376. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  33377. durationIsEmpty = result.flags[0] & 0x010000,
  33378. defaultBaseIsMoof = result.flags[0] & 0x020000,
  33379. i;
  33380. i = 8;
  33381. if (baseDataOffsetPresent) {
  33382. i += 4; // truncate top 4 bytes
  33383. // FIXME: should we read the full 64 bits?
  33384. result.baseDataOffset = view.getUint32(12);
  33385. i += 4;
  33386. }
  33387. if (sampleDescriptionIndexPresent) {
  33388. result.sampleDescriptionIndex = view.getUint32(i);
  33389. i += 4;
  33390. }
  33391. if (defaultSampleDurationPresent) {
  33392. result.defaultSampleDuration = view.getUint32(i);
  33393. i += 4;
  33394. }
  33395. if (defaultSampleSizePresent) {
  33396. result.defaultSampleSize = view.getUint32(i);
  33397. i += 4;
  33398. }
  33399. if (defaultSampleFlagsPresent) {
  33400. result.defaultSampleFlags = view.getUint32(i);
  33401. }
  33402. if (durationIsEmpty) {
  33403. result.durationIsEmpty = true;
  33404. }
  33405. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  33406. result.baseDataOffsetIsMoof = true;
  33407. }
  33408. return result;
  33409. };
  33410. var parseTfhd = tfhd;
  33411. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  33412. var win;
  33413. if (typeof window !== "undefined") {
  33414. win = window;
  33415. } else if (typeof commonjsGlobal !== "undefined") {
  33416. win = commonjsGlobal;
  33417. } else if (typeof self !== "undefined") {
  33418. win = self;
  33419. } else {
  33420. win = {};
  33421. }
  33422. var window_1 = win;
  33423. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  33424. var CaptionStream = captionStream.CaptionStream;
  33425. /**
  33426. * Maps an offset in the mdat to a sample based on the the size of the samples.
  33427. * Assumes that `parseSamples` has been called first.
  33428. *
  33429. * @param {Number} offset - The offset into the mdat
  33430. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  33431. * @return {?Object} The matching sample, or null if no match was found.
  33432. *
  33433. * @see ISO-BMFF-12/2015, Section 8.8.8
  33434. **/
  33435. var mapToSample = function mapToSample(offset, samples) {
  33436. var approximateOffset = offset;
  33437. for (var i = 0; i < samples.length; i++) {
  33438. var sample = samples[i];
  33439. if (approximateOffset < sample.size) {
  33440. return sample;
  33441. }
  33442. approximateOffset -= sample.size;
  33443. }
  33444. return null;
  33445. };
  33446. /**
  33447. * Finds SEI nal units contained in a Media Data Box.
  33448. * Assumes that `parseSamples` has been called first.
  33449. *
  33450. * @param {Uint8Array} avcStream - The bytes of the mdat
  33451. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  33452. * @param {Number} trackId - The trackId of this video track
  33453. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  33454. * The contents of the seiNal should match what is expected by
  33455. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  33456. *
  33457. * @see ISO-BMFF-12/2015, Section 8.1.1
  33458. * @see Rec. ITU-T H.264, 7.3.2.3.1
  33459. **/
  33460. var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
  33461. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  33462. result = {
  33463. logs: [],
  33464. seiNals: []
  33465. },
  33466. seiNal,
  33467. i,
  33468. length,
  33469. lastMatchedSample;
  33470. for (i = 0; i + 4 < avcStream.length; i += length) {
  33471. length = avcView.getUint32(i);
  33472. i += 4; // Bail if this doesn't appear to be an H264 stream
  33473. if (length <= 0) {
  33474. continue;
  33475. }
  33476. switch (avcStream[i] & 0x1F) {
  33477. case 0x06:
  33478. var data = avcStream.subarray(i + 1, i + 1 + length);
  33479. var matchingSample = mapToSample(i, samples);
  33480. seiNal = {
  33481. nalUnitType: 'sei_rbsp',
  33482. size: length,
  33483. data: data,
  33484. escapedRBSP: discardEmulationPreventionBytes(data),
  33485. trackId: trackId
  33486. };
  33487. if (matchingSample) {
  33488. seiNal.pts = matchingSample.pts;
  33489. seiNal.dts = matchingSample.dts;
  33490. lastMatchedSample = matchingSample;
  33491. } else if (lastMatchedSample) {
  33492. // If a matching sample cannot be found, use the last
  33493. // sample's values as they should be as close as possible
  33494. seiNal.pts = lastMatchedSample.pts;
  33495. seiNal.dts = lastMatchedSample.dts;
  33496. } else {
  33497. result.logs.push({
  33498. level: 'warn',
  33499. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  33500. });
  33501. break;
  33502. }
  33503. result.seiNals.push(seiNal);
  33504. break;
  33505. }
  33506. }
  33507. return result;
  33508. };
  33509. /**
  33510. * Parses sample information out of Track Run Boxes and calculates
  33511. * the absolute presentation and decode timestamps of each sample.
  33512. *
  33513. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  33514. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  33515. @see ISO-BMFF-12/2015, Section 8.8.12
  33516. * @param {Object} tfhd - The parsed Track Fragment Header
  33517. * @see inspect.parseTfhd
  33518. * @return {Object[]} the parsed samples
  33519. *
  33520. * @see ISO-BMFF-12/2015, Section 8.8.8
  33521. **/
  33522. var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
  33523. var currentDts = baseMediaDecodeTime;
  33524. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  33525. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  33526. var trackId = tfhd.trackId;
  33527. var allSamples = [];
  33528. truns.forEach(function (trun) {
  33529. // Note: We currently do not parse the sample table as well
  33530. // as the trun. It's possible some sources will require this.
  33531. // moov > trak > mdia > minf > stbl
  33532. var trackRun = parseTrun(trun);
  33533. var samples = trackRun.samples;
  33534. samples.forEach(function (sample) {
  33535. if (sample.duration === undefined) {
  33536. sample.duration = defaultSampleDuration;
  33537. }
  33538. if (sample.size === undefined) {
  33539. sample.size = defaultSampleSize;
  33540. }
  33541. sample.trackId = trackId;
  33542. sample.dts = currentDts;
  33543. if (sample.compositionTimeOffset === undefined) {
  33544. sample.compositionTimeOffset = 0;
  33545. }
  33546. if (typeof currentDts === 'bigint') {
  33547. sample.pts = currentDts + window_1.BigInt(sample.compositionTimeOffset);
  33548. currentDts += window_1.BigInt(sample.duration);
  33549. } else {
  33550. sample.pts = currentDts + sample.compositionTimeOffset;
  33551. currentDts += sample.duration;
  33552. }
  33553. });
  33554. allSamples = allSamples.concat(samples);
  33555. });
  33556. return allSamples;
  33557. };
  33558. /**
  33559. * Parses out caption nals from an FMP4 segment's video tracks.
  33560. *
  33561. * @param {Uint8Array} segment - The bytes of a single segment
  33562. * @param {Number} videoTrackId - The trackId of a video track in the segment
  33563. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  33564. * a list of seiNals found in that track
  33565. **/
  33566. var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
  33567. // To get the samples
  33568. var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
  33569. var mdats = findBox_1(segment, ['mdat']);
  33570. var captionNals = {};
  33571. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  33572. mdats.forEach(function (mdat, index) {
  33573. var matchingTraf = trafs[index];
  33574. mdatTrafPairs.push({
  33575. mdat: mdat,
  33576. traf: matchingTraf
  33577. });
  33578. });
  33579. mdatTrafPairs.forEach(function (pair) {
  33580. var mdat = pair.mdat;
  33581. var traf = pair.traf;
  33582. var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  33583. var headerInfo = parseTfhd(tfhd[0]);
  33584. var trackId = headerInfo.trackId;
  33585. var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  33586. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  33587. var truns = findBox_1(traf, ['trun']);
  33588. var samples;
  33589. var result; // Only parse video data for the chosen video track
  33590. if (videoTrackId === trackId && truns.length > 0) {
  33591. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  33592. result = findSeiNals(mdat, samples, trackId);
  33593. if (!captionNals[trackId]) {
  33594. captionNals[trackId] = {
  33595. seiNals: [],
  33596. logs: []
  33597. };
  33598. }
  33599. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  33600. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  33601. }
  33602. });
  33603. return captionNals;
  33604. };
  33605. /**
  33606. * Parses out inband captions from an MP4 container and returns
  33607. * caption objects that can be used by WebVTT and the TextTrack API.
  33608. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  33609. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  33610. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  33611. *
  33612. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33613. * @param {Number} trackId - The id of the video track to parse
  33614. * @param {Number} timescale - The timescale for the video track from the init segment
  33615. *
  33616. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  33617. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  33618. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  33619. * @return {String} parsedCaptions[].text - The visible content of the caption
  33620. **/
  33621. var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
  33622. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33623. if (trackId === null) {
  33624. return null;
  33625. }
  33626. captionNals = parseCaptionNals(segment, trackId);
  33627. var trackNals = captionNals[trackId] || {};
  33628. return {
  33629. seiNals: trackNals.seiNals,
  33630. logs: trackNals.logs,
  33631. timescale: timescale
  33632. };
  33633. };
  33634. /**
  33635. * Converts SEI NALUs into captions that can be used by video.js
  33636. **/
  33637. var CaptionParser = function CaptionParser() {
  33638. var isInitialized = false;
  33639. var captionStream; // Stores segments seen before trackId and timescale are set
  33640. var segmentCache; // Stores video track ID of the track being parsed
  33641. var trackId; // Stores the timescale of the track being parsed
  33642. var timescale; // Stores captions parsed so far
  33643. var parsedCaptions; // Stores whether we are receiving partial data or not
  33644. var parsingPartial;
  33645. /**
  33646. * A method to indicate whether a CaptionParser has been initalized
  33647. * @returns {Boolean}
  33648. **/
  33649. this.isInitialized = function () {
  33650. return isInitialized;
  33651. };
  33652. /**
  33653. * Initializes the underlying CaptionStream, SEI NAL parsing
  33654. * and management, and caption collection
  33655. **/
  33656. this.init = function (options) {
  33657. captionStream = new CaptionStream();
  33658. isInitialized = true;
  33659. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  33660. captionStream.on('data', function (event) {
  33661. // Convert to seconds in the source's timescale
  33662. event.startTime = event.startPts / timescale;
  33663. event.endTime = event.endPts / timescale;
  33664. parsedCaptions.captions.push(event);
  33665. parsedCaptions.captionStreams[event.stream] = true;
  33666. });
  33667. captionStream.on('log', function (log) {
  33668. parsedCaptions.logs.push(log);
  33669. });
  33670. };
  33671. /**
  33672. * Determines if a new video track will be selected
  33673. * or if the timescale changed
  33674. * @return {Boolean}
  33675. **/
  33676. this.isNewInit = function (videoTrackIds, timescales) {
  33677. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  33678. return false;
  33679. }
  33680. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  33681. };
  33682. /**
  33683. * Parses out SEI captions and interacts with underlying
  33684. * CaptionStream to return dispatched captions
  33685. *
  33686. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  33687. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  33688. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  33689. * @see parseEmbeddedCaptions
  33690. * @see m2ts/caption-stream.js
  33691. **/
  33692. this.parse = function (segment, videoTrackIds, timescales) {
  33693. var parsedData;
  33694. if (!this.isInitialized()) {
  33695. return null; // This is not likely to be a video segment
  33696. } else if (!videoTrackIds || !timescales) {
  33697. return null;
  33698. } else if (this.isNewInit(videoTrackIds, timescales)) {
  33699. // Use the first video track only as there is no
  33700. // mechanism to switch to other video tracks
  33701. trackId = videoTrackIds[0];
  33702. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  33703. // data until we have one.
  33704. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  33705. } else if (trackId === null || !timescale) {
  33706. segmentCache.push(segment);
  33707. return null;
  33708. } // Now that a timescale and trackId is set, parse cached segments
  33709. while (segmentCache.length > 0) {
  33710. var cachedSegment = segmentCache.shift();
  33711. this.parse(cachedSegment, videoTrackIds, timescales);
  33712. }
  33713. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  33714. if (parsedData && parsedData.logs) {
  33715. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  33716. }
  33717. if (parsedData === null || !parsedData.seiNals) {
  33718. if (parsedCaptions.logs.length) {
  33719. return {
  33720. logs: parsedCaptions.logs,
  33721. captions: [],
  33722. captionStreams: []
  33723. };
  33724. }
  33725. return null;
  33726. }
  33727. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  33728. this.flushStream();
  33729. return parsedCaptions;
  33730. };
  33731. /**
  33732. * Pushes SEI NALUs onto CaptionStream
  33733. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  33734. * Assumes that `parseCaptionNals` has been called first
  33735. * @see m2ts/caption-stream.js
  33736. **/
  33737. this.pushNals = function (nals) {
  33738. if (!this.isInitialized() || !nals || nals.length === 0) {
  33739. return null;
  33740. }
  33741. nals.forEach(function (nal) {
  33742. captionStream.push(nal);
  33743. });
  33744. };
  33745. /**
  33746. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  33747. * @see m2ts/caption-stream.js
  33748. **/
  33749. this.flushStream = function () {
  33750. if (!this.isInitialized()) {
  33751. return null;
  33752. }
  33753. if (!parsingPartial) {
  33754. captionStream.flush();
  33755. } else {
  33756. captionStream.partialFlush();
  33757. }
  33758. };
  33759. /**
  33760. * Reset caption buckets for new data
  33761. **/
  33762. this.clearParsedCaptions = function () {
  33763. parsedCaptions.captions = [];
  33764. parsedCaptions.captionStreams = {};
  33765. parsedCaptions.logs = [];
  33766. };
  33767. /**
  33768. * Resets underlying CaptionStream
  33769. * @see m2ts/caption-stream.js
  33770. **/
  33771. this.resetCaptionStream = function () {
  33772. if (!this.isInitialized()) {
  33773. return null;
  33774. }
  33775. captionStream.reset();
  33776. };
  33777. /**
  33778. * Convenience method to clear all captions flushed from the
  33779. * CaptionStream and still being parsed
  33780. * @see m2ts/caption-stream.js
  33781. **/
  33782. this.clearAllCaptions = function () {
  33783. this.clearParsedCaptions();
  33784. this.resetCaptionStream();
  33785. };
  33786. /**
  33787. * Reset caption parser
  33788. **/
  33789. this.reset = function () {
  33790. segmentCache = [];
  33791. trackId = null;
  33792. timescale = null;
  33793. if (!parsedCaptions) {
  33794. parsedCaptions = {
  33795. captions: [],
  33796. // CC1, CC2, CC3, CC4
  33797. captionStreams: {},
  33798. logs: []
  33799. };
  33800. } else {
  33801. this.clearParsedCaptions();
  33802. }
  33803. this.resetCaptionStream();
  33804. };
  33805. this.reset();
  33806. };
  33807. var captionParser = CaptionParser;
  33808. var toUnsigned = bin.toUnsigned;
  33809. var toHexString = bin.toHexString;
  33810. var getUint64 = numbers.getUint64;
  33811. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
  33812. /**
  33813. * Parses an MP4 initialization segment and extracts the timescale
  33814. * values for any declared tracks. Timescale values indicate the
  33815. * number of clock ticks per second to assume for time-based values
  33816. * elsewhere in the MP4.
  33817. *
  33818. * To determine the start time of an MP4, you need two pieces of
  33819. * information: the timescale unit and the earliest base media decode
  33820. * time. Multiple timescales can be specified within an MP4 but the
  33821. * base media decode time is always expressed in the timescale from
  33822. * the media header box for the track:
  33823. * ```
  33824. * moov > trak > mdia > mdhd.timescale
  33825. * ```
  33826. * @param init {Uint8Array} the bytes of the init segment
  33827. * @return {object} a hash of track ids to timescale values or null if
  33828. * the init segment is malformed.
  33829. */
  33830. timescale = function timescale(init) {
  33831. var result = {},
  33832. traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
  33833. return traks.reduce(function (result, trak) {
  33834. var tkhd, version, index, id, mdhd;
  33835. tkhd = findBox_1(trak, ['tkhd'])[0];
  33836. if (!tkhd) {
  33837. return null;
  33838. }
  33839. version = tkhd[0];
  33840. index = version === 0 ? 12 : 20;
  33841. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  33842. mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  33843. if (!mdhd) {
  33844. return null;
  33845. }
  33846. version = mdhd[0];
  33847. index = version === 0 ? 12 : 20;
  33848. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  33849. return result;
  33850. }, result);
  33851. };
  33852. /**
  33853. * Determine the base media decode start time, in seconds, for an MP4
  33854. * fragment. If multiple fragments are specified, the earliest time is
  33855. * returned.
  33856. *
  33857. * The base media decode time can be parsed from track fragment
  33858. * metadata:
  33859. * ```
  33860. * moof > traf > tfdt.baseMediaDecodeTime
  33861. * ```
  33862. * It requires the timescale value from the mdhd to interpret.
  33863. *
  33864. * @param timescale {object} a hash of track ids to timescale values.
  33865. * @return {number} the earliest base media decode start time for the
  33866. * fragment, in seconds
  33867. */
  33868. startTime = function startTime(timescale, fragment) {
  33869. var trafs; // we need info from two childrend of each track fragment box
  33870. trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
  33871. var lowestTime = trafs.reduce(function (acc, traf) {
  33872. var tfhd = findBox_1(traf, ['tfhd'])[0]; // get the track id from the tfhd
  33873. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  33874. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  33875. var tfdt = findBox_1(traf, ['tfdt'])[0];
  33876. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  33877. var baseTime; // version 1 is 64 bit
  33878. if (tfdt[0] === 1) {
  33879. baseTime = getUint64(tfdt.subarray(4, 12));
  33880. } else {
  33881. baseTime = dv.getUint32(4);
  33882. } // convert base time to seconds if it is a valid number.
  33883. var seconds;
  33884. if (typeof baseTime === 'bigint') {
  33885. seconds = baseTime / window_1.BigInt(scale);
  33886. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  33887. seconds = baseTime / scale;
  33888. }
  33889. if (seconds < Number.MAX_SAFE_INTEGER) {
  33890. seconds = Number(seconds);
  33891. }
  33892. if (seconds < acc) {
  33893. acc = seconds;
  33894. }
  33895. return acc;
  33896. }, Infinity);
  33897. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  33898. };
  33899. /**
  33900. * Determine the composition start, in seconds, for an MP4
  33901. * fragment.
  33902. *
  33903. * The composition start time of a fragment can be calculated using the base
  33904. * media decode time, composition time offset, and timescale, as follows:
  33905. *
  33906. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  33907. *
  33908. * All of the aforementioned information is contained within a media fragment's
  33909. * `traf` box, except for timescale info, which comes from the initialization
  33910. * segment, so a track id (also contained within a `traf`) is also necessary to
  33911. * associate it with a timescale
  33912. *
  33913. *
  33914. * @param timescales {object} - a hash of track ids to timescale values.
  33915. * @param fragment {Unit8Array} - the bytes of a media segment
  33916. * @return {number} the composition start time for the fragment, in seconds
  33917. **/
  33918. compositionStartTime = function compositionStartTime(timescales, fragment) {
  33919. var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
  33920. var baseMediaDecodeTime = 0;
  33921. var compositionTimeOffset = 0;
  33922. var trackId;
  33923. if (trafBoxes && trafBoxes.length) {
  33924. // The spec states that track run samples contained within a `traf` box are contiguous, but
  33925. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  33926. // We will assume that they are, so we only need the first to calculate start time.
  33927. var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
  33928. var trun = findBox_1(trafBoxes[0], ['trun'])[0];
  33929. var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
  33930. if (tfhd) {
  33931. var parsedTfhd = parseTfhd(tfhd);
  33932. trackId = parsedTfhd.trackId;
  33933. }
  33934. if (tfdt) {
  33935. var parsedTfdt = parseTfdt(tfdt);
  33936. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  33937. }
  33938. if (trun) {
  33939. var parsedTrun = parseTrun(trun);
  33940. if (parsedTrun.samples && parsedTrun.samples.length) {
  33941. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  33942. }
  33943. }
  33944. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  33945. // specified.
  33946. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  33947. if (typeof baseMediaDecodeTime === 'bigint') {
  33948. compositionTimeOffset = window_1.BigInt(compositionTimeOffset);
  33949. timescale = window_1.BigInt(timescale);
  33950. }
  33951. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  33952. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  33953. result = Number(result);
  33954. }
  33955. return result;
  33956. };
  33957. /**
  33958. * Find the trackIds of the video tracks in this source.
  33959. * Found by parsing the Handler Reference and Track Header Boxes:
  33960. * moov > trak > mdia > hdlr
  33961. * moov > trak > tkhd
  33962. *
  33963. * @param {Uint8Array} init - The bytes of the init segment for this source
  33964. * @return {Number[]} A list of trackIds
  33965. *
  33966. * @see ISO-BMFF-12/2015, Section 8.4.3
  33967. **/
  33968. getVideoTrackIds = function getVideoTrackIds(init) {
  33969. var traks = findBox_1(init, ['moov', 'trak']);
  33970. var videoTrackIds = [];
  33971. traks.forEach(function (trak) {
  33972. var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
  33973. var tkhds = findBox_1(trak, ['tkhd']);
  33974. hdlrs.forEach(function (hdlr, index) {
  33975. var handlerType = parseType_1(hdlr.subarray(8, 12));
  33976. var tkhd = tkhds[index];
  33977. var view;
  33978. var version;
  33979. var trackId;
  33980. if (handlerType === 'vide') {
  33981. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  33982. version = view.getUint8(0);
  33983. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  33984. videoTrackIds.push(trackId);
  33985. }
  33986. });
  33987. });
  33988. return videoTrackIds;
  33989. };
  33990. getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
  33991. // mdhd is a FullBox, meaning it will have its own version as the first byte
  33992. var version = mdhd[0];
  33993. var index = version === 0 ? 12 : 20;
  33994. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  33995. };
  33996. /**
  33997. * Get all the video, audio, and hint tracks from a non fragmented
  33998. * mp4 segment
  33999. */
  34000. getTracks = function getTracks(init) {
  34001. var traks = findBox_1(init, ['moov', 'trak']);
  34002. var tracks = [];
  34003. traks.forEach(function (trak) {
  34004. var track = {};
  34005. var tkhd = findBox_1(trak, ['tkhd'])[0];
  34006. var view, tkhdVersion; // id
  34007. if (tkhd) {
  34008. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  34009. tkhdVersion = view.getUint8(0);
  34010. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  34011. }
  34012. var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
  34013. if (hdlr) {
  34014. var type = parseType_1(hdlr.subarray(8, 12));
  34015. if (type === 'vide') {
  34016. track.type = 'video';
  34017. } else if (type === 'soun') {
  34018. track.type = 'audio';
  34019. } else {
  34020. track.type = type;
  34021. }
  34022. } // codec
  34023. var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  34024. if (stsd) {
  34025. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  34026. track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
  34027. var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
  34028. var codecConfig, codecConfigType;
  34029. if (codecBox) {
  34030. // https://tools.ietf.org/html/rfc6381#section-3.3
  34031. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  34032. // we don't need anything but the "config" parameter of the
  34033. // avc1 codecBox
  34034. codecConfig = codecBox.subarray(78);
  34035. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  34036. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  34037. track.codec += '.'; // left padded with zeroes for single digit hex
  34038. // profile idc
  34039. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  34040. track.codec += toHexString(codecConfig[10]); // level idc
  34041. track.codec += toHexString(codecConfig[11]);
  34042. } else {
  34043. // TODO: show a warning that we couldn't parse the codec
  34044. // and are using the default
  34045. track.codec = 'avc1.4d400d';
  34046. }
  34047. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  34048. // we do not need anything but the streamDescriptor of the mp4a codecBox
  34049. codecConfig = codecBox.subarray(28);
  34050. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  34051. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  34052. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  34053. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  34054. } else {
  34055. // TODO: show a warning that we couldn't parse the codec
  34056. // and are using the default
  34057. track.codec = 'mp4a.40.2';
  34058. }
  34059. } else {
  34060. // flac, opus, etc
  34061. track.codec = track.codec.toLowerCase();
  34062. }
  34063. }
  34064. }
  34065. var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  34066. if (mdhd) {
  34067. track.timescale = getTimescaleFromMediaHeader(mdhd);
  34068. }
  34069. tracks.push(track);
  34070. });
  34071. return tracks;
  34072. };
  34073. var probe$2 = {
  34074. // export mp4 inspector's findBox and parseType for backwards compatibility
  34075. findBox: findBox_1,
  34076. parseType: parseType_1,
  34077. timescale: timescale,
  34078. startTime: startTime,
  34079. compositionStartTime: compositionStartTime,
  34080. videoTrackIds: getVideoTrackIds,
  34081. tracks: getTracks,
  34082. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
  34083. };
  34084. var parsePid = function parsePid(packet) {
  34085. var pid = packet[1] & 0x1f;
  34086. pid <<= 8;
  34087. pid |= packet[2];
  34088. return pid;
  34089. };
  34090. var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
  34091. return !!(packet[1] & 0x40);
  34092. };
  34093. var parseAdaptionField = function parseAdaptionField(packet) {
  34094. var offset = 0; // if an adaption field is present, its length is specified by the
  34095. // fifth byte of the TS packet header. The adaptation field is
  34096. // used to add stuffing to PES packets that don't fill a complete
  34097. // TS packet, and to specify some forms of timing and control data
  34098. // that we do not currently use.
  34099. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  34100. offset += packet[4] + 1;
  34101. }
  34102. return offset;
  34103. };
  34104. var parseType = function parseType(packet, pmtPid) {
  34105. var pid = parsePid(packet);
  34106. if (pid === 0) {
  34107. return 'pat';
  34108. } else if (pid === pmtPid) {
  34109. return 'pmt';
  34110. } else if (pmtPid) {
  34111. return 'pes';
  34112. }
  34113. return null;
  34114. };
  34115. var parsePat = function parsePat(packet) {
  34116. var pusi = parsePayloadUnitStartIndicator(packet);
  34117. var offset = 4 + parseAdaptionField(packet);
  34118. if (pusi) {
  34119. offset += packet[offset] + 1;
  34120. }
  34121. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  34122. };
  34123. var parsePmt = function parsePmt(packet) {
  34124. var programMapTable = {};
  34125. var pusi = parsePayloadUnitStartIndicator(packet);
  34126. var payloadOffset = 4 + parseAdaptionField(packet);
  34127. if (pusi) {
  34128. payloadOffset += packet[payloadOffset] + 1;
  34129. } // PMTs can be sent ahead of the time when they should actually
  34130. // take effect. We don't believe this should ever be the case
  34131. // for HLS but we'll ignore "forward" PMT declarations if we see
  34132. // them. Future PMT declarations have the current_next_indicator
  34133. // set to zero.
  34134. if (!(packet[payloadOffset + 5] & 0x01)) {
  34135. return;
  34136. }
  34137. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  34138. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  34139. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  34140. // long the program info descriptors are
  34141. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  34142. var offset = 12 + programInfoLength;
  34143. while (offset < tableEnd) {
  34144. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  34145. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  34146. // skip past the elementary stream descriptors, if present
  34147. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  34148. }
  34149. return programMapTable;
  34150. };
  34151. var parsePesType = function parsePesType(packet, programMapTable) {
  34152. var pid = parsePid(packet);
  34153. var type = programMapTable[pid];
  34154. switch (type) {
  34155. case streamTypes.H264_STREAM_TYPE:
  34156. return 'video';
  34157. case streamTypes.ADTS_STREAM_TYPE:
  34158. return 'audio';
  34159. case streamTypes.METADATA_STREAM_TYPE:
  34160. return 'timed-metadata';
  34161. default:
  34162. return null;
  34163. }
  34164. };
  34165. var parsePesTime = function parsePesTime(packet) {
  34166. var pusi = parsePayloadUnitStartIndicator(packet);
  34167. if (!pusi) {
  34168. return null;
  34169. }
  34170. var offset = 4 + parseAdaptionField(packet);
  34171. if (offset >= packet.byteLength) {
  34172. // From the H 222.0 MPEG-TS spec
  34173. // "For transport stream packets carrying PES packets, stuffing is needed when there
  34174. // is insufficient PES packet data to completely fill the transport stream packet
  34175. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  34176. // the sum of the lengths of the data elements in it, so that the payload bytes
  34177. // remaining after the adaptation field exactly accommodates the available PES packet
  34178. // data."
  34179. //
  34180. // If the offset is >= the length of the packet, then the packet contains no data
  34181. // and instead is just adaption field stuffing bytes
  34182. return null;
  34183. }
  34184. var pes = null;
  34185. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  34186. // and a DTS value. Determine what combination of values is
  34187. // available to work with.
  34188. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  34189. // performs all bitwise operations on 32-bit integers but javascript
  34190. // supports a much greater range (52-bits) of integer using standard
  34191. // mathematical operations.
  34192. // We construct a 31-bit value using bitwise operators over the 31
  34193. // most significant bits and then multiply by 4 (equal to a left-shift
  34194. // of 2) before we add the final 2 least significant bits of the
  34195. // timestamp (equal to an OR.)
  34196. if (ptsDtsFlags & 0xC0) {
  34197. pes = {}; // the PTS and DTS are not written out directly. For information
  34198. // on how they are encoded, see
  34199. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  34200. 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;
  34201. pes.pts *= 4; // Left shift by 2
  34202. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  34203. pes.dts = pes.pts;
  34204. if (ptsDtsFlags & 0x40) {
  34205. 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;
  34206. pes.dts *= 4; // Left shift by 2
  34207. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  34208. }
  34209. }
  34210. return pes;
  34211. };
  34212. var parseNalUnitType = function parseNalUnitType(type) {
  34213. switch (type) {
  34214. case 0x05:
  34215. return 'slice_layer_without_partitioning_rbsp_idr';
  34216. case 0x06:
  34217. return 'sei_rbsp';
  34218. case 0x07:
  34219. return 'seq_parameter_set_rbsp';
  34220. case 0x08:
  34221. return 'pic_parameter_set_rbsp';
  34222. case 0x09:
  34223. return 'access_unit_delimiter_rbsp';
  34224. default:
  34225. return null;
  34226. }
  34227. };
  34228. var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
  34229. var offset = 4 + parseAdaptionField(packet);
  34230. var frameBuffer = packet.subarray(offset);
  34231. var frameI = 0;
  34232. var frameSyncPoint = 0;
  34233. var foundKeyFrame = false;
  34234. var nalType; // advance the sync point to a NAL start, if necessary
  34235. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  34236. if (frameBuffer[frameSyncPoint + 2] === 1) {
  34237. // the sync point is properly aligned
  34238. frameI = frameSyncPoint + 5;
  34239. break;
  34240. }
  34241. }
  34242. while (frameI < frameBuffer.byteLength) {
  34243. // look at the current byte to determine if we've hit the end of
  34244. // a NAL unit boundary
  34245. switch (frameBuffer[frameI]) {
  34246. case 0:
  34247. // skip past non-sync sequences
  34248. if (frameBuffer[frameI - 1] !== 0) {
  34249. frameI += 2;
  34250. break;
  34251. } else if (frameBuffer[frameI - 2] !== 0) {
  34252. frameI++;
  34253. break;
  34254. }
  34255. if (frameSyncPoint + 3 !== frameI - 2) {
  34256. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34257. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34258. foundKeyFrame = true;
  34259. }
  34260. } // drop trailing zeroes
  34261. do {
  34262. frameI++;
  34263. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  34264. frameSyncPoint = frameI - 2;
  34265. frameI += 3;
  34266. break;
  34267. case 1:
  34268. // skip past non-sync sequences
  34269. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  34270. frameI += 3;
  34271. break;
  34272. }
  34273. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34274. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34275. foundKeyFrame = true;
  34276. }
  34277. frameSyncPoint = frameI - 2;
  34278. frameI += 3;
  34279. break;
  34280. default:
  34281. // the current byte isn't a one or zero, so it cannot be part
  34282. // of a sync sequence
  34283. frameI += 3;
  34284. break;
  34285. }
  34286. }
  34287. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  34288. frameI -= frameSyncPoint;
  34289. frameSyncPoint = 0; // parse the final nal
  34290. if (frameBuffer && frameBuffer.byteLength > 3) {
  34291. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  34292. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  34293. foundKeyFrame = true;
  34294. }
  34295. }
  34296. return foundKeyFrame;
  34297. };
  34298. var probe$1 = {
  34299. parseType: parseType,
  34300. parsePat: parsePat,
  34301. parsePmt: parsePmt,
  34302. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  34303. parsePesType: parsePesType,
  34304. parsePesTime: parsePesTime,
  34305. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  34306. };
  34307. var handleRollover = timestampRolloverStream.handleRollover;
  34308. var probe = {};
  34309. probe.ts = probe$1;
  34310. probe.aac = utils;
  34311. var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
  34312. var MP2T_PACKET_LENGTH = 188,
  34313. // bytes
  34314. SYNC_BYTE = 0x47;
  34315. /**
  34316. * walks through segment data looking for pat and pmt packets to parse out
  34317. * program map table information
  34318. */
  34319. var parsePsi_ = function parsePsi_(bytes, pmt) {
  34320. var startIndex = 0,
  34321. endIndex = MP2T_PACKET_LENGTH,
  34322. packet,
  34323. type;
  34324. while (endIndex < bytes.byteLength) {
  34325. // Look for a pair of start and end sync bytes in the data..
  34326. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34327. // We found a packet
  34328. packet = bytes.subarray(startIndex, endIndex);
  34329. type = probe.ts.parseType(packet, pmt.pid);
  34330. switch (type) {
  34331. case 'pat':
  34332. pmt.pid = probe.ts.parsePat(packet);
  34333. break;
  34334. case 'pmt':
  34335. var table = probe.ts.parsePmt(packet);
  34336. pmt.table = pmt.table || {};
  34337. Object.keys(table).forEach(function (key) {
  34338. pmt.table[key] = table[key];
  34339. });
  34340. break;
  34341. }
  34342. startIndex += MP2T_PACKET_LENGTH;
  34343. endIndex += MP2T_PACKET_LENGTH;
  34344. continue;
  34345. } // If we get here, we have somehow become de-synchronized and we need to step
  34346. // forward one byte at a time until we find a pair of sync bytes that denote
  34347. // a packet
  34348. startIndex++;
  34349. endIndex++;
  34350. }
  34351. };
  34352. /**
  34353. * walks through the segment data from the start and end to get timing information
  34354. * for the first and last audio pes packets
  34355. */
  34356. var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
  34357. var startIndex = 0,
  34358. endIndex = MP2T_PACKET_LENGTH,
  34359. packet,
  34360. type,
  34361. pesType,
  34362. pusi,
  34363. parsed;
  34364. var endLoop = false; // Start walking from start of segment to get first audio packet
  34365. while (endIndex <= bytes.byteLength) {
  34366. // Look for a pair of start and end sync bytes in the data..
  34367. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34368. // We found a packet
  34369. packet = bytes.subarray(startIndex, endIndex);
  34370. type = probe.ts.parseType(packet, pmt.pid);
  34371. switch (type) {
  34372. case 'pes':
  34373. pesType = probe.ts.parsePesType(packet, pmt.table);
  34374. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34375. if (pesType === 'audio' && pusi) {
  34376. parsed = probe.ts.parsePesTime(packet);
  34377. if (parsed) {
  34378. parsed.type = 'audio';
  34379. result.audio.push(parsed);
  34380. endLoop = true;
  34381. }
  34382. }
  34383. break;
  34384. }
  34385. if (endLoop) {
  34386. break;
  34387. }
  34388. startIndex += MP2T_PACKET_LENGTH;
  34389. endIndex += MP2T_PACKET_LENGTH;
  34390. continue;
  34391. } // If we get here, we have somehow become de-synchronized and we need to step
  34392. // forward one byte at a time until we find a pair of sync bytes that denote
  34393. // a packet
  34394. startIndex++;
  34395. endIndex++;
  34396. } // Start walking from end of segment to get last audio packet
  34397. endIndex = bytes.byteLength;
  34398. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34399. endLoop = false;
  34400. while (startIndex >= 0) {
  34401. // Look for a pair of start and end sync bytes in the data..
  34402. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  34403. // We found a packet
  34404. packet = bytes.subarray(startIndex, endIndex);
  34405. type = probe.ts.parseType(packet, pmt.pid);
  34406. switch (type) {
  34407. case 'pes':
  34408. pesType = probe.ts.parsePesType(packet, pmt.table);
  34409. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34410. if (pesType === 'audio' && pusi) {
  34411. parsed = probe.ts.parsePesTime(packet);
  34412. if (parsed) {
  34413. parsed.type = 'audio';
  34414. result.audio.push(parsed);
  34415. endLoop = true;
  34416. }
  34417. }
  34418. break;
  34419. }
  34420. if (endLoop) {
  34421. break;
  34422. }
  34423. startIndex -= MP2T_PACKET_LENGTH;
  34424. endIndex -= MP2T_PACKET_LENGTH;
  34425. continue;
  34426. } // If we get here, we have somehow become de-synchronized and we need to step
  34427. // forward one byte at a time until we find a pair of sync bytes that denote
  34428. // a packet
  34429. startIndex--;
  34430. endIndex--;
  34431. }
  34432. };
  34433. /**
  34434. * walks through the segment data from the start and end to get timing information
  34435. * for the first and last video pes packets as well as timing information for the first
  34436. * key frame.
  34437. */
  34438. var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
  34439. var startIndex = 0,
  34440. endIndex = MP2T_PACKET_LENGTH,
  34441. packet,
  34442. type,
  34443. pesType,
  34444. pusi,
  34445. parsed,
  34446. frame,
  34447. i,
  34448. pes;
  34449. var endLoop = false;
  34450. var currentFrame = {
  34451. data: [],
  34452. size: 0
  34453. }; // Start walking from start of segment to get first video packet
  34454. while (endIndex < bytes.byteLength) {
  34455. // Look for a pair of start and end sync bytes in the data..
  34456. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34457. // We found a packet
  34458. packet = bytes.subarray(startIndex, endIndex);
  34459. type = probe.ts.parseType(packet, pmt.pid);
  34460. switch (type) {
  34461. case 'pes':
  34462. pesType = probe.ts.parsePesType(packet, pmt.table);
  34463. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34464. if (pesType === 'video') {
  34465. if (pusi && !endLoop) {
  34466. parsed = probe.ts.parsePesTime(packet);
  34467. if (parsed) {
  34468. parsed.type = 'video';
  34469. result.video.push(parsed);
  34470. endLoop = true;
  34471. }
  34472. }
  34473. if (!result.firstKeyFrame) {
  34474. if (pusi) {
  34475. if (currentFrame.size !== 0) {
  34476. frame = new Uint8Array(currentFrame.size);
  34477. i = 0;
  34478. while (currentFrame.data.length) {
  34479. pes = currentFrame.data.shift();
  34480. frame.set(pes, i);
  34481. i += pes.byteLength;
  34482. }
  34483. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  34484. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  34485. // the keyframe seems to work fine with HLS playback
  34486. // and definitely preferable to a crash with TypeError...
  34487. if (firstKeyFrame) {
  34488. result.firstKeyFrame = firstKeyFrame;
  34489. result.firstKeyFrame.type = 'video';
  34490. } else {
  34491. // eslint-disable-next-line
  34492. 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.');
  34493. }
  34494. }
  34495. currentFrame.size = 0;
  34496. }
  34497. }
  34498. currentFrame.data.push(packet);
  34499. currentFrame.size += packet.byteLength;
  34500. }
  34501. }
  34502. break;
  34503. }
  34504. if (endLoop && result.firstKeyFrame) {
  34505. break;
  34506. }
  34507. startIndex += MP2T_PACKET_LENGTH;
  34508. endIndex += MP2T_PACKET_LENGTH;
  34509. continue;
  34510. } // If we get here, we have somehow become de-synchronized and we need to step
  34511. // forward one byte at a time until we find a pair of sync bytes that denote
  34512. // a packet
  34513. startIndex++;
  34514. endIndex++;
  34515. } // Start walking from end of segment to get last video packet
  34516. endIndex = bytes.byteLength;
  34517. startIndex = endIndex - MP2T_PACKET_LENGTH;
  34518. endLoop = false;
  34519. while (startIndex >= 0) {
  34520. // Look for a pair of start and end sync bytes in the data..
  34521. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  34522. // We found a packet
  34523. packet = bytes.subarray(startIndex, endIndex);
  34524. type = probe.ts.parseType(packet, pmt.pid);
  34525. switch (type) {
  34526. case 'pes':
  34527. pesType = probe.ts.parsePesType(packet, pmt.table);
  34528. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  34529. if (pesType === 'video' && pusi) {
  34530. parsed = probe.ts.parsePesTime(packet);
  34531. if (parsed) {
  34532. parsed.type = 'video';
  34533. result.video.push(parsed);
  34534. endLoop = true;
  34535. }
  34536. }
  34537. break;
  34538. }
  34539. if (endLoop) {
  34540. break;
  34541. }
  34542. startIndex -= MP2T_PACKET_LENGTH;
  34543. endIndex -= MP2T_PACKET_LENGTH;
  34544. continue;
  34545. } // If we get here, we have somehow become de-synchronized and we need to step
  34546. // forward one byte at a time until we find a pair of sync bytes that denote
  34547. // a packet
  34548. startIndex--;
  34549. endIndex--;
  34550. }
  34551. };
  34552. /**
  34553. * Adjusts the timestamp information for the segment to account for
  34554. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  34555. */
  34556. var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
  34557. if (segmentInfo.audio && segmentInfo.audio.length) {
  34558. var audioBaseTimestamp = baseTimestamp;
  34559. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  34560. audioBaseTimestamp = segmentInfo.audio[0].dts;
  34561. }
  34562. segmentInfo.audio.forEach(function (info) {
  34563. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  34564. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  34565. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34566. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34567. });
  34568. }
  34569. if (segmentInfo.video && segmentInfo.video.length) {
  34570. var videoBaseTimestamp = baseTimestamp;
  34571. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  34572. videoBaseTimestamp = segmentInfo.video[0].dts;
  34573. }
  34574. segmentInfo.video.forEach(function (info) {
  34575. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  34576. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  34577. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  34578. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  34579. });
  34580. if (segmentInfo.firstKeyFrame) {
  34581. var frame = segmentInfo.firstKeyFrame;
  34582. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  34583. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  34584. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  34585. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  34586. }
  34587. }
  34588. };
  34589. /**
  34590. * inspects the aac data stream for start and end time information
  34591. */
  34592. var inspectAac_ = function inspectAac_(bytes) {
  34593. var endLoop = false,
  34594. audioCount = 0,
  34595. sampleRate = null,
  34596. timestamp = null,
  34597. frameSize = 0,
  34598. byteIndex = 0,
  34599. packet;
  34600. while (bytes.length - byteIndex >= 3) {
  34601. var type = probe.aac.parseType(bytes, byteIndex);
  34602. switch (type) {
  34603. case 'timed-metadata':
  34604. // Exit early because we don't have enough to parse
  34605. // the ID3 tag header
  34606. if (bytes.length - byteIndex < 10) {
  34607. endLoop = true;
  34608. break;
  34609. }
  34610. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34611. // to emit a full packet
  34612. if (frameSize > bytes.length) {
  34613. endLoop = true;
  34614. break;
  34615. }
  34616. if (timestamp === null) {
  34617. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34618. timestamp = probe.aac.parseAacTimestamp(packet);
  34619. }
  34620. byteIndex += frameSize;
  34621. break;
  34622. case 'audio':
  34623. // Exit early because we don't have enough to parse
  34624. // the ADTS frame header
  34625. if (bytes.length - byteIndex < 7) {
  34626. endLoop = true;
  34627. break;
  34628. }
  34629. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  34630. // to emit a full packet
  34631. if (frameSize > bytes.length) {
  34632. endLoop = true;
  34633. break;
  34634. }
  34635. if (sampleRate === null) {
  34636. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  34637. sampleRate = probe.aac.parseSampleRate(packet);
  34638. }
  34639. audioCount++;
  34640. byteIndex += frameSize;
  34641. break;
  34642. default:
  34643. byteIndex++;
  34644. break;
  34645. }
  34646. if (endLoop) {
  34647. return null;
  34648. }
  34649. }
  34650. if (sampleRate === null || timestamp === null) {
  34651. return null;
  34652. }
  34653. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  34654. var result = {
  34655. audio: [{
  34656. type: 'audio',
  34657. dts: timestamp,
  34658. pts: timestamp
  34659. }, {
  34660. type: 'audio',
  34661. dts: timestamp + audioCount * 1024 * audioTimescale,
  34662. pts: timestamp + audioCount * 1024 * audioTimescale
  34663. }]
  34664. };
  34665. return result;
  34666. };
  34667. /**
  34668. * inspects the transport stream segment data for start and end time information
  34669. * of the audio and video tracks (when present) as well as the first key frame's
  34670. * start time.
  34671. */
  34672. var inspectTs_ = function inspectTs_(bytes) {
  34673. var pmt = {
  34674. pid: null,
  34675. table: null
  34676. };
  34677. var result = {};
  34678. parsePsi_(bytes, pmt);
  34679. for (var pid in pmt.table) {
  34680. if (pmt.table.hasOwnProperty(pid)) {
  34681. var type = pmt.table[pid];
  34682. switch (type) {
  34683. case streamTypes.H264_STREAM_TYPE:
  34684. result.video = [];
  34685. parseVideoPes_(bytes, pmt, result);
  34686. if (result.video.length === 0) {
  34687. delete result.video;
  34688. }
  34689. break;
  34690. case streamTypes.ADTS_STREAM_TYPE:
  34691. result.audio = [];
  34692. parseAudioPes_(bytes, pmt, result);
  34693. if (result.audio.length === 0) {
  34694. delete result.audio;
  34695. }
  34696. break;
  34697. }
  34698. }
  34699. }
  34700. return result;
  34701. };
  34702. /**
  34703. * Inspects segment byte data and returns an object with start and end timing information
  34704. *
  34705. * @param {Uint8Array} bytes The segment byte data
  34706. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  34707. * timestamps for rollover. This value must be in 90khz clock.
  34708. * @return {Object} Object containing start and end frame timing info of segment.
  34709. */
  34710. var inspect = function inspect(bytes, baseTimestamp) {
  34711. var isAacData = probe.aac.isLikelyAacData(bytes);
  34712. var result;
  34713. if (isAacData) {
  34714. result = inspectAac_(bytes);
  34715. } else {
  34716. result = inspectTs_(bytes);
  34717. }
  34718. if (!result || !result.audio && !result.video) {
  34719. return null;
  34720. }
  34721. adjustTimestamp_(result, baseTimestamp);
  34722. return result;
  34723. };
  34724. var tsInspector = {
  34725. inspect: inspect,
  34726. parseAudioPes_: parseAudioPes_
  34727. };
  34728. /* global self */
  34729. /**
  34730. * Re-emits transmuxer events by converting them into messages to the
  34731. * world outside the worker.
  34732. *
  34733. * @param {Object} transmuxer the transmuxer to wire events on
  34734. * @private
  34735. */
  34736. var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
  34737. transmuxer.on('data', function (segment) {
  34738. // transfer ownership of the underlying ArrayBuffer
  34739. // instead of doing a copy to save memory
  34740. // ArrayBuffers are transferable but generic TypedArrays are not
  34741. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  34742. var initArray = segment.initSegment;
  34743. segment.initSegment = {
  34744. data: initArray.buffer,
  34745. byteOffset: initArray.byteOffset,
  34746. byteLength: initArray.byteLength
  34747. };
  34748. var typedArray = segment.data;
  34749. segment.data = typedArray.buffer;
  34750. self.postMessage({
  34751. action: 'data',
  34752. segment: segment,
  34753. byteOffset: typedArray.byteOffset,
  34754. byteLength: typedArray.byteLength
  34755. }, [segment.data]);
  34756. });
  34757. transmuxer.on('done', function (data) {
  34758. self.postMessage({
  34759. action: 'done'
  34760. });
  34761. });
  34762. transmuxer.on('gopInfo', function (gopInfo) {
  34763. self.postMessage({
  34764. action: 'gopInfo',
  34765. gopInfo: gopInfo
  34766. });
  34767. });
  34768. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  34769. var videoSegmentTimingInfo = {
  34770. start: {
  34771. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  34772. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  34773. },
  34774. end: {
  34775. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  34776. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  34777. },
  34778. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  34779. };
  34780. if (timingInfo.prependedContentDuration) {
  34781. videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  34782. }
  34783. self.postMessage({
  34784. action: 'videoSegmentTimingInfo',
  34785. videoSegmentTimingInfo: videoSegmentTimingInfo
  34786. });
  34787. });
  34788. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  34789. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  34790. var audioSegmentTimingInfo = {
  34791. start: {
  34792. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  34793. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  34794. },
  34795. end: {
  34796. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  34797. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  34798. },
  34799. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  34800. };
  34801. if (timingInfo.prependedContentDuration) {
  34802. audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  34803. }
  34804. self.postMessage({
  34805. action: 'audioSegmentTimingInfo',
  34806. audioSegmentTimingInfo: audioSegmentTimingInfo
  34807. });
  34808. });
  34809. transmuxer.on('id3Frame', function (id3Frame) {
  34810. self.postMessage({
  34811. action: 'id3Frame',
  34812. id3Frame: id3Frame
  34813. });
  34814. });
  34815. transmuxer.on('caption', function (caption) {
  34816. self.postMessage({
  34817. action: 'caption',
  34818. caption: caption
  34819. });
  34820. });
  34821. transmuxer.on('trackinfo', function (trackInfo) {
  34822. self.postMessage({
  34823. action: 'trackinfo',
  34824. trackInfo: trackInfo
  34825. });
  34826. });
  34827. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  34828. // convert to video TS since we prioritize video time over audio
  34829. self.postMessage({
  34830. action: 'audioTimingInfo',
  34831. audioTimingInfo: {
  34832. start: clock.videoTsToSeconds(audioTimingInfo.start),
  34833. end: clock.videoTsToSeconds(audioTimingInfo.end)
  34834. }
  34835. });
  34836. });
  34837. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  34838. self.postMessage({
  34839. action: 'videoTimingInfo',
  34840. videoTimingInfo: {
  34841. start: clock.videoTsToSeconds(videoTimingInfo.start),
  34842. end: clock.videoTsToSeconds(videoTimingInfo.end)
  34843. }
  34844. });
  34845. });
  34846. transmuxer.on('log', function (log) {
  34847. self.postMessage({
  34848. action: 'log',
  34849. log: log
  34850. });
  34851. });
  34852. };
  34853. /**
  34854. * All incoming messages route through this hash. If no function exists
  34855. * to handle an incoming message, then we ignore the message.
  34856. *
  34857. * @class MessageHandlers
  34858. * @param {Object} options the options to initialize with
  34859. */
  34860. var MessageHandlers = /*#__PURE__*/function () {
  34861. function MessageHandlers(self, options) {
  34862. this.options = options || {};
  34863. this.self = self;
  34864. this.init();
  34865. }
  34866. /**
  34867. * initialize our web worker and wire all the events.
  34868. */
  34869. var _proto = MessageHandlers.prototype;
  34870. _proto.init = function init() {
  34871. if (this.transmuxer) {
  34872. this.transmuxer.dispose();
  34873. }
  34874. this.transmuxer = new transmuxer.Transmuxer(this.options);
  34875. wireTransmuxerEvents(this.self, this.transmuxer);
  34876. };
  34877. _proto.pushMp4Captions = function pushMp4Captions(data) {
  34878. if (!this.captionParser) {
  34879. this.captionParser = new captionParser();
  34880. this.captionParser.init();
  34881. }
  34882. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  34883. var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  34884. this.self.postMessage({
  34885. action: 'mp4Captions',
  34886. captions: parsed && parsed.captions || [],
  34887. logs: parsed && parsed.logs || [],
  34888. data: segment.buffer
  34889. }, [segment.buffer]);
  34890. };
  34891. _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
  34892. var timescales = _ref.timescales,
  34893. data = _ref.data;
  34894. var startTime = probe$2.startTime(timescales, data);
  34895. this.self.postMessage({
  34896. action: 'probeMp4StartTime',
  34897. startTime: startTime,
  34898. data: data
  34899. }, [data.buffer]);
  34900. };
  34901. _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
  34902. var data = _ref2.data;
  34903. var tracks = probe$2.tracks(data);
  34904. this.self.postMessage({
  34905. action: 'probeMp4Tracks',
  34906. tracks: tracks,
  34907. data: data
  34908. }, [data.buffer]);
  34909. }
  34910. /**
  34911. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  34912. * internal "media time," as well as whether it contains video and/or audio.
  34913. *
  34914. * @private
  34915. * @param {Uint8Array} bytes - segment bytes
  34916. * @param {number} baseStartTime
  34917. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  34918. * This value should be in seconds, as it's converted to a 90khz clock within the
  34919. * function body.
  34920. * @return {Object} The start time of the current segment in "media time" as well as
  34921. * whether it contains video and/or audio
  34922. */
  34923. ;
  34924. _proto.probeTs = function probeTs(_ref3) {
  34925. var data = _ref3.data,
  34926. baseStartTime = _ref3.baseStartTime;
  34927. var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
  34928. var timeInfo = tsInspector.inspect(data, tsStartTime);
  34929. var result = null;
  34930. if (timeInfo) {
  34931. result = {
  34932. // each type's time info comes back as an array of 2 times, start and end
  34933. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  34934. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  34935. };
  34936. if (result.hasVideo) {
  34937. result.videoStart = timeInfo.video[0].ptsTime;
  34938. }
  34939. if (result.hasAudio) {
  34940. result.audioStart = timeInfo.audio[0].ptsTime;
  34941. }
  34942. }
  34943. this.self.postMessage({
  34944. action: 'probeTs',
  34945. result: result,
  34946. data: data
  34947. }, [data.buffer]);
  34948. };
  34949. _proto.clearAllMp4Captions = function clearAllMp4Captions() {
  34950. if (this.captionParser) {
  34951. this.captionParser.clearAllCaptions();
  34952. }
  34953. };
  34954. _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
  34955. if (this.captionParser) {
  34956. this.captionParser.clearParsedCaptions();
  34957. }
  34958. }
  34959. /**
  34960. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  34961. * processing.
  34962. *
  34963. * @param {ArrayBuffer} data data to push into the muxer
  34964. */
  34965. ;
  34966. _proto.push = function push(data) {
  34967. // Cast array buffer to correct type for transmuxer
  34968. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  34969. this.transmuxer.push(segment);
  34970. }
  34971. /**
  34972. * Recreate the transmuxer so that the next segment added via `push`
  34973. * start with a fresh transmuxer.
  34974. */
  34975. ;
  34976. _proto.reset = function reset() {
  34977. this.transmuxer.reset();
  34978. }
  34979. /**
  34980. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  34981. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  34982. * set relative to the first based on the PTS values.
  34983. *
  34984. * @param {Object} data used to set the timestamp offset in the muxer
  34985. */
  34986. ;
  34987. _proto.setTimestampOffset = function setTimestampOffset(data) {
  34988. var timestampOffset = data.timestampOffset || 0;
  34989. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
  34990. };
  34991. _proto.setAudioAppendStart = function setAudioAppendStart(data) {
  34992. this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
  34993. };
  34994. _proto.setRemux = function setRemux(data) {
  34995. this.transmuxer.setRemux(data.remux);
  34996. }
  34997. /**
  34998. * Forces the pipeline to finish processing the last segment and emit it's
  34999. * results.
  35000. *
  35001. * @param {Object} data event data, not really used
  35002. */
  35003. ;
  35004. _proto.flush = function flush(data) {
  35005. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  35006. self.postMessage({
  35007. action: 'done',
  35008. type: 'transmuxed'
  35009. });
  35010. };
  35011. _proto.endTimeline = function endTimeline() {
  35012. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  35013. // timelines
  35014. self.postMessage({
  35015. action: 'endedtimeline',
  35016. type: 'transmuxed'
  35017. });
  35018. };
  35019. _proto.alignGopsWith = function alignGopsWith(data) {
  35020. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  35021. };
  35022. return MessageHandlers;
  35023. }();
  35024. /**
  35025. * Our web worker interface so that things can talk to mux.js
  35026. * that will be running in a web worker. the scope is passed to this by
  35027. * webworkify.
  35028. *
  35029. * @param {Object} self the scope for the web worker
  35030. */
  35031. self.onmessage = function (event) {
  35032. if (event.data.action === 'init' && event.data.options) {
  35033. this.messageHandlers = new MessageHandlers(self, event.data.options);
  35034. return;
  35035. }
  35036. if (!this.messageHandlers) {
  35037. this.messageHandlers = new MessageHandlers(self);
  35038. }
  35039. if (event.data && event.data.action && event.data.action !== 'init') {
  35040. if (this.messageHandlers[event.data.action]) {
  35041. this.messageHandlers[event.data.action](event.data);
  35042. }
  35043. }
  35044. };
  35045. }));
  35046. var TransmuxWorker = factory(workerCode$1);
  35047. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  35048. var handleData_ = function handleData_(event, transmuxedData, callback) {
  35049. var _event$data$segment = event.data.segment,
  35050. type = _event$data$segment.type,
  35051. initSegment = _event$data$segment.initSegment,
  35052. captions = _event$data$segment.captions,
  35053. captionStreams = _event$data$segment.captionStreams,
  35054. metadata = _event$data$segment.metadata,
  35055. videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
  35056. videoFramePtsTime = _event$data$segment.videoFramePtsTime;
  35057. transmuxedData.buffer.push({
  35058. captions: captions,
  35059. captionStreams: captionStreams,
  35060. metadata: metadata
  35061. });
  35062. var boxes = event.data.segment.boxes || {
  35063. data: event.data.segment.data
  35064. };
  35065. var result = {
  35066. type: type,
  35067. // cast ArrayBuffer to TypedArray
  35068. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  35069. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  35070. };
  35071. if (typeof videoFrameDtsTime !== 'undefined') {
  35072. result.videoFrameDtsTime = videoFrameDtsTime;
  35073. }
  35074. if (typeof videoFramePtsTime !== 'undefined') {
  35075. result.videoFramePtsTime = videoFramePtsTime;
  35076. }
  35077. callback(result);
  35078. };
  35079. var handleDone_ = function handleDone_(_ref) {
  35080. var transmuxedData = _ref.transmuxedData,
  35081. callback = _ref.callback; // Previously we only returned data on data events,
  35082. // not on done events. Clear out the buffer to keep that consistent.
  35083. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  35084. // have received
  35085. callback(transmuxedData);
  35086. };
  35087. var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
  35088. transmuxedData.gopInfo = event.data.gopInfo;
  35089. };
  35090. var processTransmux = function processTransmux(options) {
  35091. var transmuxer = options.transmuxer,
  35092. bytes = options.bytes,
  35093. audioAppendStart = options.audioAppendStart,
  35094. gopsToAlignWith = options.gopsToAlignWith,
  35095. remux = options.remux,
  35096. onData = options.onData,
  35097. onTrackInfo = options.onTrackInfo,
  35098. onAudioTimingInfo = options.onAudioTimingInfo,
  35099. onVideoTimingInfo = options.onVideoTimingInfo,
  35100. onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
  35101. onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
  35102. onId3 = options.onId3,
  35103. onCaptions = options.onCaptions,
  35104. onDone = options.onDone,
  35105. onEndedTimeline = options.onEndedTimeline,
  35106. onTransmuxerLog = options.onTransmuxerLog,
  35107. isEndOfTimeline = options.isEndOfTimeline;
  35108. var transmuxedData = {
  35109. buffer: []
  35110. };
  35111. var waitForEndedTimelineEvent = isEndOfTimeline;
  35112. var handleMessage = function handleMessage(event) {
  35113. if (transmuxer.currentTransmux !== options) {
  35114. // disposed
  35115. return;
  35116. }
  35117. if (event.data.action === 'data') {
  35118. handleData_(event, transmuxedData, onData);
  35119. }
  35120. if (event.data.action === 'trackinfo') {
  35121. onTrackInfo(event.data.trackInfo);
  35122. }
  35123. if (event.data.action === 'gopInfo') {
  35124. handleGopInfo_(event, transmuxedData);
  35125. }
  35126. if (event.data.action === 'audioTimingInfo') {
  35127. onAudioTimingInfo(event.data.audioTimingInfo);
  35128. }
  35129. if (event.data.action === 'videoTimingInfo') {
  35130. onVideoTimingInfo(event.data.videoTimingInfo);
  35131. }
  35132. if (event.data.action === 'videoSegmentTimingInfo') {
  35133. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  35134. }
  35135. if (event.data.action === 'audioSegmentTimingInfo') {
  35136. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  35137. }
  35138. if (event.data.action === 'id3Frame') {
  35139. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  35140. }
  35141. if (event.data.action === 'caption') {
  35142. onCaptions(event.data.caption);
  35143. }
  35144. if (event.data.action === 'endedtimeline') {
  35145. waitForEndedTimelineEvent = false;
  35146. onEndedTimeline();
  35147. }
  35148. if (event.data.action === 'log') {
  35149. onTransmuxerLog(event.data.log);
  35150. } // wait for the transmuxed event since we may have audio and video
  35151. if (event.data.type !== 'transmuxed') {
  35152. return;
  35153. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  35154. // of a timeline, that means there may still be data events before the segment
  35155. // processing can be considerred complete. In that case, the final event should be
  35156. // an "endedtimeline" event with the type "transmuxed."
  35157. if (waitForEndedTimelineEvent) {
  35158. return;
  35159. }
  35160. transmuxer.onmessage = null;
  35161. handleDone_({
  35162. transmuxedData: transmuxedData,
  35163. callback: onDone
  35164. });
  35165. /* eslint-disable no-use-before-define */
  35166. dequeue(transmuxer);
  35167. /* eslint-enable */
  35168. };
  35169. transmuxer.onmessage = handleMessage;
  35170. if (audioAppendStart) {
  35171. transmuxer.postMessage({
  35172. action: 'setAudioAppendStart',
  35173. appendStart: audioAppendStart
  35174. });
  35175. } // allow empty arrays to be passed to clear out GOPs
  35176. if (Array.isArray(gopsToAlignWith)) {
  35177. transmuxer.postMessage({
  35178. action: 'alignGopsWith',
  35179. gopsToAlignWith: gopsToAlignWith
  35180. });
  35181. }
  35182. if (typeof remux !== 'undefined') {
  35183. transmuxer.postMessage({
  35184. action: 'setRemux',
  35185. remux: remux
  35186. });
  35187. }
  35188. if (bytes.byteLength) {
  35189. var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  35190. var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  35191. transmuxer.postMessage({
  35192. action: 'push',
  35193. // Send the typed-array of data as an ArrayBuffer so that
  35194. // it can be sent as a "Transferable" and avoid the costly
  35195. // memory copy
  35196. data: buffer,
  35197. // To recreate the original typed-array, we need information
  35198. // about what portion of the ArrayBuffer it was a view into
  35199. byteOffset: byteOffset,
  35200. byteLength: bytes.byteLength
  35201. }, [buffer]);
  35202. }
  35203. if (isEndOfTimeline) {
  35204. transmuxer.postMessage({
  35205. action: 'endTimeline'
  35206. });
  35207. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  35208. // the end of the segment
  35209. transmuxer.postMessage({
  35210. action: 'flush'
  35211. });
  35212. };
  35213. var dequeue = function dequeue(transmuxer) {
  35214. transmuxer.currentTransmux = null;
  35215. if (transmuxer.transmuxQueue.length) {
  35216. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  35217. if (typeof transmuxer.currentTransmux === 'function') {
  35218. transmuxer.currentTransmux();
  35219. } else {
  35220. processTransmux(transmuxer.currentTransmux);
  35221. }
  35222. }
  35223. };
  35224. var processAction = function processAction(transmuxer, action) {
  35225. transmuxer.postMessage({
  35226. action: action
  35227. });
  35228. dequeue(transmuxer);
  35229. };
  35230. var enqueueAction = function enqueueAction(action, transmuxer) {
  35231. if (!transmuxer.currentTransmux) {
  35232. transmuxer.currentTransmux = action;
  35233. processAction(transmuxer, action);
  35234. return;
  35235. }
  35236. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  35237. };
  35238. var reset = function reset(transmuxer) {
  35239. enqueueAction('reset', transmuxer);
  35240. };
  35241. var endTimeline = function endTimeline(transmuxer) {
  35242. enqueueAction('endTimeline', transmuxer);
  35243. };
  35244. var transmux = function transmux(options) {
  35245. if (!options.transmuxer.currentTransmux) {
  35246. options.transmuxer.currentTransmux = options;
  35247. processTransmux(options);
  35248. return;
  35249. }
  35250. options.transmuxer.transmuxQueue.push(options);
  35251. };
  35252. var createTransmuxer = function createTransmuxer(options) {
  35253. var transmuxer = new TransmuxWorker();
  35254. transmuxer.currentTransmux = null;
  35255. transmuxer.transmuxQueue = [];
  35256. var term = transmuxer.terminate;
  35257. transmuxer.terminate = function () {
  35258. transmuxer.currentTransmux = null;
  35259. transmuxer.transmuxQueue.length = 0;
  35260. return term.call(transmuxer);
  35261. };
  35262. transmuxer.postMessage({
  35263. action: 'init',
  35264. options: options
  35265. });
  35266. return transmuxer;
  35267. };
  35268. var segmentTransmuxer = {
  35269. reset: reset,
  35270. endTimeline: endTimeline,
  35271. transmux: transmux,
  35272. createTransmuxer: createTransmuxer
  35273. };
  35274. var workerCallback = function workerCallback(options) {
  35275. var transmuxer = options.transmuxer;
  35276. var endAction = options.endAction || options.action;
  35277. var callback = options.callback;
  35278. var message = _extends__default['default']({}, options, {
  35279. endAction: null,
  35280. transmuxer: null,
  35281. callback: null
  35282. });
  35283. var listenForEndEvent = function listenForEndEvent(event) {
  35284. if (event.data.action !== endAction) {
  35285. return;
  35286. }
  35287. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  35288. if (event.data.data) {
  35289. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  35290. if (options.data) {
  35291. options.data = event.data.data;
  35292. }
  35293. }
  35294. callback(event.data);
  35295. };
  35296. transmuxer.addEventListener('message', listenForEndEvent);
  35297. if (options.data) {
  35298. var isArrayBuffer = options.data instanceof ArrayBuffer;
  35299. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  35300. message.byteLength = options.data.byteLength;
  35301. var transfers = [isArrayBuffer ? options.data : options.data.buffer];
  35302. transmuxer.postMessage(message, transfers);
  35303. } else {
  35304. transmuxer.postMessage(message);
  35305. }
  35306. };
  35307. var REQUEST_ERRORS = {
  35308. FAILURE: 2,
  35309. TIMEOUT: -101,
  35310. ABORTED: -102
  35311. };
  35312. /**
  35313. * Abort all requests
  35314. *
  35315. * @param {Object} activeXhrs - an object that tracks all XHR requests
  35316. */
  35317. var abortAll = function abortAll(activeXhrs) {
  35318. activeXhrs.forEach(function (xhr) {
  35319. xhr.abort();
  35320. });
  35321. };
  35322. /**
  35323. * Gather important bandwidth stats once a request has completed
  35324. *
  35325. * @param {Object} request - the XHR request from which to gather stats
  35326. */
  35327. var getRequestStats = function getRequestStats(request) {
  35328. return {
  35329. bandwidth: request.bandwidth,
  35330. bytesReceived: request.bytesReceived || 0,
  35331. roundTripTime: request.roundTripTime || 0
  35332. };
  35333. };
  35334. /**
  35335. * If possible gather bandwidth stats as a request is in
  35336. * progress
  35337. *
  35338. * @param {Event} progressEvent - an event object from an XHR's progress event
  35339. */
  35340. var getProgressStats = function getProgressStats(progressEvent) {
  35341. var request = progressEvent.target;
  35342. var roundTripTime = Date.now() - request.requestTime;
  35343. var stats = {
  35344. bandwidth: Infinity,
  35345. bytesReceived: 0,
  35346. roundTripTime: roundTripTime || 0
  35347. };
  35348. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  35349. // because we should only use bandwidth stats on progress to determine when
  35350. // abort a request early due to insufficient bandwidth
  35351. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  35352. return stats;
  35353. };
  35354. /**
  35355. * Handle all error conditions in one place and return an object
  35356. * with all the information
  35357. *
  35358. * @param {Error|null} error - if non-null signals an error occured with the XHR
  35359. * @param {Object} request - the XHR request that possibly generated the error
  35360. */
  35361. var handleErrors = function handleErrors(error, request) {
  35362. if (request.timedout) {
  35363. return {
  35364. status: request.status,
  35365. message: 'HLS request timed-out at URL: ' + request.uri,
  35366. code: REQUEST_ERRORS.TIMEOUT,
  35367. xhr: request
  35368. };
  35369. }
  35370. if (request.aborted) {
  35371. return {
  35372. status: request.status,
  35373. message: 'HLS request aborted at URL: ' + request.uri,
  35374. code: REQUEST_ERRORS.ABORTED,
  35375. xhr: request
  35376. };
  35377. }
  35378. if (error) {
  35379. return {
  35380. status: request.status,
  35381. message: 'HLS request errored at URL: ' + request.uri,
  35382. code: REQUEST_ERRORS.FAILURE,
  35383. xhr: request
  35384. };
  35385. }
  35386. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  35387. return {
  35388. status: request.status,
  35389. message: 'Empty HLS response at URL: ' + request.uri,
  35390. code: REQUEST_ERRORS.FAILURE,
  35391. xhr: request
  35392. };
  35393. }
  35394. return null;
  35395. };
  35396. /**
  35397. * Handle responses for key data and convert the key data to the correct format
  35398. * for the decryption step later
  35399. *
  35400. * @param {Object} segment - a simplified copy of the segmentInfo object
  35401. * from SegmentLoader
  35402. * @param {Array} objects - objects to add the key bytes to.
  35403. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35404. * this request
  35405. */
  35406. var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
  35407. return function (error, request) {
  35408. var response = request.response;
  35409. var errorObj = handleErrors(error, request);
  35410. if (errorObj) {
  35411. return finishProcessingFn(errorObj, segment);
  35412. }
  35413. if (response.byteLength !== 16) {
  35414. return finishProcessingFn({
  35415. status: request.status,
  35416. message: 'Invalid HLS key at URL: ' + request.uri,
  35417. code: REQUEST_ERRORS.FAILURE,
  35418. xhr: request
  35419. }, segment);
  35420. }
  35421. var view = new DataView(response);
  35422. var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  35423. for (var i = 0; i < objects.length; i++) {
  35424. objects[i].bytes = bytes;
  35425. }
  35426. return finishProcessingFn(null, segment);
  35427. };
  35428. };
  35429. var parseInitSegment = function parseInitSegment(segment, _callback) {
  35430. var type = containers.detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  35431. // only know how to parse mp4 init segments at the moment
  35432. if (type !== 'mp4') {
  35433. var uri = segment.map.resolvedUri || segment.map.uri;
  35434. return _callback({
  35435. internal: true,
  35436. message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
  35437. code: REQUEST_ERRORS.FAILURE
  35438. });
  35439. }
  35440. workerCallback({
  35441. action: 'probeMp4Tracks',
  35442. data: segment.map.bytes,
  35443. transmuxer: segment.transmuxer,
  35444. callback: function callback(_ref) {
  35445. var tracks = _ref.tracks,
  35446. data = _ref.data; // transfer bytes back to us
  35447. segment.map.bytes = data;
  35448. tracks.forEach(function (track) {
  35449. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  35450. if (segment.map.tracks[track.type]) {
  35451. return;
  35452. }
  35453. segment.map.tracks[track.type] = track;
  35454. if (typeof track.id === 'number' && track.timescale) {
  35455. segment.map.timescales = segment.map.timescales || {};
  35456. segment.map.timescales[track.id] = track.timescale;
  35457. }
  35458. });
  35459. return _callback(null);
  35460. }
  35461. });
  35462. };
  35463. /**
  35464. * Handle init-segment responses
  35465. *
  35466. * @param {Object} segment - a simplified copy of the segmentInfo object
  35467. * from SegmentLoader
  35468. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35469. * this request
  35470. */
  35471. var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
  35472. var segment = _ref2.segment,
  35473. finishProcessingFn = _ref2.finishProcessingFn;
  35474. return function (error, request) {
  35475. var errorObj = handleErrors(error, request);
  35476. if (errorObj) {
  35477. return finishProcessingFn(errorObj, segment);
  35478. }
  35479. var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  35480. // until the key request is done to decrypt.
  35481. if (segment.map.key) {
  35482. segment.map.encryptedBytes = bytes;
  35483. return finishProcessingFn(null, segment);
  35484. }
  35485. segment.map.bytes = bytes;
  35486. parseInitSegment(segment, function (parseError) {
  35487. if (parseError) {
  35488. parseError.xhr = request;
  35489. parseError.status = request.status;
  35490. return finishProcessingFn(parseError, segment);
  35491. }
  35492. finishProcessingFn(null, segment);
  35493. });
  35494. };
  35495. };
  35496. /**
  35497. * Response handler for segment-requests being sure to set the correct
  35498. * property depending on whether the segment is encryped or not
  35499. * Also records and keeps track of stats that are used for ABR purposes
  35500. *
  35501. * @param {Object} segment - a simplified copy of the segmentInfo object
  35502. * from SegmentLoader
  35503. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  35504. * this request
  35505. */
  35506. var handleSegmentResponse = function handleSegmentResponse(_ref3) {
  35507. var segment = _ref3.segment,
  35508. finishProcessingFn = _ref3.finishProcessingFn,
  35509. responseType = _ref3.responseType;
  35510. return function (error, request) {
  35511. var errorObj = handleErrors(error, request);
  35512. if (errorObj) {
  35513. return finishProcessingFn(errorObj, segment);
  35514. }
  35515. var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  35516. // thrown for two primary cases:
  35517. // 1. the mime type override stops working, or is not implemented for a specific
  35518. // browser
  35519. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  35520. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  35521. segment.stats = getRequestStats(request);
  35522. if (segment.key) {
  35523. segment.encryptedBytes = new Uint8Array(newBytes);
  35524. } else {
  35525. segment.bytes = new Uint8Array(newBytes);
  35526. }
  35527. return finishProcessingFn(null, segment);
  35528. };
  35529. };
  35530. var transmuxAndNotify = function transmuxAndNotify(_ref4) {
  35531. var segment = _ref4.segment,
  35532. bytes = _ref4.bytes,
  35533. trackInfoFn = _ref4.trackInfoFn,
  35534. timingInfoFn = _ref4.timingInfoFn,
  35535. videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
  35536. audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
  35537. id3Fn = _ref4.id3Fn,
  35538. captionsFn = _ref4.captionsFn,
  35539. isEndOfTimeline = _ref4.isEndOfTimeline,
  35540. endedTimelineFn = _ref4.endedTimelineFn,
  35541. dataFn = _ref4.dataFn,
  35542. doneFn = _ref4.doneFn,
  35543. onTransmuxerLog = _ref4.onTransmuxerLog;
  35544. var fmp4Tracks = segment.map && segment.map.tracks || {};
  35545. var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  35546. // One reason for this is that in the case of full segments, we want to trust start
  35547. // times from the probe, rather than the transmuxer.
  35548. var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  35549. var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  35550. var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  35551. var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  35552. var finish = function finish() {
  35553. return transmux({
  35554. bytes: bytes,
  35555. transmuxer: segment.transmuxer,
  35556. audioAppendStart: segment.audioAppendStart,
  35557. gopsToAlignWith: segment.gopsToAlignWith,
  35558. remux: isMuxed,
  35559. onData: function onData(result) {
  35560. result.type = result.type === 'combined' ? 'video' : result.type;
  35561. dataFn(segment, result);
  35562. },
  35563. onTrackInfo: function onTrackInfo(trackInfo) {
  35564. if (trackInfoFn) {
  35565. if (isMuxed) {
  35566. trackInfo.isMuxed = true;
  35567. }
  35568. trackInfoFn(segment, trackInfo);
  35569. }
  35570. },
  35571. onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
  35572. // we only want the first start value we encounter
  35573. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  35574. audioStartFn(audioTimingInfo.start);
  35575. audioStartFn = null;
  35576. } // we want to continually update the end time
  35577. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  35578. audioEndFn(audioTimingInfo.end);
  35579. }
  35580. },
  35581. onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
  35582. // we only want the first start value we encounter
  35583. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  35584. videoStartFn(videoTimingInfo.start);
  35585. videoStartFn = null;
  35586. } // we want to continually update the end time
  35587. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  35588. videoEndFn(videoTimingInfo.end);
  35589. }
  35590. },
  35591. onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
  35592. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  35593. },
  35594. onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
  35595. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  35596. },
  35597. onId3: function onId3(id3Frames, dispatchType) {
  35598. id3Fn(segment, id3Frames, dispatchType);
  35599. },
  35600. onCaptions: function onCaptions(captions) {
  35601. captionsFn(segment, [captions]);
  35602. },
  35603. isEndOfTimeline: isEndOfTimeline,
  35604. onEndedTimeline: function onEndedTimeline() {
  35605. endedTimelineFn();
  35606. },
  35607. onTransmuxerLog: onTransmuxerLog,
  35608. onDone: function onDone(result) {
  35609. if (!doneFn) {
  35610. return;
  35611. }
  35612. result.type = result.type === 'combined' ? 'video' : result.type;
  35613. doneFn(null, segment, result);
  35614. }
  35615. });
  35616. }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  35617. // Meaning cached frame data may corrupt our notion of where this segment
  35618. // really starts. To get around this, probe for the info needed.
  35619. workerCallback({
  35620. action: 'probeTs',
  35621. transmuxer: segment.transmuxer,
  35622. data: bytes,
  35623. baseStartTime: segment.baseStartTime,
  35624. callback: function callback(data) {
  35625. segment.bytes = bytes = data.data;
  35626. var probeResult = data.result;
  35627. if (probeResult) {
  35628. trackInfoFn(segment, {
  35629. hasAudio: probeResult.hasAudio,
  35630. hasVideo: probeResult.hasVideo,
  35631. isMuxed: isMuxed
  35632. });
  35633. trackInfoFn = null;
  35634. if (probeResult.hasAudio && !isMuxed) {
  35635. audioStartFn(probeResult.audioStart);
  35636. }
  35637. if (probeResult.hasVideo) {
  35638. videoStartFn(probeResult.videoStart);
  35639. }
  35640. audioStartFn = null;
  35641. videoStartFn = null;
  35642. }
  35643. finish();
  35644. }
  35645. });
  35646. };
  35647. var handleSegmentBytes = function handleSegmentBytes(_ref5) {
  35648. var segment = _ref5.segment,
  35649. bytes = _ref5.bytes,
  35650. trackInfoFn = _ref5.trackInfoFn,
  35651. timingInfoFn = _ref5.timingInfoFn,
  35652. videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
  35653. audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
  35654. id3Fn = _ref5.id3Fn,
  35655. captionsFn = _ref5.captionsFn,
  35656. isEndOfTimeline = _ref5.isEndOfTimeline,
  35657. endedTimelineFn = _ref5.endedTimelineFn,
  35658. dataFn = _ref5.dataFn,
  35659. doneFn = _ref5.doneFn,
  35660. onTransmuxerLog = _ref5.onTransmuxerLog;
  35661. var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  35662. // We should have a handler that fetches the number of bytes required
  35663. // to check if something is fmp4. This will allow us to save bandwidth
  35664. // because we can only blacklist a playlist and abort requests
  35665. // by codec after trackinfo triggers.
  35666. if (containers.isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  35667. segment.isFmp4 = true;
  35668. var tracks = segment.map.tracks;
  35669. var trackInfo = {
  35670. isFmp4: true,
  35671. hasVideo: !!tracks.video,
  35672. hasAudio: !!tracks.audio
  35673. }; // if we have a audio track, with a codec that is not set to
  35674. // encrypted audio
  35675. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  35676. trackInfo.audioCodec = tracks.audio.codec;
  35677. } // if we have a video track, with a codec that is not set to
  35678. // encrypted video
  35679. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  35680. trackInfo.videoCodec = tracks.video.codec;
  35681. }
  35682. if (tracks.video && tracks.audio) {
  35683. trackInfo.isMuxed = true;
  35684. } // since we don't support appending fmp4 data on progress, we know we have the full
  35685. // segment here
  35686. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  35687. // time. The end time can be roughly calculated by the receiver using the duration.
  35688. //
  35689. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  35690. // that is the true start of the segment (where the playback engine should begin
  35691. // decoding).
  35692. var finishLoading = function finishLoading(captions) {
  35693. // if the track still has audio at this point it is only possible
  35694. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  35695. // above.
  35696. // we make sure to use segment.bytes here as that
  35697. dataFn(segment, {
  35698. data: bytesAsUint8Array,
  35699. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  35700. });
  35701. if (captions && captions.length) {
  35702. captionsFn(segment, captions);
  35703. }
  35704. doneFn(null, segment, {});
  35705. };
  35706. workerCallback({
  35707. action: 'probeMp4StartTime',
  35708. timescales: segment.map.timescales,
  35709. data: bytesAsUint8Array,
  35710. transmuxer: segment.transmuxer,
  35711. callback: function callback(_ref6) {
  35712. var data = _ref6.data,
  35713. startTime = _ref6.startTime; // transfer bytes back to us
  35714. bytes = data.buffer;
  35715. segment.bytes = bytesAsUint8Array = data;
  35716. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  35717. timingInfoFn(segment, 'audio', 'start', startTime);
  35718. }
  35719. if (trackInfo.hasVideo) {
  35720. timingInfoFn(segment, 'video', 'start', startTime);
  35721. } // Run through the CaptionParser in case there are captions.
  35722. // Initialize CaptionParser if it hasn't been yet
  35723. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  35724. finishLoading();
  35725. return;
  35726. }
  35727. workerCallback({
  35728. action: 'pushMp4Captions',
  35729. endAction: 'mp4Captions',
  35730. transmuxer: segment.transmuxer,
  35731. data: bytesAsUint8Array,
  35732. timescales: segment.map.timescales,
  35733. trackIds: [tracks.video.id],
  35734. callback: function callback(message) {
  35735. // transfer bytes back to us
  35736. bytes = message.data.buffer;
  35737. segment.bytes = bytesAsUint8Array = message.data;
  35738. message.logs.forEach(function (log) {
  35739. onTransmuxerLog(videojs.mergeOptions(log, {
  35740. stream: 'mp4CaptionParser'
  35741. }));
  35742. });
  35743. finishLoading(message.captions);
  35744. }
  35745. });
  35746. }
  35747. });
  35748. return;
  35749. } // VTT or other segments that don't need processing
  35750. if (!segment.transmuxer) {
  35751. doneFn(null, segment, {});
  35752. return;
  35753. }
  35754. if (typeof segment.container === 'undefined') {
  35755. segment.container = containers.detectContainerForBytes(bytesAsUint8Array);
  35756. }
  35757. if (segment.container !== 'ts' && segment.container !== 'aac') {
  35758. trackInfoFn(segment, {
  35759. hasAudio: false,
  35760. hasVideo: false
  35761. });
  35762. doneFn(null, segment, {});
  35763. return;
  35764. } // ts or aac
  35765. transmuxAndNotify({
  35766. segment: segment,
  35767. bytes: bytes,
  35768. trackInfoFn: trackInfoFn,
  35769. timingInfoFn: timingInfoFn,
  35770. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  35771. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  35772. id3Fn: id3Fn,
  35773. captionsFn: captionsFn,
  35774. isEndOfTimeline: isEndOfTimeline,
  35775. endedTimelineFn: endedTimelineFn,
  35776. dataFn: dataFn,
  35777. doneFn: doneFn,
  35778. onTransmuxerLog: onTransmuxerLog
  35779. });
  35780. };
  35781. var decrypt = function decrypt(_ref7, callback) {
  35782. var id = _ref7.id,
  35783. key = _ref7.key,
  35784. encryptedBytes = _ref7.encryptedBytes,
  35785. decryptionWorker = _ref7.decryptionWorker;
  35786. var decryptionHandler = function decryptionHandler(event) {
  35787. if (event.data.source === id) {
  35788. decryptionWorker.removeEventListener('message', decryptionHandler);
  35789. var decrypted = event.data.decrypted;
  35790. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  35791. }
  35792. };
  35793. decryptionWorker.addEventListener('message', decryptionHandler);
  35794. var keyBytes;
  35795. if (key.bytes.slice) {
  35796. keyBytes = key.bytes.slice();
  35797. } else {
  35798. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  35799. } // incrementally decrypt the bytes
  35800. decryptionWorker.postMessage(createTransferableMessage({
  35801. source: id,
  35802. encrypted: encryptedBytes,
  35803. key: keyBytes,
  35804. iv: key.iv
  35805. }), [encryptedBytes.buffer, keyBytes.buffer]);
  35806. };
  35807. /**
  35808. * Decrypt the segment via the decryption web worker
  35809. *
  35810. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  35811. * routines
  35812. * @param {Object} segment - a simplified copy of the segmentInfo object
  35813. * from SegmentLoader
  35814. * @param {Function} trackInfoFn - a callback that receives track info
  35815. * @param {Function} timingInfoFn - a callback that receives timing info
  35816. * @param {Function} videoSegmentTimingInfoFn
  35817. * a callback that receives video timing info based on media times and
  35818. * any adjustments made by the transmuxer
  35819. * @param {Function} audioSegmentTimingInfoFn
  35820. * a callback that receives audio timing info based on media times and
  35821. * any adjustments made by the transmuxer
  35822. * @param {boolean} isEndOfTimeline
  35823. * true if this segment represents the last segment in a timeline
  35824. * @param {Function} endedTimelineFn
  35825. * a callback made when a timeline is ended, will only be called if
  35826. * isEndOfTimeline is true
  35827. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  35828. * and ready to use
  35829. * @param {Function} doneFn - a callback that is executed after decryption has completed
  35830. */
  35831. var decryptSegment = function decryptSegment(_ref8) {
  35832. var decryptionWorker = _ref8.decryptionWorker,
  35833. segment = _ref8.segment,
  35834. trackInfoFn = _ref8.trackInfoFn,
  35835. timingInfoFn = _ref8.timingInfoFn,
  35836. videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
  35837. audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
  35838. id3Fn = _ref8.id3Fn,
  35839. captionsFn = _ref8.captionsFn,
  35840. isEndOfTimeline = _ref8.isEndOfTimeline,
  35841. endedTimelineFn = _ref8.endedTimelineFn,
  35842. dataFn = _ref8.dataFn,
  35843. doneFn = _ref8.doneFn,
  35844. onTransmuxerLog = _ref8.onTransmuxerLog;
  35845. decrypt({
  35846. id: segment.requestId,
  35847. key: segment.key,
  35848. encryptedBytes: segment.encryptedBytes,
  35849. decryptionWorker: decryptionWorker
  35850. }, function (decryptedBytes) {
  35851. segment.bytes = decryptedBytes;
  35852. handleSegmentBytes({
  35853. segment: segment,
  35854. bytes: segment.bytes,
  35855. trackInfoFn: trackInfoFn,
  35856. timingInfoFn: timingInfoFn,
  35857. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  35858. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  35859. id3Fn: id3Fn,
  35860. captionsFn: captionsFn,
  35861. isEndOfTimeline: isEndOfTimeline,
  35862. endedTimelineFn: endedTimelineFn,
  35863. dataFn: dataFn,
  35864. doneFn: doneFn,
  35865. onTransmuxerLog: onTransmuxerLog
  35866. });
  35867. });
  35868. };
  35869. /**
  35870. * This function waits for all XHRs to finish (with either success or failure)
  35871. * before continueing processing via it's callback. The function gathers errors
  35872. * from each request into a single errors array so that the error status for
  35873. * each request can be examined later.
  35874. *
  35875. * @param {Object} activeXhrs - an object that tracks all XHR requests
  35876. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  35877. * routines
  35878. * @param {Function} trackInfoFn - a callback that receives track info
  35879. * @param {Function} timingInfoFn - a callback that receives timing info
  35880. * @param {Function} videoSegmentTimingInfoFn
  35881. * a callback that receives video timing info based on media times and
  35882. * any adjustments made by the transmuxer
  35883. * @param {Function} audioSegmentTimingInfoFn
  35884. * a callback that receives audio timing info based on media times and
  35885. * any adjustments made by the transmuxer
  35886. * @param {Function} id3Fn - a callback that receives ID3 metadata
  35887. * @param {Function} captionsFn - a callback that receives captions
  35888. * @param {boolean} isEndOfTimeline
  35889. * true if this segment represents the last segment in a timeline
  35890. * @param {Function} endedTimelineFn
  35891. * a callback made when a timeline is ended, will only be called if
  35892. * isEndOfTimeline is true
  35893. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  35894. * and ready to use
  35895. * @param {Function} doneFn - a callback that is executed after all resources have been
  35896. * downloaded and any decryption completed
  35897. */
  35898. var waitForCompletion = function waitForCompletion(_ref9) {
  35899. var activeXhrs = _ref9.activeXhrs,
  35900. decryptionWorker = _ref9.decryptionWorker,
  35901. trackInfoFn = _ref9.trackInfoFn,
  35902. timingInfoFn = _ref9.timingInfoFn,
  35903. videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
  35904. audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
  35905. id3Fn = _ref9.id3Fn,
  35906. captionsFn = _ref9.captionsFn,
  35907. isEndOfTimeline = _ref9.isEndOfTimeline,
  35908. endedTimelineFn = _ref9.endedTimelineFn,
  35909. dataFn = _ref9.dataFn,
  35910. doneFn = _ref9.doneFn,
  35911. onTransmuxerLog = _ref9.onTransmuxerLog;
  35912. var count = 0;
  35913. var didError = false;
  35914. return function (error, segment) {
  35915. if (didError) {
  35916. return;
  35917. }
  35918. if (error) {
  35919. didError = true; // If there are errors, we have to abort any outstanding requests
  35920. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  35921. // handle the aborted events from those requests, there are some cases where we may
  35922. // never get an aborted event. For instance, if the network connection is lost and
  35923. // there were two requests, the first may have triggered an error immediately, while
  35924. // the second request remains unsent. In that case, the aborted algorithm will not
  35925. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  35926. //
  35927. // We also can't rely on the ready state of the XHR, since the request that
  35928. // triggered the connection error may also show as a ready state of 0 (unsent).
  35929. // Therefore, we have to finish this group of requests immediately after the first
  35930. // seen error.
  35931. return doneFn(error, segment);
  35932. }
  35933. count += 1;
  35934. if (count === activeXhrs.length) {
  35935. var segmentFinish = function segmentFinish() {
  35936. if (segment.encryptedBytes) {
  35937. return decryptSegment({
  35938. decryptionWorker: decryptionWorker,
  35939. segment: segment,
  35940. trackInfoFn: trackInfoFn,
  35941. timingInfoFn: timingInfoFn,
  35942. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  35943. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  35944. id3Fn: id3Fn,
  35945. captionsFn: captionsFn,
  35946. isEndOfTimeline: isEndOfTimeline,
  35947. endedTimelineFn: endedTimelineFn,
  35948. dataFn: dataFn,
  35949. doneFn: doneFn,
  35950. onTransmuxerLog: onTransmuxerLog
  35951. });
  35952. } // Otherwise, everything is ready just continue
  35953. handleSegmentBytes({
  35954. segment: segment,
  35955. bytes: segment.bytes,
  35956. trackInfoFn: trackInfoFn,
  35957. timingInfoFn: timingInfoFn,
  35958. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  35959. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  35960. id3Fn: id3Fn,
  35961. captionsFn: captionsFn,
  35962. isEndOfTimeline: isEndOfTimeline,
  35963. endedTimelineFn: endedTimelineFn,
  35964. dataFn: dataFn,
  35965. doneFn: doneFn,
  35966. onTransmuxerLog: onTransmuxerLog
  35967. });
  35968. }; // Keep track of when *all* of the requests have completed
  35969. segment.endOfAllRequests = Date.now();
  35970. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  35971. return decrypt({
  35972. decryptionWorker: decryptionWorker,
  35973. // add -init to the "id" to differentiate between segment
  35974. // and init segment decryption, just in case they happen
  35975. // at the same time at some point in the future.
  35976. id: segment.requestId + '-init',
  35977. encryptedBytes: segment.map.encryptedBytes,
  35978. key: segment.map.key
  35979. }, function (decryptedBytes) {
  35980. segment.map.bytes = decryptedBytes;
  35981. parseInitSegment(segment, function (parseError) {
  35982. if (parseError) {
  35983. abortAll(activeXhrs);
  35984. return doneFn(parseError, segment);
  35985. }
  35986. segmentFinish();
  35987. });
  35988. });
  35989. }
  35990. segmentFinish();
  35991. }
  35992. };
  35993. };
  35994. /**
  35995. * Calls the abort callback if any request within the batch was aborted. Will only call
  35996. * the callback once per batch of requests, even if multiple were aborted.
  35997. *
  35998. * @param {Object} loadendState - state to check to see if the abort function was called
  35999. * @param {Function} abortFn - callback to call for abort
  36000. */
  36001. var handleLoadEnd = function handleLoadEnd(_ref10) {
  36002. var loadendState = _ref10.loadendState,
  36003. abortFn = _ref10.abortFn;
  36004. return function (event) {
  36005. var request = event.target;
  36006. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  36007. abortFn();
  36008. loadendState.calledAbortFn = true;
  36009. }
  36010. };
  36011. };
  36012. /**
  36013. * Simple progress event callback handler that gathers some stats before
  36014. * executing a provided callback with the `segment` object
  36015. *
  36016. * @param {Object} segment - a simplified copy of the segmentInfo object
  36017. * from SegmentLoader
  36018. * @param {Function} progressFn - a callback that is executed each time a progress event
  36019. * is received
  36020. * @param {Function} trackInfoFn - a callback that receives track info
  36021. * @param {Function} timingInfoFn - a callback that receives timing info
  36022. * @param {Function} videoSegmentTimingInfoFn
  36023. * a callback that receives video timing info based on media times and
  36024. * any adjustments made by the transmuxer
  36025. * @param {Function} audioSegmentTimingInfoFn
  36026. * a callback that receives audio timing info based on media times and
  36027. * any adjustments made by the transmuxer
  36028. * @param {boolean} isEndOfTimeline
  36029. * true if this segment represents the last segment in a timeline
  36030. * @param {Function} endedTimelineFn
  36031. * a callback made when a timeline is ended, will only be called if
  36032. * isEndOfTimeline is true
  36033. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  36034. * and ready to use
  36035. * @param {Event} event - the progress event object from XMLHttpRequest
  36036. */
  36037. var handleProgress = function handleProgress(_ref11) {
  36038. var segment = _ref11.segment,
  36039. progressFn = _ref11.progressFn;
  36040. _ref11.trackInfoFn;
  36041. _ref11.timingInfoFn;
  36042. _ref11.videoSegmentTimingInfoFn;
  36043. _ref11.audioSegmentTimingInfoFn;
  36044. _ref11.id3Fn;
  36045. _ref11.captionsFn;
  36046. _ref11.isEndOfTimeline;
  36047. _ref11.endedTimelineFn;
  36048. _ref11.dataFn;
  36049. return function (event) {
  36050. var request = event.target;
  36051. if (request.aborted) {
  36052. return;
  36053. }
  36054. segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  36055. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  36056. segment.stats.firstBytesReceivedAt = Date.now();
  36057. }
  36058. return progressFn(event, segment);
  36059. };
  36060. };
  36061. /**
  36062. * Load all resources and does any processing necessary for a media-segment
  36063. *
  36064. * Features:
  36065. * decrypts the media-segment if it has a key uri and an iv
  36066. * aborts *all* requests if *any* one request fails
  36067. *
  36068. * The segment object, at minimum, has the following format:
  36069. * {
  36070. * resolvedUri: String,
  36071. * [transmuxer]: Object,
  36072. * [byterange]: {
  36073. * offset: Number,
  36074. * length: Number
  36075. * },
  36076. * [key]: {
  36077. * resolvedUri: String
  36078. * [byterange]: {
  36079. * offset: Number,
  36080. * length: Number
  36081. * },
  36082. * iv: {
  36083. * bytes: Uint32Array
  36084. * }
  36085. * },
  36086. * [map]: {
  36087. * resolvedUri: String,
  36088. * [byterange]: {
  36089. * offset: Number,
  36090. * length: Number
  36091. * },
  36092. * [bytes]: Uint8Array
  36093. * }
  36094. * }
  36095. * ...where [name] denotes optional properties
  36096. *
  36097. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  36098. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  36099. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  36100. * decryption routines
  36101. * @param {Object} segment - a simplified copy of the segmentInfo object
  36102. * from SegmentLoader
  36103. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  36104. * aborted
  36105. * @param {Function} progressFn - a callback that receives progress events from the main
  36106. * segment's xhr request
  36107. * @param {Function} trackInfoFn - a callback that receives track info
  36108. * @param {Function} timingInfoFn - a callback that receives timing info
  36109. * @param {Function} videoSegmentTimingInfoFn
  36110. * a callback that receives video timing info based on media times and
  36111. * any adjustments made by the transmuxer
  36112. * @param {Function} audioSegmentTimingInfoFn
  36113. * a callback that receives audio timing info based on media times and
  36114. * any adjustments made by the transmuxer
  36115. * @param {Function} id3Fn - a callback that receives ID3 metadata
  36116. * @param {Function} captionsFn - a callback that receives captions
  36117. * @param {boolean} isEndOfTimeline
  36118. * true if this segment represents the last segment in a timeline
  36119. * @param {Function} endedTimelineFn
  36120. * a callback made when a timeline is ended, will only be called if
  36121. * isEndOfTimeline is true
  36122. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  36123. * request, transmuxed if needed
  36124. * @param {Function} doneFn - a callback that is executed only once all requests have
  36125. * succeeded or failed
  36126. * @return {Function} a function that, when invoked, immediately aborts all
  36127. * outstanding requests
  36128. */
  36129. var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
  36130. var xhr = _ref12.xhr,
  36131. xhrOptions = _ref12.xhrOptions,
  36132. decryptionWorker = _ref12.decryptionWorker,
  36133. segment = _ref12.segment,
  36134. abortFn = _ref12.abortFn,
  36135. progressFn = _ref12.progressFn,
  36136. trackInfoFn = _ref12.trackInfoFn,
  36137. timingInfoFn = _ref12.timingInfoFn,
  36138. videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
  36139. audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
  36140. id3Fn = _ref12.id3Fn,
  36141. captionsFn = _ref12.captionsFn,
  36142. isEndOfTimeline = _ref12.isEndOfTimeline,
  36143. endedTimelineFn = _ref12.endedTimelineFn,
  36144. dataFn = _ref12.dataFn,
  36145. doneFn = _ref12.doneFn,
  36146. onTransmuxerLog = _ref12.onTransmuxerLog;
  36147. var activeXhrs = [];
  36148. var finishProcessingFn = waitForCompletion({
  36149. activeXhrs: activeXhrs,
  36150. decryptionWorker: decryptionWorker,
  36151. trackInfoFn: trackInfoFn,
  36152. timingInfoFn: timingInfoFn,
  36153. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  36154. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  36155. id3Fn: id3Fn,
  36156. captionsFn: captionsFn,
  36157. isEndOfTimeline: isEndOfTimeline,
  36158. endedTimelineFn: endedTimelineFn,
  36159. dataFn: dataFn,
  36160. doneFn: doneFn,
  36161. onTransmuxerLog: onTransmuxerLog
  36162. }); // optionally, request the decryption key
  36163. if (segment.key && !segment.key.bytes) {
  36164. var objects = [segment.key];
  36165. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  36166. objects.push(segment.map.key);
  36167. }
  36168. var keyRequestOptions = videojs.mergeOptions(xhrOptions, {
  36169. uri: segment.key.resolvedUri,
  36170. responseType: 'arraybuffer'
  36171. });
  36172. var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  36173. var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  36174. activeXhrs.push(keyXhr);
  36175. } // optionally, request the associated media init segment
  36176. if (segment.map && !segment.map.bytes) {
  36177. var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  36178. if (differentMapKey) {
  36179. var mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
  36180. uri: segment.map.key.resolvedUri,
  36181. responseType: 'arraybuffer'
  36182. });
  36183. var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  36184. var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  36185. activeXhrs.push(mapKeyXhr);
  36186. }
  36187. var initSegmentOptions = videojs.mergeOptions(xhrOptions, {
  36188. uri: segment.map.resolvedUri,
  36189. responseType: 'arraybuffer',
  36190. headers: segmentXhrHeaders(segment.map)
  36191. });
  36192. var initSegmentRequestCallback = handleInitSegmentResponse({
  36193. segment: segment,
  36194. finishProcessingFn: finishProcessingFn
  36195. });
  36196. var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  36197. activeXhrs.push(initSegmentXhr);
  36198. }
  36199. var segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
  36200. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  36201. responseType: 'arraybuffer',
  36202. headers: segmentXhrHeaders(segment)
  36203. });
  36204. var segmentRequestCallback = handleSegmentResponse({
  36205. segment: segment,
  36206. finishProcessingFn: finishProcessingFn,
  36207. responseType: segmentRequestOptions.responseType
  36208. });
  36209. var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  36210. segmentXhr.addEventListener('progress', handleProgress({
  36211. segment: segment,
  36212. progressFn: progressFn,
  36213. trackInfoFn: trackInfoFn,
  36214. timingInfoFn: timingInfoFn,
  36215. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  36216. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  36217. id3Fn: id3Fn,
  36218. captionsFn: captionsFn,
  36219. isEndOfTimeline: isEndOfTimeline,
  36220. endedTimelineFn: endedTimelineFn,
  36221. dataFn: dataFn
  36222. }));
  36223. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  36224. // multiple times, provide a shared state object
  36225. var loadendState = {};
  36226. activeXhrs.forEach(function (activeXhr) {
  36227. activeXhr.addEventListener('loadend', handleLoadEnd({
  36228. loadendState: loadendState,
  36229. abortFn: abortFn
  36230. }));
  36231. });
  36232. return function () {
  36233. return abortAll(activeXhrs);
  36234. };
  36235. };
  36236. /**
  36237. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  36238. * codec strings, or translating codec strings into objects that can be examined.
  36239. */
  36240. var logFn$1 = logger('CodecUtils');
  36241. /**
  36242. * Returns a set of codec strings parsed from the playlist or the default
  36243. * codec strings if no codecs were specified in the playlist
  36244. *
  36245. * @param {Playlist} media the current media playlist
  36246. * @return {Object} an object with the video and audio codecs
  36247. */
  36248. var getCodecs = function getCodecs(media) {
  36249. // if the codecs were explicitly specified, use them instead of the
  36250. // defaults
  36251. var mediaAttributes = media.attributes || {};
  36252. if (mediaAttributes.CODECS) {
  36253. return codecs_js.parseCodecs(mediaAttributes.CODECS);
  36254. }
  36255. };
  36256. var isMaat = function isMaat(master, media) {
  36257. var mediaAttributes = media.attributes || {};
  36258. return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36259. };
  36260. var isMuxed = function isMuxed(master, media) {
  36261. if (!isMaat(master, media)) {
  36262. return true;
  36263. }
  36264. var mediaAttributes = media.attributes || {};
  36265. var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  36266. for (var groupId in audioGroup) {
  36267. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  36268. // or there are listed playlists (the case for DASH, as the manifest will have already
  36269. // provided all of the details necessary to generate the audio playlist, as opposed to
  36270. // HLS' externally requested playlists), then the content is demuxed.
  36271. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  36272. return true;
  36273. }
  36274. }
  36275. return false;
  36276. };
  36277. var unwrapCodecList = function unwrapCodecList(codecList) {
  36278. var codecs = {};
  36279. codecList.forEach(function (_ref) {
  36280. var mediaType = _ref.mediaType,
  36281. type = _ref.type,
  36282. details = _ref.details;
  36283. codecs[mediaType] = codecs[mediaType] || [];
  36284. codecs[mediaType].push(codecs_js.translateLegacyCodec("" + type + details));
  36285. });
  36286. Object.keys(codecs).forEach(function (mediaType) {
  36287. if (codecs[mediaType].length > 1) {
  36288. 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.");
  36289. codecs[mediaType] = null;
  36290. return;
  36291. }
  36292. codecs[mediaType] = codecs[mediaType][0];
  36293. });
  36294. return codecs;
  36295. };
  36296. var codecCount = function codecCount(codecObj) {
  36297. var count = 0;
  36298. if (codecObj.audio) {
  36299. count++;
  36300. }
  36301. if (codecObj.video) {
  36302. count++;
  36303. }
  36304. return count;
  36305. };
  36306. /**
  36307. * Calculates the codec strings for a working configuration of
  36308. * SourceBuffers to play variant streams in a master playlist. If
  36309. * there is no possible working configuration, an empty object will be
  36310. * returned.
  36311. *
  36312. * @param master {Object} the m3u8 object for the master playlist
  36313. * @param media {Object} the m3u8 object for the variant playlist
  36314. * @return {Object} the codec strings.
  36315. *
  36316. * @private
  36317. */
  36318. var codecsForPlaylist = function codecsForPlaylist(master, media) {
  36319. var mediaAttributes = media.attributes || {};
  36320. var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  36321. // Put another way, there is no way to have a video-only multiple-audio HLS!
  36322. if (isMaat(master, media) && !codecInfo.audio) {
  36323. if (!isMuxed(master, media)) {
  36324. // It is possible for codecs to be specified on the audio media group playlist but
  36325. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  36326. // video are always separate (and separately specified).
  36327. var defaultCodecs = unwrapCodecList(codecs_js.codecsFromDefault(master, mediaAttributes.AUDIO) || []);
  36328. if (defaultCodecs.audio) {
  36329. codecInfo.audio = defaultCodecs.audio;
  36330. }
  36331. }
  36332. }
  36333. return codecInfo;
  36334. };
  36335. var logFn = logger('PlaylistSelector');
  36336. var representationToString = function representationToString(representation) {
  36337. if (!representation || !representation.playlist) {
  36338. return;
  36339. }
  36340. var playlist = representation.playlist;
  36341. return JSON.stringify({
  36342. id: playlist.id,
  36343. bandwidth: representation.bandwidth,
  36344. width: representation.width,
  36345. height: representation.height,
  36346. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  36347. });
  36348. }; // Utilities
  36349. /**
  36350. * Returns the CSS value for the specified property on an element
  36351. * using `getComputedStyle`. Firefox has a long-standing issue where
  36352. * getComputedStyle() may return null when running in an iframe with
  36353. * `display: none`.
  36354. *
  36355. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  36356. * @param {HTMLElement} el the htmlelement to work on
  36357. * @param {string} the proprety to get the style for
  36358. */
  36359. var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
  36360. if (!el) {
  36361. return '';
  36362. }
  36363. var result = window__default['default'].getComputedStyle(el);
  36364. if (!result) {
  36365. return '';
  36366. }
  36367. return result[property];
  36368. };
  36369. /**
  36370. * Resuable stable sort function
  36371. *
  36372. * @param {Playlists} array
  36373. * @param {Function} sortFn Different comparators
  36374. * @function stableSort
  36375. */
  36376. var stableSort = function stableSort(array, sortFn) {
  36377. var newArray = array.slice();
  36378. array.sort(function (left, right) {
  36379. var cmp = sortFn(left, right);
  36380. if (cmp === 0) {
  36381. return newArray.indexOf(left) - newArray.indexOf(right);
  36382. }
  36383. return cmp;
  36384. });
  36385. };
  36386. /**
  36387. * A comparator function to sort two playlist object by bandwidth.
  36388. *
  36389. * @param {Object} left a media playlist object
  36390. * @param {Object} right a media playlist object
  36391. * @return {number} Greater than zero if the bandwidth attribute of
  36392. * left is greater than the corresponding attribute of right. Less
  36393. * than zero if the bandwidth of right is greater than left and
  36394. * exactly zero if the two are equal.
  36395. */
  36396. var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
  36397. var leftBandwidth;
  36398. var rightBandwidth;
  36399. if (left.attributes.BANDWIDTH) {
  36400. leftBandwidth = left.attributes.BANDWIDTH;
  36401. }
  36402. leftBandwidth = leftBandwidth || window__default['default'].Number.MAX_VALUE;
  36403. if (right.attributes.BANDWIDTH) {
  36404. rightBandwidth = right.attributes.BANDWIDTH;
  36405. }
  36406. rightBandwidth = rightBandwidth || window__default['default'].Number.MAX_VALUE;
  36407. return leftBandwidth - rightBandwidth;
  36408. };
  36409. /**
  36410. * A comparator function to sort two playlist object by resolution (width).
  36411. *
  36412. * @param {Object} left a media playlist object
  36413. * @param {Object} right a media playlist object
  36414. * @return {number} Greater than zero if the resolution.width attribute of
  36415. * left is greater than the corresponding attribute of right. Less
  36416. * than zero if the resolution.width of right is greater than left and
  36417. * exactly zero if the two are equal.
  36418. */
  36419. var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
  36420. var leftWidth;
  36421. var rightWidth;
  36422. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  36423. leftWidth = left.attributes.RESOLUTION.width;
  36424. }
  36425. leftWidth = leftWidth || window__default['default'].Number.MAX_VALUE;
  36426. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  36427. rightWidth = right.attributes.RESOLUTION.width;
  36428. }
  36429. rightWidth = rightWidth || window__default['default'].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  36430. // have the same media dimensions/ resolution
  36431. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  36432. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  36433. }
  36434. return leftWidth - rightWidth;
  36435. };
  36436. /**
  36437. * Chooses the appropriate media playlist based on bandwidth and player size
  36438. *
  36439. * @param {Object} master
  36440. * Object representation of the master manifest
  36441. * @param {number} playerBandwidth
  36442. * Current calculated bandwidth of the player
  36443. * @param {number} playerWidth
  36444. * Current width of the player element (should account for the device pixel ratio)
  36445. * @param {number} playerHeight
  36446. * Current height of the player element (should account for the device pixel ratio)
  36447. * @param {boolean} limitRenditionByPlayerDimensions
  36448. * True if the player width and height should be used during the selection, false otherwise
  36449. * @param {Object} masterPlaylistController
  36450. * the current masterPlaylistController object
  36451. * @return {Playlist} the highest bitrate playlist less than the
  36452. * currently detected bandwidth, accounting for some amount of
  36453. * bandwidth variance
  36454. */
  36455. var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
  36456. // If we end up getting called before `master` is available, exit early
  36457. if (!master) {
  36458. return;
  36459. }
  36460. var options = {
  36461. bandwidth: playerBandwidth,
  36462. width: playerWidth,
  36463. height: playerHeight,
  36464. limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
  36465. };
  36466. var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
  36467. if (Playlist.isAudioOnly(master)) {
  36468. playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  36469. // at the buttom of this function for debugging.
  36470. options.audioOnly = true;
  36471. } // convert the playlists to an intermediary representation to make comparisons easier
  36472. var sortedPlaylistReps = playlists.map(function (playlist) {
  36473. var bandwidth;
  36474. var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  36475. var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  36476. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  36477. bandwidth = bandwidth || window__default['default'].Number.MAX_VALUE;
  36478. return {
  36479. bandwidth: bandwidth,
  36480. width: width,
  36481. height: height,
  36482. playlist: playlist
  36483. };
  36484. });
  36485. stableSort(sortedPlaylistReps, function (left, right) {
  36486. return left.bandwidth - right.bandwidth;
  36487. }); // filter out any playlists that have been excluded due to
  36488. // incompatible configurations
  36489. sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  36490. return !Playlist.isIncompatible(rep.playlist);
  36491. }); // filter out any playlists that have been disabled manually through the representations
  36492. // api or blacklisted temporarily due to playback errors.
  36493. var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  36494. return Playlist.isEnabled(rep.playlist);
  36495. });
  36496. if (!enabledPlaylistReps.length) {
  36497. // if there are no enabled playlists, then they have all been blacklisted or disabled
  36498. // by the user through the representations api. In this case, ignore blacklisting and
  36499. // fallback to what the user wants by using playlists the user has not disabled.
  36500. enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  36501. return !Playlist.isDisabled(rep.playlist);
  36502. });
  36503. } // filter out any variant that has greater effective bitrate
  36504. // than the current estimated bandwidth
  36505. var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
  36506. return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
  36507. });
  36508. var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  36509. // and then taking the very first element
  36510. var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
  36511. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  36512. })[0]; // if we're not going to limit renditions by player size, make an early decision.
  36513. if (limitRenditionByPlayerDimensions === false) {
  36514. var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36515. if (_chosenRep && _chosenRep.playlist) {
  36516. var type = 'sortedPlaylistReps';
  36517. if (bandwidthBestRep) {
  36518. type = 'bandwidthBestRep';
  36519. }
  36520. if (enabledPlaylistReps[0]) {
  36521. type = 'enabledPlaylistReps';
  36522. }
  36523. logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
  36524. return _chosenRep.playlist;
  36525. }
  36526. logFn('could not choose a playlist with options', options);
  36527. return null;
  36528. } // filter out playlists without resolution information
  36529. var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
  36530. return rep.width && rep.height;
  36531. }); // sort variants by resolution
  36532. stableSort(haveResolution, function (left, right) {
  36533. return left.width - right.width;
  36534. }); // if we have the exact resolution as the player use it
  36535. var resolutionBestRepList = haveResolution.filter(function (rep) {
  36536. return rep.width === playerWidth && rep.height === playerHeight;
  36537. });
  36538. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  36539. var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
  36540. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  36541. })[0];
  36542. var resolutionPlusOneList;
  36543. var resolutionPlusOneSmallest;
  36544. var resolutionPlusOneRep; // find the smallest variant that is larger than the player
  36545. // if there is no match of exact resolution
  36546. if (!resolutionBestRep) {
  36547. resolutionPlusOneList = haveResolution.filter(function (rep) {
  36548. return rep.width > playerWidth || rep.height > playerHeight;
  36549. }); // find all the variants have the same smallest resolution
  36550. resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
  36551. return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
  36552. }); // ensure that we also pick the highest bandwidth variant that
  36553. // is just-larger-than the video player
  36554. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  36555. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
  36556. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  36557. })[0];
  36558. }
  36559. var leastPixelDiffRep; // If this selector proves to be better than others,
  36560. // resolutionPlusOneRep and resolutionBestRep and all
  36561. // the code involving them should be removed.
  36562. if (masterPlaylistController.experimentalLeastPixelDiffSelector) {
  36563. // find the variant that is closest to the player's pixel size
  36564. var leastPixelDiffList = haveResolution.map(function (rep) {
  36565. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  36566. return rep;
  36567. }); // get the highest bandwidth, closest resolution playlist
  36568. stableSort(leastPixelDiffList, function (left, right) {
  36569. // sort by highest bandwidth if pixelDiff is the same
  36570. if (left.pixelDiff === right.pixelDiff) {
  36571. return right.bandwidth - left.bandwidth;
  36572. }
  36573. return left.pixelDiff - right.pixelDiff;
  36574. });
  36575. leastPixelDiffRep = leastPixelDiffList[0];
  36576. } // fallback chain of variants
  36577. var chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  36578. if (chosenRep && chosenRep.playlist) {
  36579. var _type = 'sortedPlaylistReps';
  36580. if (leastPixelDiffRep) {
  36581. _type = 'leastPixelDiffRep';
  36582. } else if (resolutionPlusOneRep) {
  36583. _type = 'resolutionPlusOneRep';
  36584. } else if (resolutionBestRep) {
  36585. _type = 'resolutionBestRep';
  36586. } else if (bandwidthBestRep) {
  36587. _type = 'bandwidthBestRep';
  36588. } else if (enabledPlaylistReps[0]) {
  36589. _type = 'enabledPlaylistReps';
  36590. }
  36591. logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
  36592. return chosenRep.playlist;
  36593. }
  36594. logFn('could not choose a playlist with options', options);
  36595. return null;
  36596. };
  36597. /**
  36598. * Chooses the appropriate media playlist based on the most recent
  36599. * bandwidth estimate and the player size.
  36600. *
  36601. * Expects to be called within the context of an instance of VhsHandler
  36602. *
  36603. * @return {Playlist} the highest bitrate playlist less than the
  36604. * currently detected bandwidth, accounting for some amount of
  36605. * bandwidth variance
  36606. */
  36607. var lastBandwidthSelector = function lastBandwidthSelector() {
  36608. var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
  36609. return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
  36610. };
  36611. /**
  36612. * Chooses the appropriate media playlist based on an
  36613. * exponential-weighted moving average of the bandwidth after
  36614. * filtering for player size.
  36615. *
  36616. * Expects to be called within the context of an instance of VhsHandler
  36617. *
  36618. * @param {number} decay - a number between 0 and 1. Higher values of
  36619. * this parameter will cause previous bandwidth estimates to lose
  36620. * significance more quickly.
  36621. * @return {Function} a function which can be invoked to create a new
  36622. * playlist selector function.
  36623. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  36624. */
  36625. var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
  36626. var average = -1;
  36627. var lastSystemBandwidth = -1;
  36628. if (decay < 0 || decay > 1) {
  36629. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  36630. }
  36631. return function () {
  36632. var pixelRatio = this.useDevicePixelRatio ? window__default['default'].devicePixelRatio || 1 : 1;
  36633. if (average < 0) {
  36634. average = this.systemBandwidth;
  36635. lastSystemBandwidth = this.systemBandwidth;
  36636. } // stop the average value from decaying for every 250ms
  36637. // when the systemBandwidth is constant
  36638. // and
  36639. // stop average from setting to a very low value when the
  36640. // systemBandwidth becomes 0 in case of chunk cancellation
  36641. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  36642. average = decay * this.systemBandwidth + (1 - decay) * average;
  36643. lastSystemBandwidth = this.systemBandwidth;
  36644. }
  36645. return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
  36646. };
  36647. };
  36648. /**
  36649. * Chooses the appropriate media playlist based on the potential to rebuffer
  36650. *
  36651. * @param {Object} settings
  36652. * Object of information required to use this selector
  36653. * @param {Object} settings.master
  36654. * Object representation of the master manifest
  36655. * @param {number} settings.currentTime
  36656. * The current time of the player
  36657. * @param {number} settings.bandwidth
  36658. * Current measured bandwidth
  36659. * @param {number} settings.duration
  36660. * Duration of the media
  36661. * @param {number} settings.segmentDuration
  36662. * Segment duration to be used in round trip time calculations
  36663. * @param {number} settings.timeUntilRebuffer
  36664. * Time left in seconds until the player has to rebuffer
  36665. * @param {number} settings.currentTimeline
  36666. * The current timeline segments are being loaded from
  36667. * @param {SyncController} settings.syncController
  36668. * SyncController for determining if we have a sync point for a given playlist
  36669. * @return {Object|null}
  36670. * {Object} return.playlist
  36671. * The highest bandwidth playlist with the least amount of rebuffering
  36672. * {Number} return.rebufferingImpact
  36673. * The amount of time in seconds switching to this playlist will rebuffer. A
  36674. * negative value means that switching will cause zero rebuffering.
  36675. */
  36676. var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
  36677. var master = settings.master,
  36678. currentTime = settings.currentTime,
  36679. bandwidth = settings.bandwidth,
  36680. duration = settings.duration,
  36681. segmentDuration = settings.segmentDuration,
  36682. timeUntilRebuffer = settings.timeUntilRebuffer,
  36683. currentTimeline = settings.currentTimeline,
  36684. syncController = settings.syncController; // filter out any playlists that have been excluded due to
  36685. // incompatible configurations
  36686. var compatiblePlaylists = master.playlists.filter(function (playlist) {
  36687. return !Playlist.isIncompatible(playlist);
  36688. }); // filter out any playlists that have been disabled manually through the representations
  36689. // api or blacklisted temporarily due to playback errors.
  36690. var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  36691. if (!enabledPlaylists.length) {
  36692. // if there are no enabled playlists, then they have all been blacklisted or disabled
  36693. // by the user through the representations api. In this case, ignore blacklisting and
  36694. // fallback to what the user wants by using playlists the user has not disabled.
  36695. enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
  36696. return !Playlist.isDisabled(playlist);
  36697. });
  36698. }
  36699. var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  36700. var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
  36701. var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  36702. // sync request first. This will double the request time
  36703. var numRequests = syncPoint ? 1 : 2;
  36704. var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  36705. var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  36706. return {
  36707. playlist: playlist,
  36708. rebufferingImpact: rebufferingImpact
  36709. };
  36710. });
  36711. var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
  36712. return estimate.rebufferingImpact <= 0;
  36713. }); // Sort by bandwidth DESC
  36714. stableSort(noRebufferingPlaylists, function (a, b) {
  36715. return comparePlaylistBandwidth(b.playlist, a.playlist);
  36716. });
  36717. if (noRebufferingPlaylists.length) {
  36718. return noRebufferingPlaylists[0];
  36719. }
  36720. stableSort(rebufferingEstimates, function (a, b) {
  36721. return a.rebufferingImpact - b.rebufferingImpact;
  36722. });
  36723. return rebufferingEstimates[0] || null;
  36724. };
  36725. /**
  36726. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  36727. * one with video. If no renditions with video exist, return the lowest audio rendition.
  36728. *
  36729. * Expects to be called within the context of an instance of VhsHandler
  36730. *
  36731. * @return {Object|null}
  36732. * {Object} return.playlist
  36733. * The lowest bitrate playlist that contains a video codec. If no such rendition
  36734. * exists pick the lowest audio rendition.
  36735. */
  36736. var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
  36737. var _this = this; // filter out any playlists that have been excluded due to
  36738. // incompatible configurations or playback errors
  36739. var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  36740. stableSort(playlists, function (a, b) {
  36741. return comparePlaylistBandwidth(a, b);
  36742. }); // Parse and assume that playlists with no video codec have no video
  36743. // (this is not necessarily true, although it is generally true).
  36744. //
  36745. // If an entire manifest has no valid videos everything will get filtered
  36746. // out.
  36747. var playlistsWithVideo = playlists.filter(function (playlist) {
  36748. return !!codecsForPlaylist(_this.playlists.master, playlist).video;
  36749. });
  36750. return playlistsWithVideo[0] || null;
  36751. };
  36752. /**
  36753. * Combine all segments into a single Uint8Array
  36754. *
  36755. * @param {Object} segmentObj
  36756. * @return {Uint8Array} concatenated bytes
  36757. * @private
  36758. */
  36759. var concatSegments = function concatSegments(segmentObj) {
  36760. var offset = 0;
  36761. var tempBuffer;
  36762. if (segmentObj.bytes) {
  36763. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  36764. segmentObj.segments.forEach(function (segment) {
  36765. tempBuffer.set(segment, offset);
  36766. offset += segment.byteLength;
  36767. });
  36768. }
  36769. return tempBuffer;
  36770. };
  36771. /**
  36772. * @file text-tracks.js
  36773. */
  36774. /**
  36775. * Create captions text tracks on video.js if they do not exist
  36776. *
  36777. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  36778. * @param {Object} tech the video.js tech
  36779. * @param {Object} captionStream the caption stream to create
  36780. * @private
  36781. */
  36782. var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
  36783. if (!inbandTextTracks[captionStream]) {
  36784. tech.trigger({
  36785. type: 'usage',
  36786. name: 'vhs-608'
  36787. });
  36788. tech.trigger({
  36789. type: 'usage',
  36790. name: 'hls-608'
  36791. });
  36792. var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  36793. if (/^cc708_/.test(captionStream)) {
  36794. instreamId = 'SERVICE' + captionStream.split('_')[1];
  36795. }
  36796. var track = tech.textTracks().getTrackById(instreamId);
  36797. if (track) {
  36798. // Resuse an existing track with a CC# id because this was
  36799. // very likely created by videojs-contrib-hls from information
  36800. // in the m3u8 for us to use
  36801. inbandTextTracks[captionStream] = track;
  36802. } else {
  36803. // This section gets called when we have caption services that aren't specified in the manifest.
  36804. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  36805. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  36806. var label = captionStream;
  36807. var language = captionStream;
  36808. var def = false;
  36809. var captionService = captionServices[instreamId];
  36810. if (captionService) {
  36811. label = captionService.label;
  36812. language = captionService.language;
  36813. def = captionService["default"];
  36814. } // Otherwise, create a track with the default `CC#` label and
  36815. // without a language
  36816. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  36817. kind: 'captions',
  36818. id: instreamId,
  36819. // TODO: investigate why this doesn't seem to turn the caption on by default
  36820. "default": def,
  36821. label: label,
  36822. language: language
  36823. }, false).track;
  36824. }
  36825. }
  36826. };
  36827. /**
  36828. * Add caption text track data to a source handler given an array of captions
  36829. *
  36830. * @param {Object}
  36831. * @param {Object} inbandTextTracks the inband text tracks
  36832. * @param {number} timestampOffset the timestamp offset of the source buffer
  36833. * @param {Array} captionArray an array of caption data
  36834. * @private
  36835. */
  36836. var addCaptionData = function addCaptionData(_ref) {
  36837. var inbandTextTracks = _ref.inbandTextTracks,
  36838. captionArray = _ref.captionArray,
  36839. timestampOffset = _ref.timestampOffset;
  36840. if (!captionArray) {
  36841. return;
  36842. }
  36843. var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
  36844. captionArray.forEach(function (caption) {
  36845. var track = caption.stream;
  36846. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  36847. });
  36848. };
  36849. /**
  36850. * Define properties on a cue for backwards compatability,
  36851. * but warn the user that the way that they are using it
  36852. * is depricated and will be removed at a later date.
  36853. *
  36854. * @param {Cue} cue the cue to add the properties on
  36855. * @private
  36856. */
  36857. var deprecateOldCue = function deprecateOldCue(cue) {
  36858. Object.defineProperties(cue.frame, {
  36859. id: {
  36860. get: function get() {
  36861. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  36862. return cue.value.key;
  36863. }
  36864. },
  36865. value: {
  36866. get: function get() {
  36867. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  36868. return cue.value.data;
  36869. }
  36870. },
  36871. privateData: {
  36872. get: function get() {
  36873. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  36874. return cue.value.data;
  36875. }
  36876. }
  36877. });
  36878. };
  36879. /**
  36880. * Add metadata text track data to a source handler given an array of metadata
  36881. *
  36882. * @param {Object}
  36883. * @param {Object} inbandTextTracks the inband text tracks
  36884. * @param {Array} metadataArray an array of meta data
  36885. * @param {number} timestampOffset the timestamp offset of the source buffer
  36886. * @param {number} videoDuration the duration of the video
  36887. * @private
  36888. */
  36889. var addMetadata = function addMetadata(_ref2) {
  36890. var inbandTextTracks = _ref2.inbandTextTracks,
  36891. metadataArray = _ref2.metadataArray,
  36892. timestampOffset = _ref2.timestampOffset,
  36893. videoDuration = _ref2.videoDuration;
  36894. if (!metadataArray) {
  36895. return;
  36896. }
  36897. var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
  36898. var metadataTrack = inbandTextTracks.metadataTrack_;
  36899. if (!metadataTrack) {
  36900. return;
  36901. }
  36902. metadataArray.forEach(function (metadata) {
  36903. var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  36904. // ignore this bit of metadata.
  36905. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  36906. // which is the "Title/Songname/Content description" frame
  36907. if (typeof time !== 'number' || window__default['default'].isNaN(time) || time < 0 || !(time < Infinity)) {
  36908. return;
  36909. }
  36910. metadata.frames.forEach(function (frame) {
  36911. var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  36912. cue.frame = frame;
  36913. cue.value = frame;
  36914. deprecateOldCue(cue);
  36915. metadataTrack.addCue(cue);
  36916. });
  36917. });
  36918. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  36919. return;
  36920. } // Updating the metadeta cues so that
  36921. // the endTime of each cue is the startTime of the next cue
  36922. // the endTime of last cue is the duration of the video
  36923. var cues = metadataTrack.cues;
  36924. var cuesArray = []; // Create a copy of the TextTrackCueList...
  36925. // ...disregarding cues with a falsey value
  36926. for (var i = 0; i < cues.length; i++) {
  36927. if (cues[i]) {
  36928. cuesArray.push(cues[i]);
  36929. }
  36930. } // Group cues by their startTime value
  36931. var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
  36932. var timeSlot = obj[cue.startTime] || [];
  36933. timeSlot.push(cue);
  36934. obj[cue.startTime] = timeSlot;
  36935. return obj;
  36936. }, {}); // Sort startTimes by ascending order
  36937. var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
  36938. return Number(a) - Number(b);
  36939. }); // Map each cue group's endTime to the next group's startTime
  36940. sortedStartTimes.forEach(function (startTime, idx) {
  36941. var cueGroup = cuesGroupedByStartTime[startTime];
  36942. var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  36943. cueGroup.forEach(function (cue) {
  36944. cue.endTime = nextTime;
  36945. });
  36946. });
  36947. };
  36948. /**
  36949. * Create metadata text track on video.js if it does not exist
  36950. *
  36951. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  36952. * @param {string} dispatchType the inband metadata track dispatch type
  36953. * @param {Object} tech the video.js tech
  36954. * @private
  36955. */
  36956. var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
  36957. if (inbandTextTracks.metadataTrack_) {
  36958. return;
  36959. }
  36960. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  36961. kind: 'metadata',
  36962. label: 'Timed Metadata'
  36963. }, false).track;
  36964. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  36965. };
  36966. /**
  36967. * Remove cues from a track on video.js.
  36968. *
  36969. * @param {Double} start start of where we should remove the cue
  36970. * @param {Double} end end of where the we should remove the cue
  36971. * @param {Object} track the text track to remove the cues from
  36972. * @private
  36973. */
  36974. var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
  36975. var i;
  36976. var cue;
  36977. if (!track) {
  36978. return;
  36979. }
  36980. if (!track.cues) {
  36981. return;
  36982. }
  36983. i = track.cues.length;
  36984. while (i--) {
  36985. cue = track.cues[i]; // Remove any cue within the provided start and end time
  36986. if (cue.startTime >= start && cue.endTime <= end) {
  36987. track.removeCue(cue);
  36988. }
  36989. }
  36990. };
  36991. /**
  36992. * Remove duplicate cues from a track on video.js (a cue is considered a
  36993. * duplicate if it has the same time interval and text as another)
  36994. *
  36995. * @param {Object} track the text track to remove the duplicate cues from
  36996. * @private
  36997. */
  36998. var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
  36999. var cues = track.cues;
  37000. if (!cues) {
  37001. return;
  37002. }
  37003. for (var i = 0; i < cues.length; i++) {
  37004. var duplicates = [];
  37005. var occurrences = 0;
  37006. for (var j = 0; j < cues.length; j++) {
  37007. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  37008. occurrences++;
  37009. if (occurrences > 1) {
  37010. duplicates.push(cues[j]);
  37011. }
  37012. }
  37013. }
  37014. if (duplicates.length) {
  37015. duplicates.forEach(function (dupe) {
  37016. return track.removeCue(dupe);
  37017. });
  37018. }
  37019. }
  37020. };
  37021. /**
  37022. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  37023. * front of current time.
  37024. *
  37025. * @param {Array} buffer
  37026. * The current buffer of gop information
  37027. * @param {number} currentTime
  37028. * The current time
  37029. * @param {Double} mapping
  37030. * Offset to map display time to stream presentation time
  37031. * @return {Array}
  37032. * List of gops considered safe to append over
  37033. */
  37034. var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
  37035. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  37036. return [];
  37037. } // pts value for current time + 3 seconds to give a bit more wiggle room
  37038. var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  37039. var i;
  37040. for (i = 0; i < buffer.length; i++) {
  37041. if (buffer[i].pts > currentTimePts) {
  37042. break;
  37043. }
  37044. }
  37045. return buffer.slice(i);
  37046. };
  37047. /**
  37048. * Appends gop information (timing and byteLength) received by the transmuxer for the
  37049. * gops appended in the last call to appendBuffer
  37050. *
  37051. * @param {Array} buffer
  37052. * The current buffer of gop information
  37053. * @param {Array} gops
  37054. * List of new gop information
  37055. * @param {boolean} replace
  37056. * If true, replace the buffer with the new gop information. If false, append the
  37057. * new gop information to the buffer in the right location of time.
  37058. * @return {Array}
  37059. * Updated list of gop information
  37060. */
  37061. var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
  37062. if (!gops.length) {
  37063. return buffer;
  37064. }
  37065. if (replace) {
  37066. // If we are in safe append mode, then completely overwrite the gop buffer
  37067. // with the most recent appeneded data. This will make sure that when appending
  37068. // future segments, we only try to align with gops that are both ahead of current
  37069. // time and in the last segment appended.
  37070. return gops.slice();
  37071. }
  37072. var start = gops[0].pts;
  37073. var i = 0;
  37074. for (i; i < buffer.length; i++) {
  37075. if (buffer[i].pts >= start) {
  37076. break;
  37077. }
  37078. }
  37079. return buffer.slice(0, i).concat(gops);
  37080. };
  37081. /**
  37082. * Removes gop information in buffer that overlaps with provided start and end
  37083. *
  37084. * @param {Array} buffer
  37085. * The current buffer of gop information
  37086. * @param {Double} start
  37087. * position to start the remove at
  37088. * @param {Double} end
  37089. * position to end the remove at
  37090. * @param {Double} mapping
  37091. * Offset to map display time to stream presentation time
  37092. */
  37093. var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
  37094. var startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  37095. var endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  37096. var updatedBuffer = buffer.slice();
  37097. var i = buffer.length;
  37098. while (i--) {
  37099. if (buffer[i].pts <= endPts) {
  37100. break;
  37101. }
  37102. }
  37103. if (i === -1) {
  37104. // no removal because end of remove range is before start of buffer
  37105. return updatedBuffer;
  37106. }
  37107. var j = i + 1;
  37108. while (j--) {
  37109. if (buffer[j].pts <= startPts) {
  37110. break;
  37111. }
  37112. } // clamp remove range start to 0 index
  37113. j = Math.max(j, 0);
  37114. updatedBuffer.splice(j, i - j + 1);
  37115. return updatedBuffer;
  37116. };
  37117. var shallowEqual = function shallowEqual(a, b) {
  37118. // if both are undefined
  37119. // or one or the other is undefined
  37120. // they are not equal
  37121. if (!a && !b || !a && b || a && !b) {
  37122. return false;
  37123. } // they are the same object and thus, equal
  37124. if (a === b) {
  37125. return true;
  37126. } // sort keys so we can make sure they have
  37127. // all the same keys later.
  37128. var akeys = Object.keys(a).sort();
  37129. var bkeys = Object.keys(b).sort(); // different number of keys, not equal
  37130. if (akeys.length !== bkeys.length) {
  37131. return false;
  37132. }
  37133. for (var i = 0; i < akeys.length; i++) {
  37134. var key = akeys[i]; // different sorted keys, not equal
  37135. if (key !== bkeys[i]) {
  37136. return false;
  37137. } // different values, not equal
  37138. if (a[key] !== b[key]) {
  37139. return false;
  37140. }
  37141. }
  37142. return true;
  37143. }; // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  37144. var QUOTA_EXCEEDED_ERR = 22;
  37145. /**
  37146. * The segment loader has no recourse except to fetch a segment in the
  37147. * current playlist and use the internal timestamps in that segment to
  37148. * generate a syncPoint. This function returns a good candidate index
  37149. * for that process.
  37150. *
  37151. * @param {Array} segments - the segments array from a playlist.
  37152. * @return {number} An index of a segment from the playlist to load
  37153. */
  37154. var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
  37155. segments = segments || [];
  37156. var timelineSegments = [];
  37157. var time = 0;
  37158. for (var i = 0; i < segments.length; i++) {
  37159. var segment = segments[i];
  37160. if (currentTimeline === segment.timeline) {
  37161. timelineSegments.push(i);
  37162. time += segment.duration;
  37163. if (time > targetTime) {
  37164. return i;
  37165. }
  37166. }
  37167. }
  37168. if (timelineSegments.length === 0) {
  37169. return 0;
  37170. } // default to the last timeline segment
  37171. return timelineSegments[timelineSegments.length - 1];
  37172. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  37173. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  37174. // as a start to prevent any potential issues with removing content too close to the
  37175. // playhead.
  37176. var MIN_BACK_BUFFER = 1; // in ms
  37177. var CHECK_BUFFER_DELAY = 500;
  37178. var finite = function finite(num) {
  37179. return typeof num === 'number' && isFinite(num);
  37180. }; // With most content hovering around 30fps, if a segment has a duration less than a half
  37181. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  37182. // not accurately reflect the rest of the content.
  37183. var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  37184. var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
  37185. // Although these checks should most likely cover non 'main' types, for now it narrows
  37186. // the scope of our checks.
  37187. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  37188. return null;
  37189. }
  37190. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  37191. return 'Neither audio nor video found in segment.';
  37192. }
  37193. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  37194. 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.';
  37195. }
  37196. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  37197. 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.';
  37198. }
  37199. return null;
  37200. };
  37201. /**
  37202. * Calculates a time value that is safe to remove from the back buffer without interrupting
  37203. * playback.
  37204. *
  37205. * @param {TimeRange} seekable
  37206. * The current seekable range
  37207. * @param {number} currentTime
  37208. * The current time of the player
  37209. * @param {number} targetDuration
  37210. * The target duration of the current playlist
  37211. * @return {number}
  37212. * Time that is safe to remove from the back buffer without interrupting playback
  37213. */
  37214. var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
  37215. // 30 seconds before the playhead provides a safe default for trimming.
  37216. //
  37217. // Choosing a reasonable default is particularly important for high bitrate content and
  37218. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  37219. // throw an APPEND_BUFFER_ERR.
  37220. var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  37221. if (seekable.length) {
  37222. // Some live playlists may have a shorter window of content than the full allowed back
  37223. // buffer. For these playlists, don't save content that's no longer within the window.
  37224. trimTime = Math.max(trimTime, seekable.start(0));
  37225. } // Don't remove within target duration of the current time to avoid the possibility of
  37226. // removing the GOP currently being played, as removing it can cause playback stalls.
  37227. var maxTrimTime = currentTime - targetDuration;
  37228. return Math.min(maxTrimTime, trimTime);
  37229. };
  37230. var segmentInfoString = function segmentInfoString(segmentInfo) {
  37231. var startOfSegment = segmentInfo.startOfSegment,
  37232. duration = segmentInfo.duration,
  37233. segment = segmentInfo.segment,
  37234. part = segmentInfo.part,
  37235. _segmentInfo$playlist = segmentInfo.playlist,
  37236. seq = _segmentInfo$playlist.mediaSequence,
  37237. id = _segmentInfo$playlist.id,
  37238. _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
  37239. segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
  37240. index = segmentInfo.mediaIndex,
  37241. partIndex = segmentInfo.partIndex,
  37242. timeline = segmentInfo.timeline;
  37243. var segmentLen = segments.length - 1;
  37244. var selection = 'mediaIndex/partIndex increment';
  37245. if (segmentInfo.getMediaInfoForTime) {
  37246. selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
  37247. } else if (segmentInfo.isSyncRequest) {
  37248. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  37249. }
  37250. if (segmentInfo.independent) {
  37251. selection += " with independent " + segmentInfo.independent;
  37252. }
  37253. var hasPartIndex = typeof partIndex === 'number';
  37254. var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  37255. var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  37256. preloadSegment: segment
  37257. }) - 1 : 0;
  37258. 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 + "]");
  37259. };
  37260. var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
  37261. return mediaType + "TimingInfo";
  37262. };
  37263. /**
  37264. * Returns the timestamp offset to use for the segment.
  37265. *
  37266. * @param {number} segmentTimeline
  37267. * The timeline of the segment
  37268. * @param {number} currentTimeline
  37269. * The timeline currently being followed by the loader
  37270. * @param {number} startOfSegment
  37271. * The estimated segment start
  37272. * @param {TimeRange[]} buffered
  37273. * The loader's buffer
  37274. * @param {boolean} overrideCheck
  37275. * If true, no checks are made to see if the timestamp offset value should be set,
  37276. * but sets it directly to a value.
  37277. *
  37278. * @return {number|null}
  37279. * Either a number representing a new timestamp offset, or null if the segment is
  37280. * part of the same timeline
  37281. */
  37282. var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
  37283. var segmentTimeline = _ref.segmentTimeline,
  37284. currentTimeline = _ref.currentTimeline,
  37285. startOfSegment = _ref.startOfSegment,
  37286. buffered = _ref.buffered,
  37287. overrideCheck = _ref.overrideCheck; // Check to see if we are crossing a discontinuity to see if we need to set the
  37288. // timestamp offset on the transmuxer and source buffer.
  37289. //
  37290. // Previously, we changed the timestampOffset if the start of this segment was less than
  37291. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  37292. // behavior, especially around long running live streams.
  37293. if (!overrideCheck && segmentTimeline === currentTimeline) {
  37294. return null;
  37295. } // When changing renditions, it's possible to request a segment on an older timeline. For
  37296. // instance, given two renditions with the following:
  37297. //
  37298. // #EXTINF:10
  37299. // segment1
  37300. // #EXT-X-DISCONTINUITY
  37301. // #EXTINF:10
  37302. // segment2
  37303. // #EXTINF:10
  37304. // segment3
  37305. //
  37306. // And the current player state:
  37307. //
  37308. // current time: 8
  37309. // buffer: 0 => 20
  37310. //
  37311. // The next segment on the current rendition would be segment3, filling the buffer from
  37312. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  37313. // then the next segment to be requested will be segment1 from the new rendition in
  37314. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  37315. // content (since it would position segment1 of the new rendition starting at 20s). This
  37316. // case can be identified when the new segment's timeline is a prior value. Instead of
  37317. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  37318. // more accurate to the actual start time of the segment.
  37319. if (segmentTimeline < currentTimeline) {
  37320. return startOfSegment;
  37321. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  37322. // value uses the end of the last segment if it is available. While this value
  37323. // should often be correct, it's better to rely on the buffered end, as the new
  37324. // content post discontinuity should line up with the buffered end as if it were
  37325. // time 0 for the new content.
  37326. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  37327. };
  37328. /**
  37329. * Returns whether or not the loader should wait for a timeline change from the timeline
  37330. * change controller before processing the segment.
  37331. *
  37332. * Primary timing in VHS goes by video. This is different from most media players, as
  37333. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  37334. * will continue to use video as the primary timing source, due to the current logic and
  37335. * expectations built around it.
  37336. * Since the timing follows video, in order to maintain sync, the video loader is
  37337. * responsible for setting both audio and video source buffer timestamp offsets.
  37338. *
  37339. * Setting different values for audio and video source buffers could lead to
  37340. * desyncing. The following examples demonstrate some of the situations where this
  37341. * distinction is important. Note that all of these cases involve demuxed content. When
  37342. * content is muxed, the audio and video are packaged together, therefore syncing
  37343. * separate media playlists is not an issue.
  37344. *
  37345. * CASE 1: Audio prepares to load a new timeline before video:
  37346. *
  37347. * Timeline: 0 1
  37348. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37349. * Audio Loader: ^
  37350. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37351. * Video Loader ^
  37352. *
  37353. * In the above example, the audio loader is preparing to load the 6th segment, the first
  37354. * after a discontinuity, while the video loader is still loading the 5th segment, before
  37355. * the discontinuity.
  37356. *
  37357. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  37358. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  37359. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  37360. * the audio loader must provide the audioAppendStart value to trim the content in the
  37361. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  37362. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  37363. * segment until that value is provided.
  37364. *
  37365. * CASE 2: Video prepares to load a new timeline before audio:
  37366. *
  37367. * Timeline: 0 1
  37368. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37369. * Audio Loader: ^
  37370. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37371. * Video Loader ^
  37372. *
  37373. * In the above example, the video loader is preparing to load the 6th segment, the first
  37374. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  37375. * the discontinuity.
  37376. *
  37377. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  37378. * segment is loaded and processed, both the video and audio timestamp offsets will be
  37379. * set, since video is used as the primary timing source. This is to ensure content lines
  37380. * up appropriately, as any modifications to the video timing are reflected by audio when
  37381. * the video loader sets the audio and video timestamp offsets to the same value. However,
  37382. * setting the timestamp offset for audio before audio has had a chance to change
  37383. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  37384. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  37385. *
  37386. * CASE 3: When seeking, audio prepares to load a new timeline before video
  37387. *
  37388. * Timeline: 0 1
  37389. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37390. * Audio Loader: ^
  37391. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  37392. * Video Loader ^
  37393. *
  37394. * In the above example, both audio and video loaders are loading segments from timeline
  37395. * 0, but imagine that the seek originated from timeline 1.
  37396. *
  37397. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  37398. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  37399. * must wait for the video loader to load its segment and update both the audio and video
  37400. * timestamp offsets before it may load and append its own segment. This is the case
  37401. * whether the seek results in a mismatched segment request (e.g., the audio loader
  37402. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  37403. * loaders choose to load the same segment index from each playlist, as the segments may
  37404. * not be aligned perfectly, even for matching segment indexes.
  37405. *
  37406. * @param {Object} timelinechangeController
  37407. * @param {number} currentTimeline
  37408. * The timeline currently being followed by the loader
  37409. * @param {number} segmentTimeline
  37410. * The timeline of the segment being loaded
  37411. * @param {('main'|'audio')} loaderType
  37412. * The loader type
  37413. * @param {boolean} audioDisabled
  37414. * Whether the audio is disabled for the loader. This should only be true when the
  37415. * loader may have muxed audio in its segment, but should not append it, e.g., for
  37416. * the main loader when an alternate audio playlist is active.
  37417. *
  37418. * @return {boolean}
  37419. * Whether the loader should wait for a timeline change from the timeline change
  37420. * controller before processing the segment
  37421. */
  37422. var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
  37423. var timelineChangeController = _ref2.timelineChangeController,
  37424. currentTimeline = _ref2.currentTimeline,
  37425. segmentTimeline = _ref2.segmentTimeline,
  37426. loaderType = _ref2.loaderType,
  37427. audioDisabled = _ref2.audioDisabled;
  37428. if (currentTimeline === segmentTimeline) {
  37429. return false;
  37430. }
  37431. if (loaderType === 'audio') {
  37432. var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  37433. type: 'main'
  37434. }); // Audio loader should wait if:
  37435. //
  37436. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  37437. // * main hasn't yet changed to the timeline audio is looking to load
  37438. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  37439. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  37440. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  37441. // loader's segments (or the content is audio/video only and handled by the main
  37442. // loader).
  37443. if (loaderType === 'main' && audioDisabled) {
  37444. var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  37445. type: 'audio'
  37446. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  37447. // change to the current timeline.
  37448. //
  37449. // Since the main loader is responsible for setting the timestamp offset for both
  37450. // audio and video, the main loader must wait for audio to be about to change to its
  37451. // timeline before setting the offset, otherwise, if audio is behind in loading,
  37452. // segments from the previous timeline would be adjusted by the new timestamp offset.
  37453. //
  37454. // This requirement means that video will not cross a timeline until the audio is
  37455. // about to cross to it, so that way audio and video will always cross the timeline
  37456. // together.
  37457. //
  37458. // In addition to normal timeline changes, these rules also apply to the start of a
  37459. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  37460. // that these rules apply to the first timeline change because if they did not, it's
  37461. // possible that the main loader will cross two timelines before the audio loader has
  37462. // crossed one. Logic may be implemented to handle the startup as a special case, but
  37463. // it's easier to simply treat all timeline changes the same.
  37464. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  37465. return false;
  37466. }
  37467. return true;
  37468. }
  37469. return false;
  37470. };
  37471. var mediaDuration = function mediaDuration(timingInfos) {
  37472. var maxDuration = 0;
  37473. ['video', 'audio'].forEach(function (type) {
  37474. var typeTimingInfo = timingInfos[type + "TimingInfo"];
  37475. if (!typeTimingInfo) {
  37476. return;
  37477. }
  37478. var start = typeTimingInfo.start,
  37479. end = typeTimingInfo.end;
  37480. var duration;
  37481. if (typeof start === 'bigint' || typeof end === 'bigint') {
  37482. duration = window__default['default'].BigInt(end) - window__default['default'].BigInt(start);
  37483. } else if (typeof start === 'number' && typeof end === 'number') {
  37484. duration = end - start;
  37485. }
  37486. if (typeof duration !== 'undefined' && duration > maxDuration) {
  37487. maxDuration = duration;
  37488. }
  37489. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  37490. // as we only need BigInt when we are above that.
  37491. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  37492. maxDuration = Number(maxDuration);
  37493. }
  37494. return maxDuration;
  37495. };
  37496. var segmentTooLong = function segmentTooLong(_ref3) {
  37497. var segmentDuration = _ref3.segmentDuration,
  37498. maxDuration = _ref3.maxDuration; // 0 duration segments are most likely due to metadata only segments or a lack of
  37499. // information.
  37500. if (!segmentDuration) {
  37501. return false;
  37502. } // For HLS:
  37503. //
  37504. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  37505. // The EXTINF duration of each Media Segment in the Playlist
  37506. // file, when rounded to the nearest integer, MUST be less than or equal
  37507. // to the target duration; longer segments can trigger playback stalls
  37508. // or other errors.
  37509. //
  37510. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  37511. // duration. Although that reported duration is occasionally approximate (i.e., not
  37512. // exact), a strict check may report that a segment is too long more often in DASH.
  37513. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  37514. };
  37515. var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
  37516. // Right now we aren't following DASH's timing model exactly, so only perform
  37517. // this check for HLS content.
  37518. if (sourceType !== 'hls') {
  37519. return null;
  37520. }
  37521. var segmentDuration = mediaDuration({
  37522. audioTimingInfo: segmentInfo.audioTimingInfo,
  37523. videoTimingInfo: segmentInfo.videoTimingInfo
  37524. }); // Don't report if we lack information.
  37525. //
  37526. // If the segment has a duration of 0 it is either a lack of information or a
  37527. // metadata only segment and shouldn't be reported here.
  37528. if (!segmentDuration) {
  37529. return null;
  37530. }
  37531. var targetDuration = segmentInfo.playlist.targetDuration;
  37532. var isSegmentWayTooLong = segmentTooLong({
  37533. segmentDuration: segmentDuration,
  37534. maxDuration: targetDuration * 2
  37535. });
  37536. var isSegmentSlightlyTooLong = segmentTooLong({
  37537. segmentDuration: segmentDuration,
  37538. maxDuration: targetDuration
  37539. });
  37540. var 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';
  37541. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  37542. return {
  37543. severity: isSegmentWayTooLong ? 'warn' : 'info',
  37544. message: segmentTooLongMessage
  37545. };
  37546. }
  37547. return null;
  37548. };
  37549. /**
  37550. * An object that manages segment loading and appending.
  37551. *
  37552. * @class SegmentLoader
  37553. * @param {Object} options required and optional options
  37554. * @extends videojs.EventTarget
  37555. */
  37556. var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
  37557. _inheritsLoose__default['default'](SegmentLoader, _videojs$EventTarget);
  37558. function SegmentLoader(settings, options) {
  37559. var _this;
  37560. _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
  37561. if (!settings) {
  37562. throw new TypeError('Initialization settings are required');
  37563. }
  37564. if (typeof settings.currentTime !== 'function') {
  37565. throw new TypeError('No currentTime getter specified');
  37566. }
  37567. if (!settings.mediaSource) {
  37568. throw new TypeError('No MediaSource specified');
  37569. } // public properties
  37570. _this.bandwidth = settings.bandwidth;
  37571. _this.throughput = {
  37572. rate: 0,
  37573. count: 0
  37574. };
  37575. _this.roundTrip = NaN;
  37576. _this.resetStats_();
  37577. _this.mediaIndex = null;
  37578. _this.partIndex = null; // private settings
  37579. _this.hasPlayed_ = settings.hasPlayed;
  37580. _this.currentTime_ = settings.currentTime;
  37581. _this.seekable_ = settings.seekable;
  37582. _this.seeking_ = settings.seeking;
  37583. _this.duration_ = settings.duration;
  37584. _this.mediaSource_ = settings.mediaSource;
  37585. _this.vhs_ = settings.vhs;
  37586. _this.loaderType_ = settings.loaderType;
  37587. _this.currentMediaInfo_ = void 0;
  37588. _this.startingMediaInfo_ = void 0;
  37589. _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  37590. _this.goalBufferLength_ = settings.goalBufferLength;
  37591. _this.sourceType_ = settings.sourceType;
  37592. _this.sourceUpdater_ = settings.sourceUpdater;
  37593. _this.inbandTextTracks_ = settings.inbandTextTracks;
  37594. _this.state_ = 'INIT';
  37595. _this.timelineChangeController_ = settings.timelineChangeController;
  37596. _this.shouldSaveSegmentTimingInfo_ = true;
  37597. _this.parse708captions_ = settings.parse708captions;
  37598. _this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  37599. _this.captionServices_ = settings.captionServices;
  37600. _this.experimentalExactManifestTimings = settings.experimentalExactManifestTimings; // private instance variables
  37601. _this.checkBufferTimeout_ = null;
  37602. _this.error_ = void 0;
  37603. _this.currentTimeline_ = -1;
  37604. _this.pendingSegment_ = null;
  37605. _this.xhrOptions_ = null;
  37606. _this.pendingSegments_ = [];
  37607. _this.audioDisabled_ = false;
  37608. _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  37609. _this.gopBuffer_ = [];
  37610. _this.timeMapping_ = 0;
  37611. _this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  37612. _this.appendInitSegment_ = {
  37613. audio: true,
  37614. video: true
  37615. };
  37616. _this.playlistOfLastInitSegment_ = {
  37617. audio: null,
  37618. video: null
  37619. };
  37620. _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  37621. // information yet to start the loading process (e.g., if the audio loader wants to
  37622. // load a segment from the next timeline but the main loader hasn't yet crossed that
  37623. // timeline), then the load call will be added to the queue until it is ready to be
  37624. // processed.
  37625. _this.loadQueue_ = [];
  37626. _this.metadataQueue_ = {
  37627. id3: [],
  37628. caption: []
  37629. };
  37630. _this.waitingOnRemove_ = false;
  37631. _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  37632. _this.activeInitSegmentId_ = null;
  37633. _this.initSegments_ = {}; // HLSe playback
  37634. _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  37635. _this.keyCache_ = {};
  37636. _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  37637. // between a time in the display time and a segment index within
  37638. // a playlist
  37639. _this.syncController_ = settings.syncController;
  37640. _this.syncPoint_ = {
  37641. segmentIndex: 0,
  37642. time: 0
  37643. };
  37644. _this.transmuxer_ = _this.createTransmuxer_();
  37645. _this.triggerSyncInfoUpdate_ = function () {
  37646. return _this.trigger('syncinfoupdate');
  37647. };
  37648. _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
  37649. _this.mediaSource_.addEventListener('sourceopen', function () {
  37650. if (!_this.isEndOfStream_()) {
  37651. _this.ended_ = false;
  37652. }
  37653. }); // ...for determining the fetch location
  37654. _this.fetchAtBuffer_ = false;
  37655. _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
  37656. Object.defineProperty(_assertThisInitialized__default['default'](_this), 'state', {
  37657. get: function get() {
  37658. return this.state_;
  37659. },
  37660. set: function set(newState) {
  37661. if (newState !== this.state_) {
  37662. this.logger_(this.state_ + " -> " + newState);
  37663. this.state_ = newState;
  37664. this.trigger('statechange');
  37665. }
  37666. }
  37667. });
  37668. _this.sourceUpdater_.on('ready', function () {
  37669. if (_this.hasEnoughInfoToAppend_()) {
  37670. _this.processCallQueue_();
  37671. }
  37672. }); // Only the main loader needs to listen for pending timeline changes, as the main
  37673. // loader should wait for audio to be ready to change its timeline so that both main
  37674. // and audio timelines change together. For more details, see the
  37675. // shouldWaitForTimelineChange function.
  37676. if (_this.loaderType_ === 'main') {
  37677. _this.timelineChangeController_.on('pendingtimelinechange', function () {
  37678. if (_this.hasEnoughInfoToAppend_()) {
  37679. _this.processCallQueue_();
  37680. }
  37681. });
  37682. } // The main loader only listens on pending timeline changes, but the audio loader,
  37683. // since its loads follow main, needs to listen on timeline changes. For more details,
  37684. // see the shouldWaitForTimelineChange function.
  37685. if (_this.loaderType_ === 'audio') {
  37686. _this.timelineChangeController_.on('timelinechange', function () {
  37687. if (_this.hasEnoughInfoToLoad_()) {
  37688. _this.processLoadQueue_();
  37689. }
  37690. if (_this.hasEnoughInfoToAppend_()) {
  37691. _this.processCallQueue_();
  37692. }
  37693. });
  37694. }
  37695. return _this;
  37696. }
  37697. var _proto = SegmentLoader.prototype;
  37698. _proto.createTransmuxer_ = function createTransmuxer_() {
  37699. return segmentTransmuxer.createTransmuxer({
  37700. remux: false,
  37701. alignGopsAtEnd: this.safeAppend_,
  37702. keepOriginalTimestamps: true,
  37703. parse708captions: this.parse708captions_,
  37704. captionServices: this.captionServices_
  37705. });
  37706. }
  37707. /**
  37708. * reset all of our media stats
  37709. *
  37710. * @private
  37711. */
  37712. ;
  37713. _proto.resetStats_ = function resetStats_() {
  37714. this.mediaBytesTransferred = 0;
  37715. this.mediaRequests = 0;
  37716. this.mediaRequestsAborted = 0;
  37717. this.mediaRequestsTimedout = 0;
  37718. this.mediaRequestsErrored = 0;
  37719. this.mediaTransferDuration = 0;
  37720. this.mediaSecondsLoaded = 0;
  37721. this.mediaAppends = 0;
  37722. }
  37723. /**
  37724. * dispose of the SegmentLoader and reset to the default state
  37725. */
  37726. ;
  37727. _proto.dispose = function dispose() {
  37728. this.trigger('dispose');
  37729. this.state = 'DISPOSED';
  37730. this.pause();
  37731. this.abort_();
  37732. if (this.transmuxer_) {
  37733. this.transmuxer_.terminate();
  37734. }
  37735. this.resetStats_();
  37736. if (this.checkBufferTimeout_) {
  37737. window__default['default'].clearTimeout(this.checkBufferTimeout_);
  37738. }
  37739. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  37740. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  37741. }
  37742. this.off();
  37743. };
  37744. _proto.setAudio = function setAudio(enable) {
  37745. this.audioDisabled_ = !enable;
  37746. if (enable) {
  37747. this.appendInitSegment_.audio = true;
  37748. } else {
  37749. // remove current track audio if it gets disabled
  37750. this.sourceUpdater_.removeAudio(0, this.duration_());
  37751. }
  37752. }
  37753. /**
  37754. * abort anything that is currently doing on with the SegmentLoader
  37755. * and reset to a default state
  37756. */
  37757. ;
  37758. _proto.abort = function abort() {
  37759. if (this.state !== 'WAITING') {
  37760. if (this.pendingSegment_) {
  37761. this.pendingSegment_ = null;
  37762. }
  37763. return;
  37764. }
  37765. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  37766. // since we are no longer "waiting" on any requests. XHR callback is not always run
  37767. // when the request is aborted. This will prevent the loader from being stuck in the
  37768. // WAITING state indefinitely.
  37769. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  37770. // next segment
  37771. if (!this.paused()) {
  37772. this.monitorBuffer_();
  37773. }
  37774. }
  37775. /**
  37776. * abort all pending xhr requests and null any pending segements
  37777. *
  37778. * @private
  37779. */
  37780. ;
  37781. _proto.abort_ = function abort_() {
  37782. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  37783. this.pendingSegment_.abortRequests();
  37784. } // clear out the segment being processed
  37785. this.pendingSegment_ = null;
  37786. this.callQueue_ = [];
  37787. this.loadQueue_ = [];
  37788. this.metadataQueue_.id3 = [];
  37789. this.metadataQueue_.caption = [];
  37790. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  37791. this.waitingOnRemove_ = false;
  37792. window__default['default'].clearTimeout(this.quotaExceededErrorRetryTimeout_);
  37793. this.quotaExceededErrorRetryTimeout_ = null;
  37794. };
  37795. _proto.checkForAbort_ = function checkForAbort_(requestId) {
  37796. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  37797. // callback that happens should reset the state to READY so that loading can continue.
  37798. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  37799. this.state = 'READY';
  37800. return true;
  37801. }
  37802. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  37803. return true;
  37804. }
  37805. return false;
  37806. }
  37807. /**
  37808. * set an error on the segment loader and null out any pending segements
  37809. *
  37810. * @param {Error} error the error to set on the SegmentLoader
  37811. * @return {Error} the error that was set or that is currently set
  37812. */
  37813. ;
  37814. _proto.error = function error(_error) {
  37815. if (typeof _error !== 'undefined') {
  37816. this.logger_('error occurred:', _error);
  37817. this.error_ = _error;
  37818. }
  37819. this.pendingSegment_ = null;
  37820. return this.error_;
  37821. };
  37822. _proto.endOfStream = function endOfStream() {
  37823. this.ended_ = true;
  37824. if (this.transmuxer_) {
  37825. // need to clear out any cached data to prepare for the new segment
  37826. segmentTransmuxer.reset(this.transmuxer_);
  37827. }
  37828. this.gopBuffer_.length = 0;
  37829. this.pause();
  37830. this.trigger('ended');
  37831. }
  37832. /**
  37833. * Indicates which time ranges are buffered
  37834. *
  37835. * @return {TimeRange}
  37836. * TimeRange object representing the current buffered ranges
  37837. */
  37838. ;
  37839. _proto.buffered_ = function buffered_() {
  37840. var trackInfo = this.getMediaInfo_();
  37841. if (!this.sourceUpdater_ || !trackInfo) {
  37842. return videojs.createTimeRanges();
  37843. }
  37844. if (this.loaderType_ === 'main') {
  37845. var hasAudio = trackInfo.hasAudio,
  37846. hasVideo = trackInfo.hasVideo,
  37847. isMuxed = trackInfo.isMuxed;
  37848. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  37849. return this.sourceUpdater_.buffered();
  37850. }
  37851. if (hasVideo) {
  37852. return this.sourceUpdater_.videoBuffered();
  37853. }
  37854. } // One case that can be ignored for now is audio only with alt audio,
  37855. // as we don't yet have proper support for that.
  37856. return this.sourceUpdater_.audioBuffered();
  37857. }
  37858. /**
  37859. * Gets and sets init segment for the provided map
  37860. *
  37861. * @param {Object} map
  37862. * The map object representing the init segment to get or set
  37863. * @param {boolean=} set
  37864. * If true, the init segment for the provided map should be saved
  37865. * @return {Object}
  37866. * map object for desired init segment
  37867. */
  37868. ;
  37869. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  37870. if (set === void 0) {
  37871. set = false;
  37872. }
  37873. if (!map) {
  37874. return null;
  37875. }
  37876. var id = initSegmentId(map);
  37877. var storedMap = this.initSegments_[id];
  37878. if (set && !storedMap && map.bytes) {
  37879. this.initSegments_[id] = storedMap = {
  37880. resolvedUri: map.resolvedUri,
  37881. byterange: map.byterange,
  37882. bytes: map.bytes,
  37883. tracks: map.tracks,
  37884. timescales: map.timescales
  37885. };
  37886. }
  37887. return storedMap || map;
  37888. }
  37889. /**
  37890. * Gets and sets key for the provided key
  37891. *
  37892. * @param {Object} key
  37893. * The key object representing the key to get or set
  37894. * @param {boolean=} set
  37895. * If true, the key for the provided key should be saved
  37896. * @return {Object}
  37897. * Key object for desired key
  37898. */
  37899. ;
  37900. _proto.segmentKey = function segmentKey(key, set) {
  37901. if (set === void 0) {
  37902. set = false;
  37903. }
  37904. if (!key) {
  37905. return null;
  37906. }
  37907. var id = segmentKeyId(key);
  37908. var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  37909. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  37910. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  37911. this.keyCache_[id] = storedKey = {
  37912. resolvedUri: key.resolvedUri,
  37913. bytes: key.bytes
  37914. };
  37915. }
  37916. var result = {
  37917. resolvedUri: (storedKey || key).resolvedUri
  37918. };
  37919. if (storedKey) {
  37920. result.bytes = storedKey.bytes;
  37921. }
  37922. return result;
  37923. }
  37924. /**
  37925. * Returns true if all configuration required for loading is present, otherwise false.
  37926. *
  37927. * @return {boolean} True if the all configuration is ready for loading
  37928. * @private
  37929. */
  37930. ;
  37931. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  37932. return this.playlist_ && !this.paused();
  37933. }
  37934. /**
  37935. * load a playlist and start to fill the buffer
  37936. */
  37937. ;
  37938. _proto.load = function load() {
  37939. // un-pause
  37940. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  37941. // specified
  37942. if (!this.playlist_) {
  37943. return;
  37944. } // if all the configuration is ready, initialize and begin loading
  37945. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  37946. return this.init_();
  37947. } // if we're in the middle of processing a segment already, don't
  37948. // kick off an additional segment request
  37949. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  37950. return;
  37951. }
  37952. this.state = 'READY';
  37953. }
  37954. /**
  37955. * Once all the starting parameters have been specified, begin
  37956. * operation. This method should only be invoked from the INIT
  37957. * state.
  37958. *
  37959. * @private
  37960. */
  37961. ;
  37962. _proto.init_ = function init_() {
  37963. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  37964. // audio data from the muxed content should be removed
  37965. this.resetEverything();
  37966. return this.monitorBuffer_();
  37967. }
  37968. /**
  37969. * set a playlist on the segment loader
  37970. *
  37971. * @param {PlaylistLoader} media the playlist to set on the segment loader
  37972. */
  37973. ;
  37974. _proto.playlist = function playlist(newPlaylist, options) {
  37975. if (options === void 0) {
  37976. options = {};
  37977. }
  37978. if (!newPlaylist) {
  37979. return;
  37980. }
  37981. var oldPlaylist = this.playlist_;
  37982. var segmentInfo = this.pendingSegment_;
  37983. this.playlist_ = newPlaylist;
  37984. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  37985. // is always our zero-time so force a sync update each time the playlist
  37986. // is refreshed from the server
  37987. //
  37988. // Use the INIT state to determine if playback has started, as the playlist sync info
  37989. // should be fixed once requests begin (as sync points are generated based on sync
  37990. // info), but not before then.
  37991. if (this.state === 'INIT') {
  37992. newPlaylist.syncInfo = {
  37993. mediaSequence: newPlaylist.mediaSequence,
  37994. time: 0
  37995. }; // Setting the date time mapping means mapping the program date time (if available)
  37996. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  37997. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  37998. // be updated as the playlist is refreshed before the loader starts loading, the
  37999. // program date time mapping needs to be updated as well.
  38000. //
  38001. // This mapping is only done for the main loader because a program date time should
  38002. // map equivalently between playlists.
  38003. if (this.loaderType_ === 'main') {
  38004. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  38005. }
  38006. }
  38007. var oldId = null;
  38008. if (oldPlaylist) {
  38009. if (oldPlaylist.id) {
  38010. oldId = oldPlaylist.id;
  38011. } else if (oldPlaylist.uri) {
  38012. oldId = oldPlaylist.uri;
  38013. }
  38014. }
  38015. this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  38016. // in LIVE, we always want to update with new playlists (including refreshes)
  38017. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  38018. // buffering now
  38019. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  38020. return this.init_();
  38021. }
  38022. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  38023. if (this.mediaIndex !== null) {
  38024. // we must reset/resync the segment loader when we switch renditions and
  38025. // the segment loader is already synced to the previous rendition
  38026. // on playlist changes we want it to be possible to fetch
  38027. // at the buffer for vod but not for live. So we use resetLoader
  38028. // for live and resyncLoader for vod. We want this because
  38029. // if a playlist uses independent and non-independent segments/parts the
  38030. // buffer may not accurately reflect the next segment that we should try
  38031. // downloading.
  38032. if (!newPlaylist.endList) {
  38033. this.resetLoader();
  38034. } else {
  38035. this.resyncLoader();
  38036. }
  38037. }
  38038. this.currentMediaInfo_ = void 0;
  38039. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  38040. return;
  38041. } // we reloaded the same playlist so we are in a live scenario
  38042. // and we will likely need to adjust the mediaIndex
  38043. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  38044. this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
  38045. // this is important because we can abort a request and this value must be
  38046. // equal to the last appended mediaIndex
  38047. if (this.mediaIndex !== null) {
  38048. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  38049. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  38050. // new playlist was incremented by 1.
  38051. if (this.mediaIndex < 0) {
  38052. this.mediaIndex = null;
  38053. this.partIndex = null;
  38054. } else {
  38055. var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  38056. // unless parts fell off of the playlist for this segment.
  38057. // In that case we need to reset partIndex and resync
  38058. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  38059. var mediaIndex = this.mediaIndex;
  38060. this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
  38061. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  38062. // as the part was dropped from our current playlists segment.
  38063. // The mediaIndex will still be valid so keep that around.
  38064. this.mediaIndex = mediaIndex;
  38065. }
  38066. }
  38067. } // update the mediaIndex on the SegmentInfo object
  38068. // this is important because we will update this.mediaIndex with this value
  38069. // in `handleAppendsDone_` after the segment has been successfully appended
  38070. if (segmentInfo) {
  38071. segmentInfo.mediaIndex -= mediaSequenceDiff;
  38072. if (segmentInfo.mediaIndex < 0) {
  38073. segmentInfo.mediaIndex = null;
  38074. segmentInfo.partIndex = null;
  38075. } else {
  38076. // we need to update the referenced segment so that timing information is
  38077. // saved for the new playlist's segment, however, if the segment fell off the
  38078. // playlist, we can leave the old reference and just lose the timing info
  38079. if (segmentInfo.mediaIndex >= 0) {
  38080. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  38081. }
  38082. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  38083. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  38084. }
  38085. }
  38086. }
  38087. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  38088. }
  38089. /**
  38090. * Prevent the loader from fetching additional segments. If there
  38091. * is a segment request outstanding, it will finish processing
  38092. * before the loader halts. A segment loader can be unpaused by
  38093. * calling load().
  38094. */
  38095. ;
  38096. _proto.pause = function pause() {
  38097. if (this.checkBufferTimeout_) {
  38098. window__default['default'].clearTimeout(this.checkBufferTimeout_);
  38099. this.checkBufferTimeout_ = null;
  38100. }
  38101. }
  38102. /**
  38103. * Returns whether the segment loader is fetching additional
  38104. * segments when given the opportunity. This property can be
  38105. * modified through calls to pause() and load().
  38106. */
  38107. ;
  38108. _proto.paused = function paused() {
  38109. return this.checkBufferTimeout_ === null;
  38110. }
  38111. /**
  38112. * Delete all the buffered data and reset the SegmentLoader
  38113. *
  38114. * @param {Function} [done] an optional callback to be executed when the remove
  38115. * operation is complete
  38116. */
  38117. ;
  38118. _proto.resetEverything = function resetEverything(done) {
  38119. this.ended_ = false;
  38120. this.activeInitSegmentId_ = null;
  38121. this.appendInitSegment_ = {
  38122. audio: true,
  38123. video: true
  38124. };
  38125. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  38126. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  38127. // we then clamp the value to duration if necessary.
  38128. this.remove(0, Infinity, done); // clears fmp4 captions
  38129. if (this.transmuxer_) {
  38130. this.transmuxer_.postMessage({
  38131. action: 'clearAllMp4Captions'
  38132. }); // reset the cache in the transmuxer
  38133. this.transmuxer_.postMessage({
  38134. action: 'reset'
  38135. });
  38136. }
  38137. }
  38138. /**
  38139. * Force the SegmentLoader to resync and start loading around the currentTime instead
  38140. * of starting at the end of the buffer
  38141. *
  38142. * Useful for fast quality changes
  38143. */
  38144. ;
  38145. _proto.resetLoader = function resetLoader() {
  38146. this.fetchAtBuffer_ = false;
  38147. this.resyncLoader();
  38148. }
  38149. /**
  38150. * Force the SegmentLoader to restart synchronization and make a conservative guess
  38151. * before returning to the simple walk-forward method
  38152. */
  38153. ;
  38154. _proto.resyncLoader = function resyncLoader() {
  38155. if (this.transmuxer_) {
  38156. // need to clear out any cached data to prepare for the new segment
  38157. segmentTransmuxer.reset(this.transmuxer_);
  38158. }
  38159. this.mediaIndex = null;
  38160. this.partIndex = null;
  38161. this.syncPoint_ = null;
  38162. this.isPendingTimestampOffset_ = false;
  38163. this.callQueue_ = [];
  38164. this.loadQueue_ = [];
  38165. this.metadataQueue_.id3 = [];
  38166. this.metadataQueue_.caption = [];
  38167. this.abort();
  38168. if (this.transmuxer_) {
  38169. this.transmuxer_.postMessage({
  38170. action: 'clearParsedMp4Captions'
  38171. });
  38172. }
  38173. }
  38174. /**
  38175. * Remove any data in the source buffer between start and end times
  38176. *
  38177. * @param {number} start - the start time of the region to remove from the buffer
  38178. * @param {number} end - the end time of the region to remove from the buffer
  38179. * @param {Function} [done] - an optional callback to be executed when the remove
  38180. * @param {boolean} force - force all remove operations to happen
  38181. * operation is complete
  38182. */
  38183. ;
  38184. _proto.remove = function remove(start, end, done, force) {
  38185. if (done === void 0) {
  38186. done = function done() {};
  38187. }
  38188. if (force === void 0) {
  38189. force = false;
  38190. } // clamp end to duration if we need to remove everything.
  38191. // This is due to a browser bug that causes issues if we remove to Infinity.
  38192. // videojs/videojs-contrib-hls#1225
  38193. if (end === Infinity) {
  38194. end = this.duration_();
  38195. } // skip removes that would throw an error
  38196. // commonly happens during a rendition switch at the start of a video
  38197. // from start 0 to end 0
  38198. if (end <= start) {
  38199. this.logger_('skipping remove because end ${end} is <= start ${start}');
  38200. return;
  38201. }
  38202. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  38203. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  38204. return;
  38205. } // set it to one to complete this function's removes
  38206. var removesRemaining = 1;
  38207. var removeFinished = function removeFinished() {
  38208. removesRemaining--;
  38209. if (removesRemaining === 0) {
  38210. done();
  38211. }
  38212. };
  38213. if (force || !this.audioDisabled_) {
  38214. removesRemaining++;
  38215. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  38216. } // While it would be better to only remove video if the main loader has video, this
  38217. // should be safe with audio only as removeVideo will call back even if there's no
  38218. // video buffer.
  38219. //
  38220. // In theory we can check to see if there's video before calling the remove, but in
  38221. // the event that we're switching between renditions and from video to audio only
  38222. // (when we add support for that), we may need to clear the video contents despite
  38223. // what the new media will contain.
  38224. if (force || this.loaderType_ === 'main') {
  38225. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  38226. removesRemaining++;
  38227. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  38228. } // remove any captions and ID3 tags
  38229. for (var track in this.inbandTextTracks_) {
  38230. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  38231. }
  38232. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  38233. removeFinished();
  38234. }
  38235. /**
  38236. * (re-)schedule monitorBufferTick_ to run as soon as possible
  38237. *
  38238. * @private
  38239. */
  38240. ;
  38241. _proto.monitorBuffer_ = function monitorBuffer_() {
  38242. if (this.checkBufferTimeout_) {
  38243. window__default['default'].clearTimeout(this.checkBufferTimeout_);
  38244. }
  38245. this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), 1);
  38246. }
  38247. /**
  38248. * As long as the SegmentLoader is in the READY state, periodically
  38249. * invoke fillBuffer_().
  38250. *
  38251. * @private
  38252. */
  38253. ;
  38254. _proto.monitorBufferTick_ = function monitorBufferTick_() {
  38255. if (this.state === 'READY') {
  38256. this.fillBuffer_();
  38257. }
  38258. if (this.checkBufferTimeout_) {
  38259. window__default['default'].clearTimeout(this.checkBufferTimeout_);
  38260. }
  38261. this.checkBufferTimeout_ = window__default['default'].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  38262. }
  38263. /**
  38264. * fill the buffer with segements unless the sourceBuffers are
  38265. * currently updating
  38266. *
  38267. * Note: this function should only ever be called by monitorBuffer_
  38268. * and never directly
  38269. *
  38270. * @private
  38271. */
  38272. ;
  38273. _proto.fillBuffer_ = function fillBuffer_() {
  38274. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  38275. // except when we're ready for the next segment, this check can most likely be removed
  38276. if (this.sourceUpdater_.updating()) {
  38277. return;
  38278. } // see if we need to begin loading immediately
  38279. var segmentInfo = this.chooseNextRequest_();
  38280. if (!segmentInfo) {
  38281. return;
  38282. }
  38283. if (typeof segmentInfo.timestampOffset === 'number') {
  38284. this.isPendingTimestampOffset_ = false;
  38285. this.timelineChangeController_.pendingTimelineChange({
  38286. type: this.loaderType_,
  38287. from: this.currentTimeline_,
  38288. to: segmentInfo.timeline
  38289. });
  38290. }
  38291. this.loadSegment_(segmentInfo);
  38292. }
  38293. /**
  38294. * Determines if we should call endOfStream on the media source based
  38295. * on the state of the buffer or if appened segment was the final
  38296. * segment in the playlist.
  38297. *
  38298. * @param {number} [mediaIndex] the media index of segment we last appended
  38299. * @param {Object} [playlist] a media playlist object
  38300. * @return {boolean} do we need to call endOfStream on the MediaSource
  38301. */
  38302. ;
  38303. _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
  38304. if (mediaIndex === void 0) {
  38305. mediaIndex = this.mediaIndex;
  38306. }
  38307. if (playlist === void 0) {
  38308. playlist = this.playlist_;
  38309. }
  38310. if (partIndex === void 0) {
  38311. partIndex = this.partIndex;
  38312. }
  38313. if (!playlist || !this.mediaSource_) {
  38314. return false;
  38315. }
  38316. var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  38317. var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  38318. var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
  38319. // so that MediaSources can trigger the `ended` event when it runs out of
  38320. // buffered data instead of waiting for me
  38321. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  38322. }
  38323. /**
  38324. * Determines what request should be made given current segment loader state.
  38325. *
  38326. * @return {Object} a request object that describes the segment/part to load
  38327. */
  38328. ;
  38329. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  38330. var buffered = this.buffered_();
  38331. var bufferedEnd = lastBufferedEnd(buffered) || 0;
  38332. var bufferedTime = timeAheadOf(buffered, this.currentTime_());
  38333. var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  38334. var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  38335. var segments = this.playlist_.segments; // return no segment if:
  38336. // 1. we don't have segments
  38337. // 2. The video has not yet played and we already downloaded a segment
  38338. // 3. we already have enough buffered time
  38339. if (!segments.length || preloaded || haveEnoughBuffer) {
  38340. return null;
  38341. }
  38342. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  38343. var next = {
  38344. partIndex: null,
  38345. mediaIndex: null,
  38346. startOfSegment: null,
  38347. playlist: this.playlist_,
  38348. isSyncRequest: Boolean(!this.syncPoint_)
  38349. };
  38350. if (next.isSyncRequest) {
  38351. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  38352. } else if (this.mediaIndex !== null) {
  38353. var segment = segments[this.mediaIndex];
  38354. var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  38355. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  38356. if (segment.parts && segment.parts[partIndex + 1]) {
  38357. next.mediaIndex = this.mediaIndex;
  38358. next.partIndex = partIndex + 1;
  38359. } else {
  38360. next.mediaIndex = this.mediaIndex + 1;
  38361. }
  38362. } else {
  38363. // Find the segment containing the end of the buffer or current time.
  38364. var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
  38365. experimentalExactManifestTimings: this.experimentalExactManifestTimings,
  38366. playlist: this.playlist_,
  38367. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  38368. startingPartIndex: this.syncPoint_.partIndex,
  38369. startingSegmentIndex: this.syncPoint_.segmentIndex,
  38370. startTime: this.syncPoint_.time
  38371. }),
  38372. segmentIndex = _Playlist$getMediaInf.segmentIndex,
  38373. startTime = _Playlist$getMediaInf.startTime,
  38374. _partIndex = _Playlist$getMediaInf.partIndex;
  38375. next.getMediaInfoForTime = this.fetchAtBuffer_ ? "bufferedEnd " + bufferedEnd : "currentTime " + this.currentTime_();
  38376. next.mediaIndex = segmentIndex;
  38377. next.startOfSegment = startTime;
  38378. next.partIndex = _partIndex;
  38379. }
  38380. var nextSegment = segments[next.mediaIndex];
  38381. var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  38382. // the next partIndex is invalid do not choose a next segment.
  38383. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  38384. return null;
  38385. } // if the next segment has parts, and we don't have a partIndex.
  38386. // Set partIndex to 0
  38387. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  38388. next.partIndex = 0;
  38389. nextPart = nextSegment.parts[0];
  38390. } // if we have no buffered data then we need to make sure
  38391. // that the next part we append is "independent" if possible.
  38392. // So we check if the previous part is independent, and request
  38393. // it if it is.
  38394. if (!bufferedTime && nextPart && !nextPart.independent) {
  38395. if (next.partIndex === 0) {
  38396. var lastSegment = segments[next.mediaIndex - 1];
  38397. var lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  38398. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  38399. next.mediaIndex -= 1;
  38400. next.partIndex = lastSegment.parts.length - 1;
  38401. next.independent = 'previous segment';
  38402. }
  38403. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  38404. next.partIndex -= 1;
  38405. next.independent = 'previous part';
  38406. }
  38407. }
  38408. var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  38409. // 1. this is the last segment in the playlist
  38410. // 2. end of stream has been called on the media source already
  38411. // 3. the player is not seeking
  38412. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  38413. return null;
  38414. }
  38415. return this.generateSegmentInfo_(next);
  38416. };
  38417. _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
  38418. var independent = options.independent,
  38419. playlist = options.playlist,
  38420. mediaIndex = options.mediaIndex,
  38421. startOfSegment = options.startOfSegment,
  38422. isSyncRequest = options.isSyncRequest,
  38423. partIndex = options.partIndex,
  38424. forceTimestampOffset = options.forceTimestampOffset,
  38425. getMediaInfoForTime = options.getMediaInfoForTime;
  38426. var segment = playlist.segments[mediaIndex];
  38427. var part = typeof partIndex === 'number' && segment.parts[partIndex];
  38428. var segmentInfo = {
  38429. requestId: 'segment-loader-' + Math.random(),
  38430. // resolve the segment URL relative to the playlist
  38431. uri: part && part.resolvedUri || segment.resolvedUri,
  38432. // the segment's mediaIndex at the time it was requested
  38433. mediaIndex: mediaIndex,
  38434. partIndex: part ? partIndex : null,
  38435. // whether or not to update the SegmentLoader's state with this
  38436. // segment's mediaIndex
  38437. isSyncRequest: isSyncRequest,
  38438. startOfSegment: startOfSegment,
  38439. // the segment's playlist
  38440. playlist: playlist,
  38441. // unencrypted bytes of the segment
  38442. bytes: null,
  38443. // when a key is defined for this segment, the encrypted bytes
  38444. encryptedBytes: null,
  38445. // The target timestampOffset for this segment when we append it
  38446. // to the source buffer
  38447. timestampOffset: null,
  38448. // The timeline that the segment is in
  38449. timeline: segment.timeline,
  38450. // The expected duration of the segment in seconds
  38451. duration: part && part.duration || segment.duration,
  38452. // retain the segment in case the playlist updates while doing an async process
  38453. segment: segment,
  38454. part: part,
  38455. byteLength: 0,
  38456. transmuxer: this.transmuxer_,
  38457. // type of getMediaInfoForTime that was used to get this segment
  38458. getMediaInfoForTime: getMediaInfoForTime,
  38459. independent: independent
  38460. };
  38461. var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  38462. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  38463. segmentTimeline: segment.timeline,
  38464. currentTimeline: this.currentTimeline_,
  38465. startOfSegment: startOfSegment,
  38466. buffered: this.buffered_(),
  38467. overrideCheck: overrideCheck
  38468. });
  38469. var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  38470. if (typeof audioBufferedEnd === 'number') {
  38471. // since the transmuxer is using the actual timing values, but the buffer is
  38472. // adjusted by the timestamp offset, we must adjust the value here
  38473. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  38474. }
  38475. if (this.sourceUpdater_.videoBuffered().length) {
  38476. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  38477. // adjusted by the timestmap offset, we must adjust the value here
  38478. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  38479. }
  38480. return segmentInfo;
  38481. } // get the timestampoffset for a segment,
  38482. // added so that vtt segment loader can override and prevent
  38483. // adding timestamp offsets.
  38484. ;
  38485. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
  38486. return timestampOffsetForSegment(options);
  38487. }
  38488. /**
  38489. * Determines if the network has enough bandwidth to complete the current segment
  38490. * request in a timely manner. If not, the request will be aborted early and bandwidth
  38491. * updated to trigger a playlist switch.
  38492. *
  38493. * @param {Object} stats
  38494. * Object containing stats about the request timing and size
  38495. * @private
  38496. */
  38497. ;
  38498. _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
  38499. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  38500. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  38501. // the lowestEnabledRendition.
  38502. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  38503. !this.playlist_.attributes.BANDWIDTH) {
  38504. return;
  38505. } // Wait at least 1 second since the first byte of data has been received before
  38506. // using the calculated bandwidth from the progress event to allow the bitrate
  38507. // to stabilize
  38508. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  38509. return;
  38510. }
  38511. var currentTime = this.currentTime_();
  38512. var measuredBandwidth = stats.bandwidth;
  38513. var segmentDuration = this.pendingSegment_.duration;
  38514. var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  38515. // if we are only left with less than 1 second when the request completes.
  38516. // A negative timeUntilRebuffering indicates we are already rebuffering
  38517. var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  38518. // is larger than the estimated time until the player runs out of forward buffer
  38519. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  38520. return;
  38521. }
  38522. var switchCandidate = minRebufferMaxBandwidthSelector({
  38523. master: this.vhs_.playlists.master,
  38524. currentTime: currentTime,
  38525. bandwidth: measuredBandwidth,
  38526. duration: this.duration_(),
  38527. segmentDuration: segmentDuration,
  38528. timeUntilRebuffer: timeUntilRebuffer$1,
  38529. currentTimeline: this.currentTimeline_,
  38530. syncController: this.syncController_
  38531. });
  38532. if (!switchCandidate) {
  38533. return;
  38534. }
  38535. var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  38536. var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  38537. var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  38538. // potential round trip time of the new request so that we are not too aggressive
  38539. // with switching to a playlist that might save us a fraction of a second.
  38540. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  38541. minimumTimeSaving = 1;
  38542. }
  38543. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  38544. return;
  38545. } // set the bandwidth to that of the desired playlist being sure to scale by
  38546. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  38547. // don't trigger a bandwidthupdate as the bandwidth is artifial
  38548. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  38549. this.trigger('earlyabort');
  38550. };
  38551. _proto.handleAbort_ = function handleAbort_(segmentInfo) {
  38552. this.logger_("Aborting " + segmentInfoString(segmentInfo));
  38553. this.mediaRequestsAborted += 1;
  38554. }
  38555. /**
  38556. * XHR `progress` event handler
  38557. *
  38558. * @param {Event}
  38559. * The XHR `progress` event
  38560. * @param {Object} simpleSegment
  38561. * A simplified segment object copy
  38562. * @private
  38563. */
  38564. ;
  38565. _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
  38566. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38567. if (this.checkForAbort_(simpleSegment.requestId)) {
  38568. return;
  38569. }
  38570. this.trigger('progress');
  38571. };
  38572. _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
  38573. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38574. if (this.checkForAbort_(simpleSegment.requestId)) {
  38575. return;
  38576. }
  38577. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  38578. return;
  38579. }
  38580. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  38581. // Guard against cases where we're not getting track info at all until we are
  38582. // certain that all streams will provide it.
  38583. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  38584. this.appendInitSegment_ = {
  38585. audio: true,
  38586. video: true
  38587. };
  38588. this.startingMediaInfo_ = trackInfo;
  38589. this.currentMediaInfo_ = trackInfo;
  38590. this.logger_('trackinfo update', trackInfo);
  38591. this.trigger('trackinfo');
  38592. } // trackinfo may cause an abort if the trackinfo
  38593. // causes a codec change to an unsupported codec.
  38594. if (this.checkForAbort_(simpleSegment.requestId)) {
  38595. return;
  38596. } // set trackinfo on the pending segment so that
  38597. // it can append.
  38598. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  38599. if (this.hasEnoughInfoToAppend_()) {
  38600. this.processCallQueue_();
  38601. }
  38602. };
  38603. _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  38604. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38605. if (this.checkForAbort_(simpleSegment.requestId)) {
  38606. return;
  38607. }
  38608. var segmentInfo = this.pendingSegment_;
  38609. var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  38610. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  38611. segmentInfo[timingInfoProperty][timeType] = time;
  38612. this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
  38613. if (this.hasEnoughInfoToAppend_()) {
  38614. this.processCallQueue_();
  38615. }
  38616. };
  38617. _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
  38618. var _this2 = this;
  38619. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38620. if (this.checkForAbort_(simpleSegment.requestId)) {
  38621. return;
  38622. } // This could only happen with fmp4 segments, but
  38623. // should still not happen in general
  38624. if (captionData.length === 0) {
  38625. this.logger_('SegmentLoader received no captions from a caption event');
  38626. return;
  38627. }
  38628. var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  38629. // can be adjusted by the timestamp offset
  38630. if (!segmentInfo.hasAppendedData_) {
  38631. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  38632. return;
  38633. }
  38634. var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  38635. var captionTracks = {}; // get total start/end and captions for each track/stream
  38636. captionData.forEach(function (caption) {
  38637. // caption.stream is actually a track name...
  38638. // set to the existing values in tracks or default values
  38639. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  38640. // Infinity, as any other value will be less than this
  38641. startTime: Infinity,
  38642. captions: [],
  38643. // 0 as an other value will be more than this
  38644. endTime: 0
  38645. };
  38646. var captionTrack = captionTracks[caption.stream];
  38647. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  38648. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  38649. captionTrack.captions.push(caption);
  38650. });
  38651. Object.keys(captionTracks).forEach(function (trackName) {
  38652. var _captionTracks$trackN = captionTracks[trackName],
  38653. startTime = _captionTracks$trackN.startTime,
  38654. endTime = _captionTracks$trackN.endTime,
  38655. captions = _captionTracks$trackN.captions;
  38656. var inbandTextTracks = _this2.inbandTextTracks_;
  38657. _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
  38658. createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  38659. // We do this because a rendition change that also changes the timescale for captions
  38660. // will result in captions being re-parsed for certain segments. If we add them again
  38661. // without clearing we will have two of the same captions visible.
  38662. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  38663. addCaptionData({
  38664. captionArray: captions,
  38665. inbandTextTracks: inbandTextTracks,
  38666. timestampOffset: timestampOffset
  38667. });
  38668. }); // Reset stored captions since we added parsed
  38669. // captions to a text track at this point
  38670. if (this.transmuxer_) {
  38671. this.transmuxer_.postMessage({
  38672. action: 'clearParsedMp4Captions'
  38673. });
  38674. }
  38675. };
  38676. _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
  38677. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38678. if (this.checkForAbort_(simpleSegment.requestId)) {
  38679. return;
  38680. }
  38681. var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  38682. if (!segmentInfo.hasAppendedData_) {
  38683. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  38684. return;
  38685. }
  38686. var 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
  38687. // audio/video source with a metadata track, and an alt audio with a metadata track.
  38688. // However, this probably won't happen, and if it does it can be handled then.
  38689. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  38690. addMetadata({
  38691. inbandTextTracks: this.inbandTextTracks_,
  38692. metadataArray: id3Frames,
  38693. timestampOffset: timestampOffset,
  38694. videoDuration: this.duration_()
  38695. });
  38696. };
  38697. _proto.processMetadataQueue_ = function processMetadataQueue_() {
  38698. this.metadataQueue_.id3.forEach(function (fn) {
  38699. return fn();
  38700. });
  38701. this.metadataQueue_.caption.forEach(function (fn) {
  38702. return fn();
  38703. });
  38704. this.metadataQueue_.id3 = [];
  38705. this.metadataQueue_.caption = [];
  38706. };
  38707. _proto.processCallQueue_ = function processCallQueue_() {
  38708. var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  38709. // functions may check the length of the load queue and default to pushing themselves
  38710. // back onto the queue.
  38711. this.callQueue_ = [];
  38712. callQueue.forEach(function (fun) {
  38713. return fun();
  38714. });
  38715. };
  38716. _proto.processLoadQueue_ = function processLoadQueue_() {
  38717. var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  38718. // functions may check the length of the load queue and default to pushing themselves
  38719. // back onto the queue.
  38720. this.loadQueue_ = [];
  38721. loadQueue.forEach(function (fun) {
  38722. return fun();
  38723. });
  38724. }
  38725. /**
  38726. * Determines whether the loader has enough info to load the next segment.
  38727. *
  38728. * @return {boolean}
  38729. * Whether or not the loader has enough info to load the next segment
  38730. */
  38731. ;
  38732. _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
  38733. // Since primary timing goes by video, only the audio loader potentially needs to wait
  38734. // to load.
  38735. if (this.loaderType_ !== 'audio') {
  38736. return true;
  38737. }
  38738. var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  38739. // enough info to load.
  38740. if (!segmentInfo) {
  38741. return false;
  38742. } // The first segment can and should be loaded immediately so that source buffers are
  38743. // created together (before appending). Source buffer creation uses the presence of
  38744. // audio and video data to determine whether to create audio/video source buffers, and
  38745. // uses processed (transmuxed or parsed) media to determine the types required.
  38746. if (!this.getCurrentMediaInfo_()) {
  38747. return true;
  38748. }
  38749. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  38750. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  38751. // But in practice, there are a few reasons why it is better to wait until a loader
  38752. // is ready to append that segment before requesting and downloading:
  38753. //
  38754. // 1. Because audio and main loaders cross discontinuities together, if this loader
  38755. // is waiting for the other to catch up, then instead of requesting another
  38756. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  38757. // allotted to the loader currently behind.
  38758. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  38759. // is ready to be processed or not, isolating the queueing behavior to the loader.
  38760. // 3. The audio loader bases some of its segment properties on timing information
  38761. // provided by the main loader, meaning that, if the logic for waiting on
  38762. // processing was in media-segment-request, then it would also need to know how
  38763. // to re-generate the segment information after the main loader caught up.
  38764. shouldWaitForTimelineChange({
  38765. timelineChangeController: this.timelineChangeController_,
  38766. currentTimeline: this.currentTimeline_,
  38767. segmentTimeline: segmentInfo.timeline,
  38768. loaderType: this.loaderType_,
  38769. audioDisabled: this.audioDisabled_
  38770. })) {
  38771. return false;
  38772. }
  38773. return true;
  38774. };
  38775. _proto.getCurrentMediaInfo_ = function getCurrentMediaInfo_(segmentInfo) {
  38776. if (segmentInfo === void 0) {
  38777. segmentInfo = this.pendingSegment_;
  38778. }
  38779. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  38780. };
  38781. _proto.getMediaInfo_ = function getMediaInfo_(segmentInfo) {
  38782. if (segmentInfo === void 0) {
  38783. segmentInfo = this.pendingSegment_;
  38784. }
  38785. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  38786. };
  38787. _proto.getPendingSegmentPlaylist = function getPendingSegmentPlaylist() {
  38788. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  38789. };
  38790. _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
  38791. if (!this.sourceUpdater_.ready()) {
  38792. return false;
  38793. } // If content needs to be removed or the loader is waiting on an append reattempt,
  38794. // then no additional content should be appended until the prior append is resolved.
  38795. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  38796. return false;
  38797. }
  38798. var segmentInfo = this.pendingSegment_;
  38799. var trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  38800. // we do not have information on this specific
  38801. // segment yet
  38802. if (!segmentInfo || !trackInfo) {
  38803. return false;
  38804. }
  38805. var hasAudio = trackInfo.hasAudio,
  38806. hasVideo = trackInfo.hasVideo,
  38807. isMuxed = trackInfo.isMuxed;
  38808. if (hasVideo && !segmentInfo.videoTimingInfo) {
  38809. return false;
  38810. } // muxed content only relies on video timing information for now.
  38811. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  38812. return false;
  38813. }
  38814. if (shouldWaitForTimelineChange({
  38815. timelineChangeController: this.timelineChangeController_,
  38816. currentTimeline: this.currentTimeline_,
  38817. segmentTimeline: segmentInfo.timeline,
  38818. loaderType: this.loaderType_,
  38819. audioDisabled: this.audioDisabled_
  38820. })) {
  38821. return false;
  38822. }
  38823. return true;
  38824. };
  38825. _proto.handleData_ = function handleData_(simpleSegment, result) {
  38826. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  38827. if (this.checkForAbort_(simpleSegment.requestId)) {
  38828. return;
  38829. } // If there's anything in the call queue, then this data came later and should be
  38830. // executed after the calls currently queued.
  38831. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  38832. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  38833. return;
  38834. }
  38835. var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  38836. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  38837. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  38838. // logic may change behavior depending on the state, and changing state too early may
  38839. // inflate our estimates of bandwidth. In the future this should be re-examined to
  38840. // note more granular states.
  38841. // don't process and append data if the mediaSource is closed
  38842. if (this.mediaSource_.readyState === 'closed') {
  38843. return;
  38844. } // if this request included an initialization segment, save that data
  38845. // to the initSegment cache
  38846. if (simpleSegment.map) {
  38847. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  38848. segmentInfo.segment.map = simpleSegment.map;
  38849. } // if this request included a segment key, save that data in the cache
  38850. if (simpleSegment.key) {
  38851. this.segmentKey(simpleSegment.key, true);
  38852. }
  38853. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  38854. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  38855. if (segmentInfo.isFmp4) {
  38856. this.trigger('fmp4');
  38857. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  38858. } else {
  38859. var trackInfo = this.getCurrentMediaInfo_();
  38860. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  38861. var firstVideoFrameTimeForData;
  38862. if (useVideoTimingInfo) {
  38863. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  38864. } // Segment loader knows more about segment timing than the transmuxer (in certain
  38865. // aspects), so make any changes required for a more accurate start time.
  38866. // Don't set the end time yet, as the segment may not be finished processing.
  38867. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  38868. currentStart: segmentInfo.timingInfo.start,
  38869. playlist: segmentInfo.playlist,
  38870. mediaIndex: segmentInfo.mediaIndex,
  38871. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  38872. useVideoTimingInfo: useVideoTimingInfo,
  38873. firstVideoFrameTimeForData: firstVideoFrameTimeForData,
  38874. videoTimingInfo: segmentInfo.videoTimingInfo,
  38875. audioTimingInfo: segmentInfo.audioTimingInfo
  38876. });
  38877. } // Init segments for audio and video only need to be appended in certain cases. Now
  38878. // that data is about to be appended, we can check the final cases to determine
  38879. // whether we should append an init segment.
  38880. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  38881. // as we use the start of the segment to offset the best guess (playlist provided)
  38882. // timestamp offset.
  38883. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  38884. // be appended or not.
  38885. if (segmentInfo.isSyncRequest) {
  38886. // first save/update our timing info for this segment.
  38887. // this is what allows us to choose an accurate segment
  38888. // and the main reason we make a sync request.
  38889. this.updateTimingInfoEnd_(segmentInfo);
  38890. this.syncController_.saveSegmentTimingInfo({
  38891. segmentInfo: segmentInfo,
  38892. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  38893. });
  38894. var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  38895. // after taking into account its timing info, do not append it.
  38896. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  38897. this.logger_('sync segment was incorrect, not appending');
  38898. return;
  38899. } // otherwise append it like any other segment as our guess was correct.
  38900. this.logger_('sync segment was correct, appending');
  38901. } // Save some state so that in the future anything waiting on first append (and/or
  38902. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  38903. // we need some notion of whether the timestamp offset or other relevant information
  38904. // has had a chance to be set.
  38905. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  38906. this.processMetadataQueue_();
  38907. this.appendData_(segmentInfo, result);
  38908. };
  38909. _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
  38910. // alt audio doesn't manage timestamp offset
  38911. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
  38912. // segment for each chunk
  38913. !segmentInfo.changedTimestampOffset) {
  38914. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  38915. // append init segments
  38916. this.appendInitSegment_ = {
  38917. audio: true,
  38918. video: true
  38919. };
  38920. }
  38921. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  38922. // make sure we append init segment on playlist changes, in case the media config
  38923. // changed
  38924. this.appendInitSegment_[type] = true;
  38925. }
  38926. };
  38927. _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
  38928. var type = _ref4.type,
  38929. initSegment = _ref4.initSegment,
  38930. map = _ref4.map,
  38931. playlist = _ref4.playlist; // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  38932. // (Section 3) required to parse the applicable Media Segments. It applies to every
  38933. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  38934. // or until the end of the playlist."
  38935. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  38936. if (map) {
  38937. var id = initSegmentId(map);
  38938. if (this.activeInitSegmentId_ === id) {
  38939. // don't need to re-append the init segment if the ID matches
  38940. return null;
  38941. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  38942. // obtained) init segment
  38943. //
  38944. // this also caches the init segment for later use
  38945. initSegment = this.initSegmentForMap(map, true).bytes;
  38946. this.activeInitSegmentId_ = id;
  38947. } // We used to always prepend init segments for video, however, that shouldn't be
  38948. // necessary. Instead, we should only append on changes, similar to what we've always
  38949. // done for audio. This is more important (though may not be that important) for
  38950. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  38951. // appends.
  38952. if (initSegment && this.appendInitSegment_[type]) {
  38953. // Make sure we track the playlist that we last used for the init segment, so that
  38954. // we can re-append the init segment in the event that we get data from a new
  38955. // playlist. Discontinuities and track changes are handled in other sections.
  38956. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  38957. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  38958. // we are appending the muxer init segment
  38959. this.activeInitSegmentId_ = null;
  38960. return initSegment;
  38961. }
  38962. return null;
  38963. };
  38964. _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
  38965. var _this3 = this;
  38966. var segmentInfo = _ref5.segmentInfo,
  38967. type = _ref5.type,
  38968. bytes = _ref5.bytes;
  38969. var audioBuffered = this.sourceUpdater_.audioBuffered();
  38970. var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  38971. // should be cleared out during the buffer removals. However, log in case it helps
  38972. // debug.
  38973. if (audioBuffered.length > 1) {
  38974. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  38975. }
  38976. if (videoBuffered.length > 1) {
  38977. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  38978. }
  38979. var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  38980. var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  38981. var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  38982. var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  38983. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  38984. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  38985. // allow for appends of segments this size). In the future, it may be possible to
  38986. // split up the segment and append in pieces, but for now, error out this playlist
  38987. // in an attempt to switch to a more manageable rendition.
  38988. 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(', ') + ", "));
  38989. this.error({
  38990. message: 'Quota exceeded error with append of a single segment of content',
  38991. excludeUntil: Infinity
  38992. });
  38993. this.trigger('error');
  38994. return;
  38995. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  38996. // that the segment-loader should block on future events until this one is handled, so
  38997. // that it doesn't keep moving onto further segments. Adding the call to the call
  38998. // queue will prevent further appends until waitingOnRemove_ and
  38999. // quotaExceededErrorRetryTimeout_ are cleared.
  39000. //
  39001. // Note that this will only block the current loader. In the case of demuxed content,
  39002. // the other load may keep filling as fast as possible. In practice, this should be
  39003. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  39004. // source buffer, or video fills without enough room for audio to append (and without
  39005. // the availability of clearing out seconds of back buffer to make room for audio).
  39006. // But it might still be good to handle this case in the future as a TODO.
  39007. this.waitingOnRemove_ = true;
  39008. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  39009. segmentInfo: segmentInfo,
  39010. type: type,
  39011. bytes: bytes
  39012. }));
  39013. var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  39014. // before retrying.
  39015. var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  39016. this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
  39017. this.remove(0, timeToRemoveUntil, function () {
  39018. _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
  39019. _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  39020. // attempts (since we can't clear less than the minimum)
  39021. _this3.quotaExceededErrorRetryTimeout_ = window__default['default'].setTimeout(function () {
  39022. _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  39023. _this3.quotaExceededErrorRetryTimeout_ = null;
  39024. _this3.processCallQueue_();
  39025. }, MIN_BACK_BUFFER * 1000);
  39026. }, true);
  39027. };
  39028. _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
  39029. var segmentInfo = _ref6.segmentInfo,
  39030. type = _ref6.type,
  39031. bytes = _ref6.bytes; // if there's no error, nothing to do
  39032. if (!error) {
  39033. return;
  39034. }
  39035. if (error.code === QUOTA_EXCEEDED_ERR) {
  39036. this.handleQuotaExceededError_({
  39037. segmentInfo: segmentInfo,
  39038. type: type,
  39039. bytes: bytes
  39040. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  39041. // to trigger an append error.
  39042. return;
  39043. }
  39044. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  39045. 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.
  39046. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  39047. //
  39048. // Trigger a special error so that it can be handled separately from normal,
  39049. // recoverable errors.
  39050. this.trigger('appenderror');
  39051. };
  39052. _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
  39053. var segmentInfo = _ref7.segmentInfo,
  39054. type = _ref7.type,
  39055. initSegment = _ref7.initSegment,
  39056. data = _ref7.data,
  39057. bytes = _ref7.bytes; // If this is a re-append, bytes were already created and don't need to be recreated
  39058. if (!bytes) {
  39059. var segments = [data];
  39060. var byteLength = data.byteLength;
  39061. if (initSegment) {
  39062. // if the media initialization segment is changing, append it before the content
  39063. // segment
  39064. segments.unshift(initSegment);
  39065. byteLength += initSegment.byteLength;
  39066. } // Technically we should be OK appending the init segment separately, however, we
  39067. // haven't yet tested that, and prepending is how we have always done things.
  39068. bytes = concatSegments({
  39069. bytes: byteLength,
  39070. segments: segments
  39071. });
  39072. }
  39073. this.sourceUpdater_.appendBuffer({
  39074. segmentInfo: segmentInfo,
  39075. type: type,
  39076. bytes: bytes
  39077. }, this.handleAppendError_.bind(this, {
  39078. segmentInfo: segmentInfo,
  39079. type: type,
  39080. bytes: bytes
  39081. }));
  39082. };
  39083. _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  39084. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  39085. return;
  39086. }
  39087. var segment = this.pendingSegment_.segment;
  39088. var timingInfoProperty = type + "TimingInfo";
  39089. if (!segment[timingInfoProperty]) {
  39090. segment[timingInfoProperty] = {};
  39091. }
  39092. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  39093. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  39094. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  39095. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  39096. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  39097. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  39098. };
  39099. _proto.appendData_ = function appendData_(segmentInfo, result) {
  39100. var type = result.type,
  39101. data = result.data;
  39102. if (!data || !data.byteLength) {
  39103. return;
  39104. }
  39105. if (type === 'audio' && this.audioDisabled_) {
  39106. return;
  39107. }
  39108. var initSegment = this.getInitSegmentAndUpdateState_({
  39109. type: type,
  39110. initSegment: result.initSegment,
  39111. playlist: segmentInfo.playlist,
  39112. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  39113. });
  39114. this.appendToSourceBuffer_({
  39115. segmentInfo: segmentInfo,
  39116. type: type,
  39117. initSegment: initSegment,
  39118. data: data
  39119. });
  39120. }
  39121. /**
  39122. * load a specific segment from a request into the buffer
  39123. *
  39124. * @private
  39125. */
  39126. ;
  39127. _proto.loadSegment_ = function loadSegment_(segmentInfo) {
  39128. var _this4 = this;
  39129. this.state = 'WAITING';
  39130. this.pendingSegment_ = segmentInfo;
  39131. this.trimBackBuffer_(segmentInfo);
  39132. if (typeof segmentInfo.timestampOffset === 'number') {
  39133. if (this.transmuxer_) {
  39134. this.transmuxer_.postMessage({
  39135. action: 'clearAllMp4Captions'
  39136. });
  39137. }
  39138. }
  39139. if (!this.hasEnoughInfoToLoad_()) {
  39140. this.loadQueue_.push(function () {
  39141. // regenerate the audioAppendStart, timestampOffset, etc as they
  39142. // may have changed since this function was added to the queue.
  39143. var options = _extends__default['default']({}, segmentInfo, {
  39144. forceTimestampOffset: true
  39145. });
  39146. _extends__default['default'](segmentInfo, _this4.generateSegmentInfo_(options));
  39147. _this4.isPendingTimestampOffset_ = false;
  39148. _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
  39149. });
  39150. return;
  39151. }
  39152. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  39153. };
  39154. _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
  39155. var _this5 = this; // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  39156. // the transmuxer still needs to be updated before then.
  39157. //
  39158. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  39159. // offset must be passed to the transmuxer for stream correcting adjustments.
  39160. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  39161. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  39162. segmentInfo.gopsToAlignWith = [];
  39163. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  39164. this.transmuxer_.postMessage({
  39165. action: 'reset'
  39166. });
  39167. this.transmuxer_.postMessage({
  39168. action: 'setTimestampOffset',
  39169. timestampOffset: segmentInfo.timestampOffset
  39170. });
  39171. }
  39172. var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  39173. var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  39174. var isWalkingForward = this.mediaIndex !== null;
  39175. var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  39176. // the first timeline
  39177. segmentInfo.timeline > 0;
  39178. var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  39179. 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),
  39180. // then this init segment has never been seen before and should be appended.
  39181. //
  39182. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  39183. // both to true and leave the decision of whether to append the init segment to append time.
  39184. if (simpleSegment.map && !simpleSegment.map.bytes) {
  39185. this.logger_('going to request init segment.');
  39186. this.appendInitSegment_ = {
  39187. video: true,
  39188. audio: true
  39189. };
  39190. }
  39191. segmentInfo.abortRequests = mediaSegmentRequest({
  39192. xhr: this.vhs_.xhr,
  39193. xhrOptions: this.xhrOptions_,
  39194. decryptionWorker: this.decrypter_,
  39195. segment: simpleSegment,
  39196. abortFn: this.handleAbort_.bind(this, segmentInfo),
  39197. progressFn: this.handleProgress_.bind(this),
  39198. trackInfoFn: this.handleTrackInfo_.bind(this),
  39199. timingInfoFn: this.handleTimingInfo_.bind(this),
  39200. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  39201. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  39202. captionsFn: this.handleCaptions_.bind(this),
  39203. isEndOfTimeline: isEndOfTimeline,
  39204. endedTimelineFn: function endedTimelineFn() {
  39205. _this5.logger_('received endedtimeline callback');
  39206. },
  39207. id3Fn: this.handleId3_.bind(this),
  39208. dataFn: this.handleData_.bind(this),
  39209. doneFn: this.segmentRequestFinished_.bind(this),
  39210. onTransmuxerLog: function onTransmuxerLog(_ref8) {
  39211. var message = _ref8.message,
  39212. level = _ref8.level,
  39213. stream = _ref8.stream;
  39214. _this5.logger_(segmentInfoString(segmentInfo) + " logged from transmuxer stream " + stream + " as a " + level + ": " + message);
  39215. }
  39216. });
  39217. }
  39218. /**
  39219. * trim the back buffer so that we don't have too much data
  39220. * in the source buffer
  39221. *
  39222. * @private
  39223. *
  39224. * @param {Object} segmentInfo - the current segment
  39225. */
  39226. ;
  39227. _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
  39228. var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  39229. // buffer and a very conservative "garbage collector"
  39230. // We manually clear out the old buffer to ensure
  39231. // we don't trigger the QuotaExceeded error
  39232. // on the source buffer during subsequent appends
  39233. if (removeToTime > 0) {
  39234. this.remove(0, removeToTime);
  39235. }
  39236. }
  39237. /**
  39238. * created a simplified copy of the segment object with just the
  39239. * information necessary to perform the XHR and decryption
  39240. *
  39241. * @private
  39242. *
  39243. * @param {Object} segmentInfo - the current segment
  39244. * @return {Object} a simplified segment object copy
  39245. */
  39246. ;
  39247. _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
  39248. var segment = segmentInfo.segment;
  39249. var part = segmentInfo.part;
  39250. var simpleSegment = {
  39251. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  39252. byterange: part ? part.byterange : segment.byterange,
  39253. requestId: segmentInfo.requestId,
  39254. transmuxer: segmentInfo.transmuxer,
  39255. audioAppendStart: segmentInfo.audioAppendStart,
  39256. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  39257. part: segmentInfo.part
  39258. };
  39259. var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  39260. if (previousSegment && previousSegment.timeline === segment.timeline) {
  39261. // The baseStartTime of a segment is used to handle rollover when probing the TS
  39262. // segment to retrieve timing information. Since the probe only looks at the media's
  39263. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  39264. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  39265. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  39266. // seconds of media time, so should be used here. The previous segment is used since
  39267. // the end of the previous segment should represent the beginning of the current
  39268. // segment, so long as they are on the same timeline.
  39269. if (previousSegment.videoTimingInfo) {
  39270. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  39271. } else if (previousSegment.audioTimingInfo) {
  39272. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  39273. }
  39274. }
  39275. if (segment.key) {
  39276. // if the media sequence is greater than 2^32, the IV will be incorrect
  39277. // assuming 10s segments, that would be about 1300 years
  39278. var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  39279. simpleSegment.key = this.segmentKey(segment.key);
  39280. simpleSegment.key.iv = iv;
  39281. }
  39282. if (segment.map) {
  39283. simpleSegment.map = this.initSegmentForMap(segment.map);
  39284. }
  39285. return simpleSegment;
  39286. };
  39287. _proto.saveTransferStats_ = function saveTransferStats_(stats) {
  39288. // every request counts as a media request even if it has been aborted
  39289. // or canceled due to a timeout
  39290. this.mediaRequests += 1;
  39291. if (stats) {
  39292. this.mediaBytesTransferred += stats.bytesReceived;
  39293. this.mediaTransferDuration += stats.roundTripTime;
  39294. }
  39295. };
  39296. _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
  39297. // byteLength will be used for throughput, and should be based on bytes receieved,
  39298. // which we only know at the end of the request and should reflect total bytes
  39299. // downloaded rather than just bytes processed from components of the segment
  39300. this.pendingSegment_.byteLength = stats.bytesReceived;
  39301. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39302. this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
  39303. return;
  39304. }
  39305. this.bandwidth = stats.bandwidth;
  39306. this.roundTrip = stats.roundTripTime;
  39307. };
  39308. _proto.handleTimeout_ = function handleTimeout_() {
  39309. // although the VTT segment loader bandwidth isn't really used, it's good to
  39310. // maintain functinality between segment loaders
  39311. this.mediaRequestsTimedout += 1;
  39312. this.bandwidth = 1;
  39313. this.roundTrip = NaN;
  39314. this.trigger('bandwidthupdate');
  39315. this.trigger('timeout');
  39316. }
  39317. /**
  39318. * Handle the callback from the segmentRequest function and set the
  39319. * associated SegmentLoader state and errors if necessary
  39320. *
  39321. * @private
  39322. */
  39323. ;
  39324. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  39325. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  39326. // check the call queue directly since this function doesn't need to deal with any
  39327. // data, and can continue even if the source buffers are not set up and we didn't get
  39328. // any data from the segment
  39329. if (this.callQueue_.length) {
  39330. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  39331. return;
  39332. }
  39333. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  39334. if (!this.pendingSegment_) {
  39335. return;
  39336. } // the request was aborted and the SegmentLoader has already started
  39337. // another request. this can happen when the timeout for an aborted
  39338. // request triggers due to a limitation in the XHR library
  39339. // do not count this as any sort of request or we risk double-counting
  39340. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  39341. return;
  39342. } // an error occurred from the active pendingSegment_ so reset everything
  39343. if (error) {
  39344. this.pendingSegment_ = null;
  39345. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  39346. if (error.code === REQUEST_ERRORS.ABORTED) {
  39347. return;
  39348. }
  39349. this.pause(); // the error is really just that at least one of the requests timed-out
  39350. // set the bandwidth to a very low value and trigger an ABR switch to
  39351. // take emergency action
  39352. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  39353. this.handleTimeout_();
  39354. return;
  39355. } // if control-flow has arrived here, then the error is real
  39356. // emit an error event to blacklist the current playlist
  39357. this.mediaRequestsErrored += 1;
  39358. this.error(error);
  39359. this.trigger('error');
  39360. return;
  39361. }
  39362. var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  39363. // generated for ABR purposes
  39364. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  39365. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  39366. if (result.gopInfo) {
  39367. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  39368. } // Although we may have already started appending on progress, we shouldn't switch the
  39369. // state away from loading until we are officially done loading the segment data.
  39370. this.state = 'APPENDING'; // used for testing
  39371. this.trigger('appending');
  39372. this.waitForAppendsToComplete_(segmentInfo);
  39373. };
  39374. _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
  39375. var timelineMapping = this.syncController_.mappingForTimeline(timeline);
  39376. if (timelineMapping !== null) {
  39377. this.timeMapping_ = timelineMapping;
  39378. }
  39379. };
  39380. _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
  39381. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  39382. this.mediaSecondsLoaded += segment.end - segment.start;
  39383. } else {
  39384. this.mediaSecondsLoaded += segment.duration;
  39385. }
  39386. };
  39387. _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  39388. if (timestampOffset === null) {
  39389. return false;
  39390. } // note that we're potentially using the same timestamp offset for both video and
  39391. // audio
  39392. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39393. return true;
  39394. }
  39395. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39396. return true;
  39397. }
  39398. return false;
  39399. };
  39400. _proto.trueSegmentStart_ = function trueSegmentStart_(_ref9) {
  39401. var currentStart = _ref9.currentStart,
  39402. playlist = _ref9.playlist,
  39403. mediaIndex = _ref9.mediaIndex,
  39404. firstVideoFrameTimeForData = _ref9.firstVideoFrameTimeForData,
  39405. currentVideoTimestampOffset = _ref9.currentVideoTimestampOffset,
  39406. useVideoTimingInfo = _ref9.useVideoTimingInfo,
  39407. videoTimingInfo = _ref9.videoTimingInfo,
  39408. audioTimingInfo = _ref9.audioTimingInfo;
  39409. if (typeof currentStart !== 'undefined') {
  39410. // if start was set once, keep using it
  39411. return currentStart;
  39412. }
  39413. if (!useVideoTimingInfo) {
  39414. return audioTimingInfo.start;
  39415. }
  39416. var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  39417. // within that segment. Since the transmuxer maintains a cache of incomplete data
  39418. // from and/or the last frame seen, the start time may reflect a frame that starts
  39419. // in the previous segment. Check for that case and ensure the start time is
  39420. // accurate for the segment.
  39421. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  39422. return firstVideoFrameTimeForData;
  39423. }
  39424. return videoTimingInfo.start;
  39425. };
  39426. _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
  39427. var trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  39428. if (!trackInfo) {
  39429. this.error({
  39430. message: 'No starting media returned, likely due to an unsupported media format.',
  39431. blacklistDuration: Infinity
  39432. });
  39433. this.trigger('error');
  39434. return;
  39435. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  39436. // on each queue this loader is responsible for to ensure that the appends are
  39437. // complete.
  39438. var hasAudio = trackInfo.hasAudio,
  39439. hasVideo = trackInfo.hasVideo,
  39440. isMuxed = trackInfo.isMuxed;
  39441. var waitForVideo = this.loaderType_ === 'main' && hasVideo;
  39442. var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  39443. segmentInfo.waitingOnAppends = 0; // segments with no data
  39444. if (!segmentInfo.hasAppendedData_) {
  39445. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  39446. // When there's no audio or video data in the segment, there's no audio or video
  39447. // timing information.
  39448. //
  39449. // If there's no audio or video timing information, then the timestamp offset
  39450. // can't be adjusted to the appropriate value for the transmuxer and source
  39451. // buffers.
  39452. //
  39453. // Therefore, the next segment should be used to set the timestamp offset.
  39454. this.isPendingTimestampOffset_ = true;
  39455. } // override settings for metadata only segments
  39456. segmentInfo.timingInfo = {
  39457. start: 0
  39458. };
  39459. segmentInfo.waitingOnAppends++;
  39460. if (!this.isPendingTimestampOffset_) {
  39461. // update the timestampoffset
  39462. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  39463. // no video/audio data.
  39464. this.processMetadataQueue_();
  39465. } // append is "done" instantly with no data.
  39466. this.checkAppendsDone_(segmentInfo);
  39467. return;
  39468. } // Since source updater could call back synchronously, do the increments first.
  39469. if (waitForVideo) {
  39470. segmentInfo.waitingOnAppends++;
  39471. }
  39472. if (waitForAudio) {
  39473. segmentInfo.waitingOnAppends++;
  39474. }
  39475. if (waitForVideo) {
  39476. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39477. }
  39478. if (waitForAudio) {
  39479. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  39480. }
  39481. };
  39482. _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
  39483. if (this.checkForAbort_(segmentInfo.requestId)) {
  39484. return;
  39485. }
  39486. segmentInfo.waitingOnAppends--;
  39487. if (segmentInfo.waitingOnAppends === 0) {
  39488. this.handleAppendsDone_();
  39489. }
  39490. };
  39491. _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
  39492. var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  39493. if (illegalMediaSwitchError) {
  39494. this.error({
  39495. message: illegalMediaSwitchError,
  39496. blacklistDuration: Infinity
  39497. });
  39498. this.trigger('error');
  39499. return true;
  39500. }
  39501. return false;
  39502. };
  39503. _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
  39504. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  39505. // priority, timing-wise, so we must wait
  39506. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  39507. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  39508. this.loaderType_ !== 'main') {
  39509. return;
  39510. }
  39511. var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  39512. // the timing info here comes from video. In the event that the audio is longer than
  39513. // the video, this will trim the start of the audio.
  39514. // This also trims any offset from 0 at the beginning of the media
  39515. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  39516. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  39517. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  39518. timingInfo: segmentInfo.timingInfo
  39519. }); // In the event that there are part segment downloads, each will try to update the
  39520. // timestamp offset. Retaining this bit of state prevents us from updating in the
  39521. // future (within the same segment), however, there may be a better way to handle it.
  39522. segmentInfo.changedTimestampOffset = true;
  39523. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  39524. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  39525. didChange = true;
  39526. }
  39527. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  39528. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  39529. didChange = true;
  39530. }
  39531. if (didChange) {
  39532. this.trigger('timestampoffset');
  39533. }
  39534. };
  39535. _proto.getSegmentStartTimeForTimestampOffsetCalculation_ = function getSegmentStartTimeForTimestampOffsetCalculation_(_ref10) {
  39536. var videoTimingInfo = _ref10.videoTimingInfo,
  39537. audioTimingInfo = _ref10.audioTimingInfo,
  39538. timingInfo = _ref10.timingInfo;
  39539. if (!this.useDtsForTimestampOffset_) {
  39540. return timingInfo.start;
  39541. }
  39542. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  39543. return videoTimingInfo.transmuxedDecodeStart;
  39544. } // handle audio only
  39545. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  39546. return audioTimingInfo.transmuxedDecodeStart;
  39547. } // handle content not transmuxed (e.g., MP4)
  39548. return timingInfo.start;
  39549. };
  39550. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
  39551. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  39552. var trackInfo = this.getMediaInfo_();
  39553. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  39554. var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  39555. if (!prioritizedTimingInfo) {
  39556. return;
  39557. }
  39558. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  39559. // current example is the case of fmp4), so use the rough duration to calculate an
  39560. // end time.
  39561. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  39562. }
  39563. /**
  39564. * callback to run when appendBuffer is finished. detects if we are
  39565. * in a good state to do things with the data we got, or if we need
  39566. * to wait for more
  39567. *
  39568. * @private
  39569. */
  39570. ;
  39571. _proto.handleAppendsDone_ = function handleAppendsDone_() {
  39572. // appendsdone can cause an abort
  39573. if (this.pendingSegment_) {
  39574. this.trigger('appendsdone');
  39575. }
  39576. if (!this.pendingSegment_) {
  39577. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  39578. // all appending cases?
  39579. if (!this.paused()) {
  39580. this.monitorBuffer_();
  39581. }
  39582. return;
  39583. }
  39584. var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  39585. // best to wait until all appends are done so we're sure that the primary media is
  39586. // finished (and we have its end time).
  39587. this.updateTimingInfoEnd_(segmentInfo);
  39588. if (this.shouldSaveSegmentTimingInfo_) {
  39589. // Timeline mappings should only be saved for the main loader. This is for multiple
  39590. // reasons:
  39591. //
  39592. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  39593. // and the main loader try to save the timeline mapping, whichever comes later
  39594. // will overwrite the first. In theory this is OK, as the mappings should be the
  39595. // same, however, it breaks for (2)
  39596. // 2) In the event of a live stream, the initial live point will make for a somewhat
  39597. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  39598. // the mapping will be off for one of the streams, dependent on which one was
  39599. // first saved (see (1)).
  39600. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  39601. //
  39602. // Since the audio loader will wait for the main loader to load the first segment,
  39603. // the main loader will save the first timeline mapping, and ensure that there won't
  39604. // be a case where audio loads two segments without saving a mapping (thus leading
  39605. // to missing segment timing info).
  39606. this.syncController_.saveSegmentTimingInfo({
  39607. segmentInfo: segmentInfo,
  39608. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  39609. });
  39610. }
  39611. var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  39612. if (segmentDurationMessage) {
  39613. if (segmentDurationMessage.severity === 'warn') {
  39614. videojs.log.warn(segmentDurationMessage.message);
  39615. } else {
  39616. this.logger_(segmentDurationMessage.message);
  39617. }
  39618. }
  39619. this.recordThroughput_(segmentInfo);
  39620. this.pendingSegment_ = null;
  39621. this.state = 'READY';
  39622. if (segmentInfo.isSyncRequest) {
  39623. this.trigger('syncinfoupdate'); // if the sync request was not appended
  39624. // then it was not the correct segment.
  39625. // throw it away and use the data it gave us
  39626. // to get the correct one.
  39627. if (!segmentInfo.hasAppendedData_) {
  39628. this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
  39629. return;
  39630. }
  39631. }
  39632. this.logger_("Appended " + segmentInfoString(segmentInfo));
  39633. this.addSegmentMetadataCue_(segmentInfo);
  39634. this.fetchAtBuffer_ = true;
  39635. if (this.currentTimeline_ !== segmentInfo.timeline) {
  39636. this.timelineChangeController_.lastTimelineChange({
  39637. type: this.loaderType_,
  39638. from: this.currentTimeline_,
  39639. to: segmentInfo.timeline
  39640. }); // If audio is not disabled, the main segment loader is responsible for updating
  39641. // the audio timeline as well. If the content is video only, this won't have any
  39642. // impact.
  39643. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  39644. this.timelineChangeController_.lastTimelineChange({
  39645. type: 'audio',
  39646. from: this.currentTimeline_,
  39647. to: segmentInfo.timeline
  39648. });
  39649. }
  39650. }
  39651. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  39652. // the following conditional otherwise it may consider this a bad "guess"
  39653. // and attempt to resync when the post-update seekable window and live
  39654. // point would mean that this was the perfect segment to fetch
  39655. this.trigger('syncinfoupdate');
  39656. var segment = segmentInfo.segment;
  39657. var part = segmentInfo.part;
  39658. var badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  39659. var 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
  39660. // the currentTime_ that means that our conservative guess was too conservative.
  39661. // In that case, reset the loader state so that we try to use any information gained
  39662. // from the previous request to create a new, more accurate, sync-point.
  39663. if (badSegmentGuess || badPartGuess) {
  39664. this.logger_("bad " + (badSegmentGuess ? 'segment' : 'part') + " " + segmentInfoString(segmentInfo));
  39665. this.resetEverything();
  39666. return;
  39667. }
  39668. var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  39669. // and conservatively guess
  39670. if (isWalkingForward) {
  39671. this.trigger('bandwidthupdate');
  39672. }
  39673. this.trigger('progress');
  39674. this.mediaIndex = segmentInfo.mediaIndex;
  39675. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  39676. // buffer, end the stream. this ensures the "ended" event will
  39677. // fire if playback reaches that point.
  39678. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  39679. this.endOfStream();
  39680. } // used for testing
  39681. this.trigger('appended');
  39682. if (segmentInfo.hasAppendedData_) {
  39683. this.mediaAppends++;
  39684. }
  39685. if (!this.paused()) {
  39686. this.monitorBuffer_();
  39687. }
  39688. }
  39689. /**
  39690. * Records the current throughput of the decrypt, transmux, and append
  39691. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  39692. * moving average of the throughput. `throughput.count` is the number of
  39693. * data points in the average.
  39694. *
  39695. * @private
  39696. * @param {Object} segmentInfo the object returned by loadSegment
  39697. */
  39698. ;
  39699. _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
  39700. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  39701. 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));
  39702. return;
  39703. }
  39704. var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  39705. // by zero in the case where the throughput is ridiculously high
  39706. var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  39707. var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  39708. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  39709. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  39710. }
  39711. /**
  39712. * Adds a cue to the segment-metadata track with some metadata information about the
  39713. * segment
  39714. *
  39715. * @private
  39716. * @param {Object} segmentInfo
  39717. * the object returned by loadSegment
  39718. * @method addSegmentMetadataCue_
  39719. */
  39720. ;
  39721. _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
  39722. if (!this.segmentMetadataTrack_) {
  39723. return;
  39724. }
  39725. var segment = segmentInfo.segment;
  39726. var start = segment.start;
  39727. var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  39728. if (!finite(start) || !finite(end)) {
  39729. return;
  39730. }
  39731. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  39732. var Cue = window__default['default'].WebKitDataCue || window__default['default'].VTTCue;
  39733. var value = {
  39734. custom: segment.custom,
  39735. dateTimeObject: segment.dateTimeObject,
  39736. dateTimeString: segment.dateTimeString,
  39737. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  39738. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  39739. codecs: segmentInfo.playlist.attributes.CODECS,
  39740. byteLength: segmentInfo.byteLength,
  39741. uri: segmentInfo.uri,
  39742. timeline: segmentInfo.timeline,
  39743. playlist: segmentInfo.playlist.id,
  39744. start: start,
  39745. end: end
  39746. };
  39747. var data = JSON.stringify(value);
  39748. var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  39749. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  39750. cue.value = value;
  39751. this.segmentMetadataTrack_.addCue(cue);
  39752. };
  39753. return SegmentLoader;
  39754. }(videojs.EventTarget);
  39755. function noop() {}
  39756. var toTitleCase = function toTitleCase(string) {
  39757. if (typeof string !== 'string') {
  39758. return string;
  39759. }
  39760. return string.replace(/./, function (w) {
  39761. return w.toUpperCase();
  39762. });
  39763. };
  39764. var bufferTypes = ['video', 'audio'];
  39765. var _updating = function updating(type, sourceUpdater) {
  39766. var sourceBuffer = sourceUpdater[type + "Buffer"];
  39767. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  39768. };
  39769. var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
  39770. for (var i = 0; i < queue.length; i++) {
  39771. var queueEntry = queue[i];
  39772. if (queueEntry.type === 'mediaSource') {
  39773. // If the next entry is a media source entry (uses multiple source buffers), block
  39774. // processing to allow it to go through first.
  39775. return null;
  39776. }
  39777. if (queueEntry.type === type) {
  39778. return i;
  39779. }
  39780. }
  39781. return null;
  39782. };
  39783. var shiftQueue = function shiftQueue(type, sourceUpdater) {
  39784. if (sourceUpdater.queue.length === 0) {
  39785. return;
  39786. }
  39787. var queueIndex = 0;
  39788. var queueEntry = sourceUpdater.queue[queueIndex];
  39789. if (queueEntry.type === 'mediaSource') {
  39790. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  39791. sourceUpdater.queue.shift();
  39792. queueEntry.action(sourceUpdater);
  39793. if (queueEntry.doneFn) {
  39794. queueEntry.doneFn();
  39795. } // Only specific source buffer actions must wait for async updateend events. Media
  39796. // Source actions process synchronously. Therefore, both audio and video source
  39797. // buffers are now clear to process the next queue entries.
  39798. shiftQueue('audio', sourceUpdater);
  39799. shiftQueue('video', sourceUpdater);
  39800. } // Media Source actions require both source buffers, so if the media source action
  39801. // couldn't process yet (because one or both source buffers are busy), block other
  39802. // queue actions until both are available and the media source action can process.
  39803. return;
  39804. }
  39805. if (type === 'mediaSource') {
  39806. // If the queue was shifted by a media source action (this happens when pushing a
  39807. // media source action onto the queue), then it wasn't from an updateend event from an
  39808. // audio or video source buffer, so there's no change from previous state, and no
  39809. // processing should be done.
  39810. return;
  39811. } // Media source queue entries don't need to consider whether the source updater is
  39812. // started (i.e., source buffers are created) as they don't need the source buffers, but
  39813. // source buffer queue entries do.
  39814. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
  39815. return;
  39816. }
  39817. if (queueEntry.type !== type) {
  39818. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  39819. if (queueIndex === null) {
  39820. // Either there's no queue entry that uses this source buffer type in the queue, or
  39821. // there's a media source queue entry before the next entry of this type, in which
  39822. // case wait for that action to process first.
  39823. return;
  39824. }
  39825. queueEntry = sourceUpdater.queue[queueIndex];
  39826. }
  39827. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  39828. //
  39829. // The queue pending operation must be set before the action is performed in the event
  39830. // that the action results in a synchronous event that is acted upon. For instance, if
  39831. // an exception is thrown that can be handled, it's possible that new actions will be
  39832. // appended to an empty queue and immediately executed, but would not have the correct
  39833. // pending information if this property was set after the action was performed.
  39834. sourceUpdater.queuePending[type] = queueEntry;
  39835. queueEntry.action(type, sourceUpdater);
  39836. if (!queueEntry.doneFn) {
  39837. // synchronous operation, process next entry
  39838. sourceUpdater.queuePending[type] = null;
  39839. shiftQueue(type, sourceUpdater);
  39840. return;
  39841. }
  39842. };
  39843. var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
  39844. var buffer = sourceUpdater[type + "Buffer"];
  39845. var titleType = toTitleCase(type);
  39846. if (!buffer) {
  39847. return;
  39848. }
  39849. buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  39850. buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  39851. sourceUpdater.codecs[type] = null;
  39852. sourceUpdater[type + "Buffer"] = null;
  39853. };
  39854. var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
  39855. return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  39856. };
  39857. var actions = {
  39858. appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
  39859. return function (type, sourceUpdater) {
  39860. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  39861. // or the media source does not contain this source buffer.
  39862. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39863. return;
  39864. }
  39865. sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
  39866. try {
  39867. sourceBuffer.appendBuffer(bytes);
  39868. } catch (e) {
  39869. sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
  39870. sourceUpdater.queuePending[type] = null;
  39871. onError(e);
  39872. }
  39873. };
  39874. },
  39875. remove: function remove(start, end) {
  39876. return function (type, sourceUpdater) {
  39877. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  39878. // or the media source does not contain this source buffer.
  39879. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39880. return;
  39881. }
  39882. sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
  39883. try {
  39884. sourceBuffer.remove(start, end);
  39885. } catch (e) {
  39886. sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
  39887. }
  39888. };
  39889. },
  39890. timestampOffset: function timestampOffset(offset) {
  39891. return function (type, sourceUpdater) {
  39892. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  39893. // or the media source does not contain this source buffer.
  39894. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39895. return;
  39896. }
  39897. sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
  39898. sourceBuffer.timestampOffset = offset;
  39899. };
  39900. },
  39901. callback: function callback(_callback) {
  39902. return function (type, sourceUpdater) {
  39903. _callback();
  39904. };
  39905. },
  39906. endOfStream: function endOfStream(error) {
  39907. return function (sourceUpdater) {
  39908. if (sourceUpdater.mediaSource.readyState !== 'open') {
  39909. return;
  39910. }
  39911. sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
  39912. try {
  39913. sourceUpdater.mediaSource.endOfStream(error);
  39914. } catch (e) {
  39915. videojs.log.warn('Failed to call media source endOfStream', e);
  39916. }
  39917. };
  39918. },
  39919. duration: function duration(_duration) {
  39920. return function (sourceUpdater) {
  39921. sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
  39922. try {
  39923. sourceUpdater.mediaSource.duration = _duration;
  39924. } catch (e) {
  39925. videojs.log.warn('Failed to set media source duration', e);
  39926. }
  39927. };
  39928. },
  39929. abort: function abort() {
  39930. return function (type, sourceUpdater) {
  39931. if (sourceUpdater.mediaSource.readyState !== 'open') {
  39932. return;
  39933. }
  39934. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  39935. // or the media source does not contain this source buffer.
  39936. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39937. return;
  39938. }
  39939. sourceUpdater.logger_("calling abort on " + type + "Buffer");
  39940. try {
  39941. sourceBuffer.abort();
  39942. } catch (e) {
  39943. videojs.log.warn("Failed to abort on " + type + "Buffer", e);
  39944. }
  39945. };
  39946. },
  39947. addSourceBuffer: function addSourceBuffer(type, codec) {
  39948. return function (sourceUpdater) {
  39949. var titleType = toTitleCase(type);
  39950. var mime = codecs_js.getMimeForCodec(codec);
  39951. sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
  39952. var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  39953. sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  39954. sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  39955. sourceUpdater.codecs[type] = codec;
  39956. sourceUpdater[type + "Buffer"] = sourceBuffer;
  39957. };
  39958. },
  39959. removeSourceBuffer: function removeSourceBuffer(type) {
  39960. return function (sourceUpdater) {
  39961. var sourceBuffer = sourceUpdater[type + "Buffer"];
  39962. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  39963. // or the media source does not contain this source buffer.
  39964. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39965. return;
  39966. }
  39967. sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
  39968. try {
  39969. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  39970. } catch (e) {
  39971. videojs.log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
  39972. }
  39973. };
  39974. },
  39975. changeType: function changeType(codec) {
  39976. return function (type, sourceUpdater) {
  39977. var sourceBuffer = sourceUpdater[type + "Buffer"];
  39978. var mime = codecs_js.getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  39979. // or the media source does not contain this source buffer.
  39980. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  39981. return;
  39982. } // do not update codec if we don't need to.
  39983. if (sourceUpdater.codecs[type] === codec) {
  39984. return;
  39985. }
  39986. sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
  39987. sourceBuffer.changeType(mime);
  39988. sourceUpdater.codecs[type] = codec;
  39989. };
  39990. }
  39991. };
  39992. var pushQueue = function pushQueue(_ref) {
  39993. var type = _ref.type,
  39994. sourceUpdater = _ref.sourceUpdater,
  39995. action = _ref.action,
  39996. doneFn = _ref.doneFn,
  39997. name = _ref.name;
  39998. sourceUpdater.queue.push({
  39999. type: type,
  40000. action: action,
  40001. doneFn: doneFn,
  40002. name: name
  40003. });
  40004. shiftQueue(type, sourceUpdater);
  40005. };
  40006. var onUpdateend = function onUpdateend(type, sourceUpdater) {
  40007. return function (e) {
  40008. // Although there should, in theory, be a pending action for any updateend receieved,
  40009. // there are some actions that may trigger updateend events without set definitions in
  40010. // the w3c spec. For instance, setting the duration on the media source may trigger
  40011. // updateend events on source buffers. This does not appear to be in the spec. As such,
  40012. // if we encounter an updateend without a corresponding pending action from our queue
  40013. // for that source buffer type, process the next action.
  40014. if (sourceUpdater.queuePending[type]) {
  40015. var doneFn = sourceUpdater.queuePending[type].doneFn;
  40016. sourceUpdater.queuePending[type] = null;
  40017. if (doneFn) {
  40018. // if there's an error, report it
  40019. doneFn(sourceUpdater[type + "Error_"]);
  40020. }
  40021. }
  40022. shiftQueue(type, sourceUpdater);
  40023. };
  40024. };
  40025. /**
  40026. * A queue of callbacks to be serialized and applied when a
  40027. * MediaSource and its associated SourceBuffers are not in the
  40028. * updating state. It is used by the segment loader to update the
  40029. * underlying SourceBuffers when new data is loaded, for instance.
  40030. *
  40031. * @class SourceUpdater
  40032. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  40033. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  40034. */
  40035. var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
  40036. _inheritsLoose__default['default'](SourceUpdater, _videojs$EventTarget);
  40037. function SourceUpdater(mediaSource) {
  40038. var _this;
  40039. _this = _videojs$EventTarget.call(this) || this;
  40040. _this.mediaSource = mediaSource;
  40041. _this.sourceopenListener_ = function () {
  40042. return shiftQueue('mediaSource', _assertThisInitialized__default['default'](_this));
  40043. };
  40044. _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
  40045. _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  40046. _this.audioTimestampOffset_ = 0;
  40047. _this.videoTimestampOffset_ = 0;
  40048. _this.queue = [];
  40049. _this.queuePending = {
  40050. audio: null,
  40051. video: null
  40052. };
  40053. _this.delayedAudioAppendQueue_ = [];
  40054. _this.videoAppendQueued_ = false;
  40055. _this.codecs = {};
  40056. _this.onVideoUpdateEnd_ = onUpdateend('video', _assertThisInitialized__default['default'](_this));
  40057. _this.onAudioUpdateEnd_ = onUpdateend('audio', _assertThisInitialized__default['default'](_this));
  40058. _this.onVideoError_ = function (e) {
  40059. // used for debugging
  40060. _this.videoError_ = e;
  40061. };
  40062. _this.onAudioError_ = function (e) {
  40063. // used for debugging
  40064. _this.audioError_ = e;
  40065. };
  40066. _this.createdSourceBuffers_ = false;
  40067. _this.initializedEme_ = false;
  40068. _this.triggeredReady_ = false;
  40069. return _this;
  40070. }
  40071. var _proto = SourceUpdater.prototype;
  40072. _proto.initializedEme = function initializedEme() {
  40073. this.initializedEme_ = true;
  40074. this.triggerReady();
  40075. };
  40076. _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
  40077. // if false, likely waiting on one of the segment loaders to get enough data to create
  40078. // source buffers
  40079. return this.createdSourceBuffers_;
  40080. };
  40081. _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
  40082. return this.initializedEme_;
  40083. };
  40084. _proto.ready = function ready() {
  40085. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  40086. };
  40087. _proto.createSourceBuffers = function createSourceBuffers(codecs) {
  40088. if (this.hasCreatedSourceBuffers()) {
  40089. // already created them before
  40090. return;
  40091. } // the intial addOrChangeSourceBuffers will always be
  40092. // two add buffers.
  40093. this.addOrChangeSourceBuffers(codecs);
  40094. this.createdSourceBuffers_ = true;
  40095. this.trigger('createdsourcebuffers');
  40096. this.triggerReady();
  40097. };
  40098. _proto.triggerReady = function triggerReady() {
  40099. // only allow ready to be triggered once, this prevents the case
  40100. // where:
  40101. // 1. we trigger createdsourcebuffers
  40102. // 2. ie 11 synchronously initializates eme
  40103. // 3. the synchronous initialization causes us to trigger ready
  40104. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  40105. if (this.ready() && !this.triggeredReady_) {
  40106. this.triggeredReady_ = true;
  40107. this.trigger('ready');
  40108. }
  40109. }
  40110. /**
  40111. * Add a type of source buffer to the media source.
  40112. *
  40113. * @param {string} type
  40114. * The type of source buffer to add.
  40115. *
  40116. * @param {string} codec
  40117. * The codec to add the source buffer with.
  40118. */
  40119. ;
  40120. _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
  40121. pushQueue({
  40122. type: 'mediaSource',
  40123. sourceUpdater: this,
  40124. action: actions.addSourceBuffer(type, codec),
  40125. name: 'addSourceBuffer'
  40126. });
  40127. }
  40128. /**
  40129. * call abort on a source buffer.
  40130. *
  40131. * @param {string} type
  40132. * The type of source buffer to call abort on.
  40133. */
  40134. ;
  40135. _proto.abort = function abort(type) {
  40136. pushQueue({
  40137. type: type,
  40138. sourceUpdater: this,
  40139. action: actions.abort(type),
  40140. name: 'abort'
  40141. });
  40142. }
  40143. /**
  40144. * Call removeSourceBuffer and remove a specific type
  40145. * of source buffer on the mediaSource.
  40146. *
  40147. * @param {string} type
  40148. * The type of source buffer to remove.
  40149. */
  40150. ;
  40151. _proto.removeSourceBuffer = function removeSourceBuffer(type) {
  40152. if (!this.canRemoveSourceBuffer()) {
  40153. videojs.log.error('removeSourceBuffer is not supported!');
  40154. return;
  40155. }
  40156. pushQueue({
  40157. type: 'mediaSource',
  40158. sourceUpdater: this,
  40159. action: actions.removeSourceBuffer(type),
  40160. name: 'removeSourceBuffer'
  40161. });
  40162. }
  40163. /**
  40164. * Whether or not the removeSourceBuffer function is supported
  40165. * on the mediaSource.
  40166. *
  40167. * @return {boolean}
  40168. * if removeSourceBuffer can be called.
  40169. */
  40170. ;
  40171. _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
  40172. // IE reports that it supports removeSourceBuffer, but often throws
  40173. // errors when attempting to use the function. So we report that it
  40174. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  40175. // throws errors, so we report that it does not support this as well.
  40176. 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';
  40177. }
  40178. /**
  40179. * Whether or not the changeType function is supported
  40180. * on our SourceBuffers.
  40181. *
  40182. * @return {boolean}
  40183. * if changeType can be called.
  40184. */
  40185. ;
  40186. SourceUpdater.canChangeType = function canChangeType() {
  40187. return window__default['default'].SourceBuffer && window__default['default'].SourceBuffer.prototype && typeof window__default['default'].SourceBuffer.prototype.changeType === 'function';
  40188. }
  40189. /**
  40190. * Whether or not the changeType function is supported
  40191. * on our SourceBuffers.
  40192. *
  40193. * @return {boolean}
  40194. * if changeType can be called.
  40195. */
  40196. ;
  40197. _proto.canChangeType = function canChangeType() {
  40198. return this.constructor.canChangeType();
  40199. }
  40200. /**
  40201. * Call the changeType function on a source buffer, given the code and type.
  40202. *
  40203. * @param {string} type
  40204. * The type of source buffer to call changeType on.
  40205. *
  40206. * @param {string} codec
  40207. * The codec string to change type with on the source buffer.
  40208. */
  40209. ;
  40210. _proto.changeType = function changeType(type, codec) {
  40211. if (!this.canChangeType()) {
  40212. videojs.log.error('changeType is not supported!');
  40213. return;
  40214. }
  40215. pushQueue({
  40216. type: type,
  40217. sourceUpdater: this,
  40218. action: actions.changeType(codec),
  40219. name: 'changeType'
  40220. });
  40221. }
  40222. /**
  40223. * Add source buffers with a codec or, if they are already created,
  40224. * call changeType on source buffers using changeType.
  40225. *
  40226. * @param {Object} codecs
  40227. * Codecs to switch to
  40228. */
  40229. ;
  40230. _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
  40231. var _this2 = this;
  40232. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  40233. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  40234. }
  40235. Object.keys(codecs).forEach(function (type) {
  40236. var codec = codecs[type];
  40237. if (!_this2.hasCreatedSourceBuffers()) {
  40238. return _this2.addSourceBuffer(type, codec);
  40239. }
  40240. if (_this2.canChangeType()) {
  40241. _this2.changeType(type, codec);
  40242. }
  40243. });
  40244. }
  40245. /**
  40246. * Queue an update to append an ArrayBuffer.
  40247. *
  40248. * @param {MediaObject} object containing audioBytes and/or videoBytes
  40249. * @param {Function} done the function to call when done
  40250. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  40251. */
  40252. ;
  40253. _proto.appendBuffer = function appendBuffer(options, doneFn) {
  40254. var _this3 = this;
  40255. var segmentInfo = options.segmentInfo,
  40256. type = options.type,
  40257. bytes = options.bytes;
  40258. this.processedAppend_ = true;
  40259. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  40260. this.delayedAudioAppendQueue_.push([options, doneFn]);
  40261. this.logger_("delayed audio append of " + bytes.length + " until video append");
  40262. return;
  40263. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  40264. // not be fired. This means that the queue will be blocked until the next action
  40265. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  40266. // these errors by calling the doneFn with the specific error.
  40267. var onError = doneFn;
  40268. pushQueue({
  40269. type: type,
  40270. sourceUpdater: this,
  40271. action: actions.appendBuffer(bytes, segmentInfo || {
  40272. mediaIndex: -1
  40273. }, onError),
  40274. doneFn: doneFn,
  40275. name: 'appendBuffer'
  40276. });
  40277. if (type === 'video') {
  40278. this.videoAppendQueued_ = true;
  40279. if (!this.delayedAudioAppendQueue_.length) {
  40280. return;
  40281. }
  40282. var queue = this.delayedAudioAppendQueue_.slice();
  40283. this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
  40284. this.delayedAudioAppendQueue_.length = 0;
  40285. queue.forEach(function (que) {
  40286. _this3.appendBuffer.apply(_this3, que);
  40287. });
  40288. }
  40289. }
  40290. /**
  40291. * Get the audio buffer's buffered timerange.
  40292. *
  40293. * @return {TimeRange}
  40294. * The audio buffer's buffered time range
  40295. */
  40296. ;
  40297. _proto.audioBuffered = function audioBuffered() {
  40298. // no media source/source buffer or it isn't in the media sources
  40299. // source buffer list
  40300. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  40301. return videojs.createTimeRange();
  40302. }
  40303. return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs.createTimeRange();
  40304. }
  40305. /**
  40306. * Get the video buffer's buffered timerange.
  40307. *
  40308. * @return {TimeRange}
  40309. * The video buffer's buffered time range
  40310. */
  40311. ;
  40312. _proto.videoBuffered = function videoBuffered() {
  40313. // no media source/source buffer or it isn't in the media sources
  40314. // source buffer list
  40315. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  40316. return videojs.createTimeRange();
  40317. }
  40318. return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs.createTimeRange();
  40319. }
  40320. /**
  40321. * Get a combined video/audio buffer's buffered timerange.
  40322. *
  40323. * @return {TimeRange}
  40324. * the combined time range
  40325. */
  40326. ;
  40327. _proto.buffered = function buffered() {
  40328. var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  40329. var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  40330. if (audio && !video) {
  40331. return this.audioBuffered();
  40332. }
  40333. if (video && !audio) {
  40334. return this.videoBuffered();
  40335. }
  40336. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  40337. }
  40338. /**
  40339. * Add a callback to the queue that will set duration on the mediaSource.
  40340. *
  40341. * @param {number} duration
  40342. * The duration to set
  40343. *
  40344. * @param {Function} [doneFn]
  40345. * function to run after duration has been set.
  40346. */
  40347. ;
  40348. _proto.setDuration = function setDuration(duration, doneFn) {
  40349. if (doneFn === void 0) {
  40350. doneFn = noop;
  40351. } // In order to set the duration on the media source, it's necessary to wait for all
  40352. // source buffers to no longer be updating. "If the updating attribute equals true on
  40353. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40354. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40355. pushQueue({
  40356. type: 'mediaSource',
  40357. sourceUpdater: this,
  40358. action: actions.duration(duration),
  40359. name: 'duration',
  40360. doneFn: doneFn
  40361. });
  40362. }
  40363. /**
  40364. * Add a mediaSource endOfStream call to the queue
  40365. *
  40366. * @param {Error} [error]
  40367. * Call endOfStream with an error
  40368. *
  40369. * @param {Function} [doneFn]
  40370. * A function that should be called when the
  40371. * endOfStream call has finished.
  40372. */
  40373. ;
  40374. _proto.endOfStream = function endOfStream(error, doneFn) {
  40375. if (error === void 0) {
  40376. error = null;
  40377. }
  40378. if (doneFn === void 0) {
  40379. doneFn = noop;
  40380. }
  40381. if (typeof error !== 'string') {
  40382. error = undefined;
  40383. } // In order to set the duration on the media source, it's necessary to wait for all
  40384. // source buffers to no longer be updating. "If the updating attribute equals true on
  40385. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  40386. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  40387. pushQueue({
  40388. type: 'mediaSource',
  40389. sourceUpdater: this,
  40390. action: actions.endOfStream(error),
  40391. name: 'endOfStream',
  40392. doneFn: doneFn
  40393. });
  40394. }
  40395. /**
  40396. * Queue an update to remove a time range from the buffer.
  40397. *
  40398. * @param {number} start where to start the removal
  40399. * @param {number} end where to end the removal
  40400. * @param {Function} [done=noop] optional callback to be executed when the remove
  40401. * operation is complete
  40402. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40403. */
  40404. ;
  40405. _proto.removeAudio = function removeAudio(start, end, done) {
  40406. if (done === void 0) {
  40407. done = noop;
  40408. }
  40409. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  40410. done();
  40411. return;
  40412. }
  40413. pushQueue({
  40414. type: 'audio',
  40415. sourceUpdater: this,
  40416. action: actions.remove(start, end),
  40417. doneFn: done,
  40418. name: 'remove'
  40419. });
  40420. }
  40421. /**
  40422. * Queue an update to remove a time range from the buffer.
  40423. *
  40424. * @param {number} start where to start the removal
  40425. * @param {number} end where to end the removal
  40426. * @param {Function} [done=noop] optional callback to be executed when the remove
  40427. * operation is complete
  40428. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  40429. */
  40430. ;
  40431. _proto.removeVideo = function removeVideo(start, end, done) {
  40432. if (done === void 0) {
  40433. done = noop;
  40434. }
  40435. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  40436. done();
  40437. return;
  40438. }
  40439. pushQueue({
  40440. type: 'video',
  40441. sourceUpdater: this,
  40442. action: actions.remove(start, end),
  40443. doneFn: done,
  40444. name: 'remove'
  40445. });
  40446. }
  40447. /**
  40448. * Whether the underlying sourceBuffer is updating or not
  40449. *
  40450. * @return {boolean} the updating status of the SourceBuffer
  40451. */
  40452. ;
  40453. _proto.updating = function updating() {
  40454. // the audio/video source buffer is updating
  40455. if (_updating('audio', this) || _updating('video', this)) {
  40456. return true;
  40457. }
  40458. return false;
  40459. }
  40460. /**
  40461. * Set/get the timestampoffset on the audio SourceBuffer
  40462. *
  40463. * @return {number} the timestamp offset
  40464. */
  40465. ;
  40466. _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
  40467. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  40468. this.audioTimestampOffset_ !== offset) {
  40469. pushQueue({
  40470. type: 'audio',
  40471. sourceUpdater: this,
  40472. action: actions.timestampOffset(offset),
  40473. name: 'timestampOffset'
  40474. });
  40475. this.audioTimestampOffset_ = offset;
  40476. }
  40477. return this.audioTimestampOffset_;
  40478. }
  40479. /**
  40480. * Set/get the timestampoffset on the video SourceBuffer
  40481. *
  40482. * @return {number} the timestamp offset
  40483. */
  40484. ;
  40485. _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
  40486. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  40487. this.videoTimestampOffset !== offset) {
  40488. pushQueue({
  40489. type: 'video',
  40490. sourceUpdater: this,
  40491. action: actions.timestampOffset(offset),
  40492. name: 'timestampOffset'
  40493. });
  40494. this.videoTimestampOffset_ = offset;
  40495. }
  40496. return this.videoTimestampOffset_;
  40497. }
  40498. /**
  40499. * Add a function to the queue that will be called
  40500. * when it is its turn to run in the audio queue.
  40501. *
  40502. * @param {Function} callback
  40503. * The callback to queue.
  40504. */
  40505. ;
  40506. _proto.audioQueueCallback = function audioQueueCallback(callback) {
  40507. if (!this.audioBuffer) {
  40508. return;
  40509. }
  40510. pushQueue({
  40511. type: 'audio',
  40512. sourceUpdater: this,
  40513. action: actions.callback(callback),
  40514. name: 'callback'
  40515. });
  40516. }
  40517. /**
  40518. * Add a function to the queue that will be called
  40519. * when it is its turn to run in the video queue.
  40520. *
  40521. * @param {Function} callback
  40522. * The callback to queue.
  40523. */
  40524. ;
  40525. _proto.videoQueueCallback = function videoQueueCallback(callback) {
  40526. if (!this.videoBuffer) {
  40527. return;
  40528. }
  40529. pushQueue({
  40530. type: 'video',
  40531. sourceUpdater: this,
  40532. action: actions.callback(callback),
  40533. name: 'callback'
  40534. });
  40535. }
  40536. /**
  40537. * dispose of the source updater and the underlying sourceBuffer
  40538. */
  40539. ;
  40540. _proto.dispose = function dispose() {
  40541. var _this4 = this;
  40542. this.trigger('dispose');
  40543. bufferTypes.forEach(function (type) {
  40544. _this4.abort(type);
  40545. if (_this4.canRemoveSourceBuffer()) {
  40546. _this4.removeSourceBuffer(type);
  40547. } else {
  40548. _this4[type + "QueueCallback"](function () {
  40549. return cleanupBuffer(type, _this4);
  40550. });
  40551. }
  40552. });
  40553. this.videoAppendQueued_ = false;
  40554. this.delayedAudioAppendQueue_.length = 0;
  40555. if (this.sourceopenListener_) {
  40556. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  40557. }
  40558. this.off();
  40559. };
  40560. return SourceUpdater;
  40561. }(videojs.EventTarget);
  40562. var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
  40563. return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  40564. };
  40565. var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (_char3) {
  40566. return _char3.charCodeAt(0);
  40567. }));
  40568. var NoVttJsError = /*#__PURE__*/function (_Error) {
  40569. _inheritsLoose__default['default'](NoVttJsError, _Error);
  40570. function NoVttJsError() {
  40571. return _Error.call(this, 'Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.') || this;
  40572. }
  40573. return NoVttJsError;
  40574. }( /*#__PURE__*/_wrapNativeSuper__default['default'](Error));
  40575. /**
  40576. * An object that manages segment loading and appending.
  40577. *
  40578. * @class VTTSegmentLoader
  40579. * @param {Object} options required and optional options
  40580. * @extends videojs.EventTarget
  40581. */
  40582. var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
  40583. _inheritsLoose__default['default'](VTTSegmentLoader, _SegmentLoader);
  40584. function VTTSegmentLoader(settings, options) {
  40585. var _this;
  40586. if (options === void 0) {
  40587. options = {};
  40588. }
  40589. _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
  40590. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  40591. _this.mediaSource_ = null;
  40592. _this.subtitlesTrack_ = null;
  40593. _this.loaderType_ = 'subtitle';
  40594. _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  40595. _this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  40596. // the sync controller leads to improper behavior.
  40597. _this.shouldSaveSegmentTimingInfo_ = false;
  40598. return _this;
  40599. }
  40600. var _proto = VTTSegmentLoader.prototype;
  40601. _proto.createTransmuxer_ = function createTransmuxer_() {
  40602. // don't need to transmux any subtitles
  40603. return null;
  40604. }
  40605. /**
  40606. * Indicates which time ranges are buffered
  40607. *
  40608. * @return {TimeRange}
  40609. * TimeRange object representing the current buffered ranges
  40610. */
  40611. ;
  40612. _proto.buffered_ = function buffered_() {
  40613. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  40614. return videojs.createTimeRanges();
  40615. }
  40616. var cues = this.subtitlesTrack_.cues;
  40617. var start = cues[0].startTime;
  40618. var end = cues[cues.length - 1].startTime;
  40619. return videojs.createTimeRanges([[start, end]]);
  40620. }
  40621. /**
  40622. * Gets and sets init segment for the provided map
  40623. *
  40624. * @param {Object} map
  40625. * The map object representing the init segment to get or set
  40626. * @param {boolean=} set
  40627. * If true, the init segment for the provided map should be saved
  40628. * @return {Object}
  40629. * map object for desired init segment
  40630. */
  40631. ;
  40632. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  40633. if (set === void 0) {
  40634. set = false;
  40635. }
  40636. if (!map) {
  40637. return null;
  40638. }
  40639. var id = initSegmentId(map);
  40640. var storedMap = this.initSegments_[id];
  40641. if (set && !storedMap && map.bytes) {
  40642. // append WebVTT line terminators to the media initialization segment if it exists
  40643. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  40644. // requires two or more WebVTT line terminators between the WebVTT header and the
  40645. // rest of the file
  40646. var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  40647. var combinedSegment = new Uint8Array(combinedByteLength);
  40648. combinedSegment.set(map.bytes);
  40649. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  40650. this.initSegments_[id] = storedMap = {
  40651. resolvedUri: map.resolvedUri,
  40652. byterange: map.byterange,
  40653. bytes: combinedSegment
  40654. };
  40655. }
  40656. return storedMap || map;
  40657. }
  40658. /**
  40659. * Returns true if all configuration required for loading is present, otherwise false.
  40660. *
  40661. * @return {boolean} True if the all configuration is ready for loading
  40662. * @private
  40663. */
  40664. ;
  40665. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  40666. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  40667. }
  40668. /**
  40669. * Once all the starting parameters have been specified, begin
  40670. * operation. This method should only be invoked from the INIT
  40671. * state.
  40672. *
  40673. * @private
  40674. */
  40675. ;
  40676. _proto.init_ = function init_() {
  40677. this.state = 'READY';
  40678. this.resetEverything();
  40679. return this.monitorBuffer_();
  40680. }
  40681. /**
  40682. * Set a subtitle track on the segment loader to add subtitles to
  40683. *
  40684. * @param {TextTrack=} track
  40685. * The text track to add loaded subtitles to
  40686. * @return {TextTrack}
  40687. * Returns the subtitles track
  40688. */
  40689. ;
  40690. _proto.track = function track(_track) {
  40691. if (typeof _track === 'undefined') {
  40692. return this.subtitlesTrack_;
  40693. }
  40694. this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
  40695. // buffering now
  40696. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  40697. this.init_();
  40698. }
  40699. return this.subtitlesTrack_;
  40700. }
  40701. /**
  40702. * Remove any data in the source buffer between start and end times
  40703. *
  40704. * @param {number} start - the start time of the region to remove from the buffer
  40705. * @param {number} end - the end time of the region to remove from the buffer
  40706. */
  40707. ;
  40708. _proto.remove = function remove(start, end) {
  40709. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  40710. }
  40711. /**
  40712. * fill the buffer with segements unless the sourceBuffers are
  40713. * currently updating
  40714. *
  40715. * Note: this function should only ever be called by monitorBuffer_
  40716. * and never directly
  40717. *
  40718. * @private
  40719. */
  40720. ;
  40721. _proto.fillBuffer_ = function fillBuffer_() {
  40722. var _this2 = this; // see if we need to begin loading immediately
  40723. var segmentInfo = this.chooseNextRequest_();
  40724. if (!segmentInfo) {
  40725. return;
  40726. }
  40727. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  40728. // We don't have the timestamp offset that we need to sync subtitles.
  40729. // Rerun on a timestamp offset or user interaction.
  40730. var checkTimestampOffset = function checkTimestampOffset() {
  40731. _this2.state = 'READY';
  40732. if (!_this2.paused()) {
  40733. // if not paused, queue a buffer check as soon as possible
  40734. _this2.monitorBuffer_();
  40735. }
  40736. };
  40737. this.syncController_.one('timestampoffset', checkTimestampOffset);
  40738. this.state = 'WAITING_ON_TIMELINE';
  40739. return;
  40740. }
  40741. this.loadSegment_(segmentInfo);
  40742. } // never set a timestamp offset for vtt segments.
  40743. ;
  40744. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
  40745. return null;
  40746. };
  40747. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  40748. return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
  40749. }
  40750. /**
  40751. * Prevents the segment loader from requesting segments we know contain no subtitles
  40752. * by walking forward until we find the next segment that we don't know whether it is
  40753. * empty or not.
  40754. *
  40755. * @param {Object} segmentInfo
  40756. * a segment info object that describes the current segment
  40757. * @return {Object}
  40758. * a segment info object that describes the current segment
  40759. */
  40760. ;
  40761. _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
  40762. while (segmentInfo && segmentInfo.segment.empty) {
  40763. // stop at the last possible segmentInfo
  40764. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  40765. segmentInfo = null;
  40766. break;
  40767. }
  40768. segmentInfo = this.generateSegmentInfo_({
  40769. playlist: segmentInfo.playlist,
  40770. mediaIndex: segmentInfo.mediaIndex + 1,
  40771. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  40772. isSyncRequest: segmentInfo.isSyncRequest
  40773. });
  40774. }
  40775. return segmentInfo;
  40776. };
  40777. _proto.stopForError = function stopForError(error) {
  40778. this.error(error);
  40779. this.state = 'READY';
  40780. this.pause();
  40781. this.trigger('error');
  40782. }
  40783. /**
  40784. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  40785. *
  40786. * @private
  40787. */
  40788. ;
  40789. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  40790. var _this3 = this;
  40791. if (!this.subtitlesTrack_) {
  40792. this.state = 'READY';
  40793. return;
  40794. }
  40795. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  40796. if (!this.pendingSegment_) {
  40797. this.state = 'READY';
  40798. this.mediaRequestsAborted += 1;
  40799. return;
  40800. }
  40801. if (error) {
  40802. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  40803. this.handleTimeout_();
  40804. }
  40805. if (error.code === REQUEST_ERRORS.ABORTED) {
  40806. this.mediaRequestsAborted += 1;
  40807. } else {
  40808. this.mediaRequestsErrored += 1;
  40809. }
  40810. this.stopForError(error);
  40811. return;
  40812. }
  40813. var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  40814. // maintain functionality between segment loaders
  40815. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  40816. if (simpleSegment.key) {
  40817. this.segmentKey(simpleSegment.key, true);
  40818. }
  40819. this.state = 'APPENDING'; // used for tests
  40820. this.trigger('appending');
  40821. var segment = segmentInfo.segment;
  40822. if (segment.map) {
  40823. segment.map.bytes = simpleSegment.map.bytes;
  40824. }
  40825. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  40826. if (typeof window__default['default'].WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  40827. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  40828. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  40829. this.loadVttJs().then(function () {
  40830. return _this3.segmentRequestFinished_(error, simpleSegment, result);
  40831. }, function () {
  40832. return _this3.stopForError({
  40833. message: 'Error loading vtt.js'
  40834. });
  40835. });
  40836. return;
  40837. }
  40838. segment.requested = true;
  40839. try {
  40840. this.parseVTTCues_(segmentInfo);
  40841. } catch (e) {
  40842. this.stopForError({
  40843. message: e.message
  40844. });
  40845. return;
  40846. }
  40847. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  40848. if (segmentInfo.cues.length) {
  40849. segmentInfo.timingInfo = {
  40850. start: segmentInfo.cues[0].startTime,
  40851. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  40852. };
  40853. } else {
  40854. segmentInfo.timingInfo = {
  40855. start: segmentInfo.startOfSegment,
  40856. end: segmentInfo.startOfSegment + segmentInfo.duration
  40857. };
  40858. }
  40859. if (segmentInfo.isSyncRequest) {
  40860. this.trigger('syncinfoupdate');
  40861. this.pendingSegment_ = null;
  40862. this.state = 'READY';
  40863. return;
  40864. }
  40865. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  40866. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  40867. // the subtitle track
  40868. segmentInfo.cues.forEach(function (cue) {
  40869. _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window__default['default'].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  40870. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  40871. // cues to have identical time-intervals, but if the text is also identical
  40872. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  40873. // "overlaps" VTT segments)
  40874. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  40875. this.handleAppendsDone_();
  40876. };
  40877. _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
  40878. // that we do not support here.
  40879. };
  40880. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
  40881. }
  40882. /**
  40883. * Uses the WebVTT parser to parse the segment response
  40884. *
  40885. * @throws NoVttJsError
  40886. *
  40887. * @param {Object} segmentInfo
  40888. * a segment info object that describes the current segment
  40889. * @private
  40890. */
  40891. ;
  40892. _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
  40893. var decoder;
  40894. var decodeBytesToString = false;
  40895. if (typeof window__default['default'].WebVTT !== 'function') {
  40896. // caller is responsible for exception handling.
  40897. throw new NoVttJsError();
  40898. }
  40899. if (typeof window__default['default'].TextDecoder === 'function') {
  40900. decoder = new window__default['default'].TextDecoder('utf8');
  40901. } else {
  40902. decoder = window__default['default'].WebVTT.StringDecoder();
  40903. decodeBytesToString = true;
  40904. }
  40905. var parser = new window__default['default'].WebVTT.Parser(window__default['default'], window__default['default'].vttjs, decoder);
  40906. segmentInfo.cues = [];
  40907. segmentInfo.timestampmap = {
  40908. MPEGTS: 0,
  40909. LOCAL: 0
  40910. };
  40911. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  40912. parser.ontimestampmap = function (map) {
  40913. segmentInfo.timestampmap = map;
  40914. };
  40915. parser.onparsingerror = function (error) {
  40916. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  40917. };
  40918. if (segmentInfo.segment.map) {
  40919. var mapData = segmentInfo.segment.map.bytes;
  40920. if (decodeBytesToString) {
  40921. mapData = uint8ToUtf8(mapData);
  40922. }
  40923. parser.parse(mapData);
  40924. }
  40925. var segmentData = segmentInfo.bytes;
  40926. if (decodeBytesToString) {
  40927. segmentData = uint8ToUtf8(segmentData);
  40928. }
  40929. parser.parse(segmentData);
  40930. parser.flush();
  40931. }
  40932. /**
  40933. * Updates the start and end times of any cues parsed by the WebVTT parser using
  40934. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  40935. * from the SyncController
  40936. *
  40937. * @param {Object} segmentInfo
  40938. * a segment info object that describes the current segment
  40939. * @param {Object} mappingObj
  40940. * object containing a mapping from TS to media time
  40941. * @param {Object} playlist
  40942. * the playlist object containing the segment
  40943. * @private
  40944. */
  40945. ;
  40946. _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  40947. var segment = segmentInfo.segment;
  40948. if (!mappingObj) {
  40949. // If the sync controller does not have a mapping of TS to Media Time for the
  40950. // timeline, then we don't have enough information to update the cue
  40951. // start/end times
  40952. return;
  40953. }
  40954. if (!segmentInfo.cues.length) {
  40955. // If there are no cues, we also do not have enough information to figure out
  40956. // segment timing. Mark that the segment contains no cues so we don't re-request
  40957. // an empty segment.
  40958. segment.empty = true;
  40959. return;
  40960. }
  40961. var timestampmap = segmentInfo.timestampmap;
  40962. var diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  40963. segmentInfo.cues.forEach(function (cue) {
  40964. // First convert cue time to TS time using the timestamp-map provided within the vtt
  40965. cue.startTime += diff;
  40966. cue.endTime += diff;
  40967. });
  40968. if (!playlist.syncInfo) {
  40969. var firstStart = segmentInfo.cues[0].startTime;
  40970. var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  40971. playlist.syncInfo = {
  40972. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  40973. time: Math.min(firstStart, lastStart - segment.duration)
  40974. };
  40975. }
  40976. };
  40977. return VTTSegmentLoader;
  40978. }(SegmentLoader);
  40979. /**
  40980. * @file ad-cue-tags.js
  40981. */
  40982. /**
  40983. * Searches for an ad cue that overlaps with the given mediaTime
  40984. *
  40985. * @param {Object} track
  40986. * the track to find the cue for
  40987. *
  40988. * @param {number} mediaTime
  40989. * the time to find the cue at
  40990. *
  40991. * @return {Object|null}
  40992. * the found cue or null
  40993. */
  40994. var findAdCue = function findAdCue(track, mediaTime) {
  40995. var cues = track.cues;
  40996. for (var i = 0; i < cues.length; i++) {
  40997. var cue = cues[i];
  40998. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  40999. return cue;
  41000. }
  41001. }
  41002. return null;
  41003. };
  41004. var updateAdCues = function updateAdCues(media, track, offset) {
  41005. if (offset === void 0) {
  41006. offset = 0;
  41007. }
  41008. if (!media.segments) {
  41009. return;
  41010. }
  41011. var mediaTime = offset;
  41012. var cue;
  41013. for (var i = 0; i < media.segments.length; i++) {
  41014. var segment = media.segments[i];
  41015. if (!cue) {
  41016. // Since the cues will span for at least the segment duration, adding a fudge
  41017. // factor of half segment duration will prevent duplicate cues from being
  41018. // created when timing info is not exact (e.g. cue start time initialized
  41019. // at 10.006677, but next call mediaTime is 10.003332 )
  41020. cue = findAdCue(track, mediaTime + segment.duration / 2);
  41021. }
  41022. if (cue) {
  41023. if ('cueIn' in segment) {
  41024. // Found a CUE-IN so end the cue
  41025. cue.endTime = mediaTime;
  41026. cue.adEndTime = mediaTime;
  41027. mediaTime += segment.duration;
  41028. cue = null;
  41029. continue;
  41030. }
  41031. if (mediaTime < cue.endTime) {
  41032. // Already processed this mediaTime for this cue
  41033. mediaTime += segment.duration;
  41034. continue;
  41035. } // otherwise extend cue until a CUE-IN is found
  41036. cue.endTime += segment.duration;
  41037. } else {
  41038. if ('cueOut' in segment) {
  41039. cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  41040. cue.adStartTime = mediaTime; // Assumes tag format to be
  41041. // #EXT-X-CUE-OUT:30
  41042. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  41043. track.addCue(cue);
  41044. }
  41045. if ('cueOutCont' in segment) {
  41046. // Entered into the middle of an ad cue
  41047. // Assumes tag formate to be
  41048. // #EXT-X-CUE-OUT-CONT:10/30
  41049. var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
  41050. adOffset = _segment$cueOutCont$s[0],
  41051. adTotal = _segment$cueOutCont$s[1];
  41052. cue = new window__default['default'].VTTCue(mediaTime, mediaTime + segment.duration, '');
  41053. cue.adStartTime = mediaTime - adOffset;
  41054. cue.adEndTime = cue.adStartTime + adTotal;
  41055. track.addCue(cue);
  41056. }
  41057. }
  41058. mediaTime += segment.duration;
  41059. }
  41060. }; // synchronize expired playlist segments.
  41061. // the max media sequence diff is 48 hours of live stream
  41062. // content with two second segments. Anything larger than that
  41063. // will likely be invalid.
  41064. var MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  41065. var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  41066. // the equivalence display-time 0 === segment-index 0
  41067. {
  41068. name: 'VOD',
  41069. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  41070. if (duration !== Infinity) {
  41071. var syncPoint = {
  41072. time: 0,
  41073. segmentIndex: 0,
  41074. partIndex: null
  41075. };
  41076. return syncPoint;
  41077. }
  41078. return null;
  41079. }
  41080. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  41081. {
  41082. name: 'ProgramDateTime',
  41083. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  41084. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  41085. return null;
  41086. }
  41087. var syncPoint = null;
  41088. var lastDistance = null;
  41089. var partsAndSegments = getPartsAndSegments(playlist);
  41090. currentTime = currentTime || 0;
  41091. for (var i = 0; i < partsAndSegments.length; i++) {
  41092. // start from the end and loop backwards for live
  41093. // or start from the front and loop forwards for non-live
  41094. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41095. var partAndSegment = partsAndSegments[index];
  41096. var segment = partAndSegment.segment;
  41097. var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  41098. if (!datetimeMapping || !segment.dateTimeObject) {
  41099. continue;
  41100. }
  41101. var segmentTime = segment.dateTimeObject.getTime() / 1000;
  41102. var start = segmentTime + datetimeMapping; // take part duration into account.
  41103. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  41104. for (var z = 0; z < partAndSegment.partIndex; z++) {
  41105. start += segment.parts[z].duration;
  41106. }
  41107. }
  41108. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  41109. // currentTime and can stop looking for better candidates
  41110. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  41111. break;
  41112. }
  41113. lastDistance = distance;
  41114. syncPoint = {
  41115. time: start,
  41116. segmentIndex: partAndSegment.segmentIndex,
  41117. partIndex: partAndSegment.partIndex
  41118. };
  41119. }
  41120. return syncPoint;
  41121. }
  41122. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  41123. // segment in the current timeline with timing data
  41124. {
  41125. name: 'Segment',
  41126. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  41127. var syncPoint = null;
  41128. var lastDistance = null;
  41129. currentTime = currentTime || 0;
  41130. var partsAndSegments = getPartsAndSegments(playlist);
  41131. for (var i = 0; i < partsAndSegments.length; i++) {
  41132. // start from the end and loop backwards for live
  41133. // or start from the front and loop forwards for non-live
  41134. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  41135. var partAndSegment = partsAndSegments[index];
  41136. var segment = partAndSegment.segment;
  41137. var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  41138. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  41139. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  41140. // currentTime and can stop looking for better candidates
  41141. if (lastDistance !== null && lastDistance < distance) {
  41142. break;
  41143. }
  41144. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41145. lastDistance = distance;
  41146. syncPoint = {
  41147. time: start,
  41148. segmentIndex: partAndSegment.segmentIndex,
  41149. partIndex: partAndSegment.partIndex
  41150. };
  41151. }
  41152. }
  41153. }
  41154. return syncPoint;
  41155. }
  41156. }, // Stategy "Discontinuity": We have a discontinuity with a known
  41157. // display-time
  41158. {
  41159. name: 'Discontinuity',
  41160. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  41161. var syncPoint = null;
  41162. currentTime = currentTime || 0;
  41163. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41164. var lastDistance = null;
  41165. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  41166. var segmentIndex = playlist.discontinuityStarts[i];
  41167. var discontinuity = playlist.discontinuitySequence + i + 1;
  41168. var discontinuitySync = syncController.discontinuities[discontinuity];
  41169. if (discontinuitySync) {
  41170. var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  41171. // currentTime and can stop looking for better candidates
  41172. if (lastDistance !== null && lastDistance < distance) {
  41173. break;
  41174. }
  41175. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  41176. lastDistance = distance;
  41177. syncPoint = {
  41178. time: discontinuitySync.time,
  41179. segmentIndex: segmentIndex,
  41180. partIndex: null
  41181. };
  41182. }
  41183. }
  41184. }
  41185. }
  41186. return syncPoint;
  41187. }
  41188. }, // Stategy "Playlist": We have a playlist with a known mapping of
  41189. // segment index to display time
  41190. {
  41191. name: 'Playlist',
  41192. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  41193. if (playlist.syncInfo) {
  41194. var syncPoint = {
  41195. time: playlist.syncInfo.time,
  41196. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  41197. partIndex: null
  41198. };
  41199. return syncPoint;
  41200. }
  41201. return null;
  41202. }
  41203. }];
  41204. var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
  41205. _inheritsLoose__default['default'](SyncController, _videojs$EventTarget);
  41206. function SyncController(options) {
  41207. var _this;
  41208. _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
  41209. _this.timelines = [];
  41210. _this.discontinuities = [];
  41211. _this.timelineToDatetimeMappings = {};
  41212. _this.logger_ = logger('SyncController');
  41213. return _this;
  41214. }
  41215. /**
  41216. * Find a sync-point for the playlist specified
  41217. *
  41218. * A sync-point is defined as a known mapping from display-time to
  41219. * a segment-index in the current playlist.
  41220. *
  41221. * @param {Playlist} playlist
  41222. * The playlist that needs a sync-point
  41223. * @param {number} duration
  41224. * Duration of the MediaSource (Infinite if playing a live source)
  41225. * @param {number} currentTimeline
  41226. * The last timeline from which a segment was loaded
  41227. * @return {Object}
  41228. * A sync-point object
  41229. */
  41230. var _proto = SyncController.prototype;
  41231. _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  41232. var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  41233. if (!syncPoints.length) {
  41234. // Signal that we need to attempt to get a sync-point manually
  41235. // by fetching a segment in the playlist and constructing
  41236. // a sync-point from that information
  41237. return null;
  41238. } // Now find the sync-point that is closest to the currentTime because
  41239. // that should result in the most accurate guess about which segment
  41240. // to fetch
  41241. return this.selectSyncPoint_(syncPoints, {
  41242. key: 'time',
  41243. value: currentTime
  41244. });
  41245. }
  41246. /**
  41247. * Calculate the amount of time that has expired off the playlist during playback
  41248. *
  41249. * @param {Playlist} playlist
  41250. * Playlist object to calculate expired from
  41251. * @param {number} duration
  41252. * Duration of the MediaSource (Infinity if playling a live source)
  41253. * @return {number|null}
  41254. * The amount of time that has expired off the playlist during playback. Null
  41255. * if no sync-points for the playlist can be found.
  41256. */
  41257. ;
  41258. _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
  41259. if (!playlist || !playlist.segments) {
  41260. return null;
  41261. }
  41262. var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  41263. if (!syncPoints.length) {
  41264. return null;
  41265. }
  41266. var syncPoint = this.selectSyncPoint_(syncPoints, {
  41267. key: 'segmentIndex',
  41268. value: 0
  41269. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  41270. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  41271. if (syncPoint.segmentIndex > 0) {
  41272. syncPoint.time *= -1;
  41273. }
  41274. return Math.abs(syncPoint.time + sumDurations({
  41275. defaultDuration: playlist.targetDuration,
  41276. durationList: playlist.segments,
  41277. startIndex: syncPoint.segmentIndex,
  41278. endIndex: 0
  41279. }));
  41280. }
  41281. /**
  41282. * Runs each sync-point strategy and returns a list of sync-points returned by the
  41283. * strategies
  41284. *
  41285. * @private
  41286. * @param {Playlist} playlist
  41287. * The playlist that needs a sync-point
  41288. * @param {number} duration
  41289. * Duration of the MediaSource (Infinity if playing a live source)
  41290. * @param {number} currentTimeline
  41291. * The last timeline from which a segment was loaded
  41292. * @return {Array}
  41293. * A list of sync-point objects
  41294. */
  41295. ;
  41296. _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
  41297. var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  41298. for (var i = 0; i < syncPointStrategies.length; i++) {
  41299. var strategy = syncPointStrategies[i];
  41300. var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  41301. if (syncPoint) {
  41302. syncPoint.strategy = strategy.name;
  41303. syncPoints.push({
  41304. strategy: strategy.name,
  41305. syncPoint: syncPoint
  41306. });
  41307. }
  41308. }
  41309. return syncPoints;
  41310. }
  41311. /**
  41312. * Selects the sync-point nearest the specified target
  41313. *
  41314. * @private
  41315. * @param {Array} syncPoints
  41316. * List of sync-points to select from
  41317. * @param {Object} target
  41318. * Object specifying the property and value we are targeting
  41319. * @param {string} target.key
  41320. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  41321. * @param {number} target.value
  41322. * The value to target for the specified key.
  41323. * @return {Object}
  41324. * The sync-point nearest the target
  41325. */
  41326. ;
  41327. _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
  41328. var bestSyncPoint = syncPoints[0].syncPoint;
  41329. var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  41330. var bestStrategy = syncPoints[0].strategy;
  41331. for (var i = 1; i < syncPoints.length; i++) {
  41332. var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  41333. if (newDistance < bestDistance) {
  41334. bestDistance = newDistance;
  41335. bestSyncPoint = syncPoints[i].syncPoint;
  41336. bestStrategy = syncPoints[i].strategy;
  41337. }
  41338. }
  41339. 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 : '') + ']');
  41340. return bestSyncPoint;
  41341. }
  41342. /**
  41343. * Save any meta-data present on the segments when segments leave
  41344. * the live window to the playlist to allow for synchronization at the
  41345. * playlist level later.
  41346. *
  41347. * @param {Playlist} oldPlaylist - The previous active playlist
  41348. * @param {Playlist} newPlaylist - The updated and most current playlist
  41349. */
  41350. ;
  41351. _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  41352. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  41353. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  41354. videojs.log.warn("Not saving expired segment info. Media sequence gap " + mediaSequenceDiff + " is too large.");
  41355. return;
  41356. } // When a segment expires from the playlist and it has a start time
  41357. // save that information as a possible sync-point reference in future
  41358. for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
  41359. var lastRemovedSegment = oldPlaylist.segments[i];
  41360. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  41361. newPlaylist.syncInfo = {
  41362. mediaSequence: oldPlaylist.mediaSequence + i,
  41363. time: lastRemovedSegment.start
  41364. };
  41365. this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
  41366. this.trigger('syncinfoupdate');
  41367. break;
  41368. }
  41369. }
  41370. }
  41371. /**
  41372. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  41373. * before segments start to load.
  41374. *
  41375. * @param {Playlist} playlist - The currently active playlist
  41376. */
  41377. ;
  41378. _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
  41379. // It's possible for the playlist to be updated before playback starts, meaning time
  41380. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  41381. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  41382. // unless the mappings are cleared.
  41383. this.timelineToDatetimeMappings = {};
  41384. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  41385. var firstSegment = playlist.segments[0];
  41386. var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  41387. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  41388. }
  41389. }
  41390. /**
  41391. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  41392. * based on the latest timing information.
  41393. *
  41394. * @param {Object} options
  41395. * Options object
  41396. * @param {SegmentInfo} options.segmentInfo
  41397. * The current active request information
  41398. * @param {boolean} options.shouldSaveTimelineMapping
  41399. * If there's a timeline change, determines if the timeline mapping should be
  41400. * saved for timeline mapping and program date time mappings.
  41401. */
  41402. ;
  41403. _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
  41404. var segmentInfo = _ref.segmentInfo,
  41405. shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
  41406. var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  41407. var segment = segmentInfo.segment;
  41408. if (didCalculateSegmentTimeMapping) {
  41409. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  41410. // now with segment timing information
  41411. if (!segmentInfo.playlist.syncInfo) {
  41412. segmentInfo.playlist.syncInfo = {
  41413. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  41414. time: segment.start
  41415. };
  41416. }
  41417. }
  41418. var dateTime = segment.dateTimeObject;
  41419. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  41420. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  41421. }
  41422. };
  41423. _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
  41424. if (typeof this.timelines[timeline] === 'undefined') {
  41425. return null;
  41426. }
  41427. return this.timelines[timeline].time;
  41428. };
  41429. _proto.mappingForTimeline = function mappingForTimeline(timeline) {
  41430. if (typeof this.timelines[timeline] === 'undefined') {
  41431. return null;
  41432. }
  41433. return this.timelines[timeline].mapping;
  41434. }
  41435. /**
  41436. * Use the "media time" for a segment to generate a mapping to "display time" and
  41437. * save that display time to the segment.
  41438. *
  41439. * @private
  41440. * @param {SegmentInfo} segmentInfo
  41441. * The current active request information
  41442. * @param {Object} timingInfo
  41443. * The start and end time of the current segment in "media time"
  41444. * @param {boolean} shouldSaveTimelineMapping
  41445. * If there's a timeline change, determines if the timeline mapping should be
  41446. * saved in timelines.
  41447. * @return {boolean}
  41448. * Returns false if segment time mapping could not be calculated
  41449. */
  41450. ;
  41451. _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  41452. // TODO: remove side effects
  41453. var segment = segmentInfo.segment;
  41454. var part = segmentInfo.part;
  41455. var mappingObj = this.timelines[segmentInfo.timeline];
  41456. var start;
  41457. var end;
  41458. if (typeof segmentInfo.timestampOffset === 'number') {
  41459. mappingObj = {
  41460. time: segmentInfo.startOfSegment,
  41461. mapping: segmentInfo.startOfSegment - timingInfo.start
  41462. };
  41463. if (shouldSaveTimelineMapping) {
  41464. this.timelines[segmentInfo.timeline] = mappingObj;
  41465. this.trigger('timestampoffset');
  41466. this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
  41467. }
  41468. start = segmentInfo.startOfSegment;
  41469. end = timingInfo.end + mappingObj.mapping;
  41470. } else if (mappingObj) {
  41471. start = timingInfo.start + mappingObj.mapping;
  41472. end = timingInfo.end + mappingObj.mapping;
  41473. } else {
  41474. return false;
  41475. }
  41476. if (part) {
  41477. part.start = start;
  41478. part.end = end;
  41479. } // If we don't have a segment start yet or the start value we got
  41480. // is less than our current segment.start value, save a new start value.
  41481. // We have to do this because parts will have segment timing info saved
  41482. // multiple times and we want segment start to be the earliest part start
  41483. // value for that segment.
  41484. if (!segment.start || start < segment.start) {
  41485. segment.start = start;
  41486. }
  41487. segment.end = end;
  41488. return true;
  41489. }
  41490. /**
  41491. * Each time we have discontinuity in the playlist, attempt to calculate the location
  41492. * in display of the start of the discontinuity and save that. We also save an accuracy
  41493. * value so that we save values with the most accuracy (closest to 0.)
  41494. *
  41495. * @private
  41496. * @param {SegmentInfo} segmentInfo - The current active request information
  41497. */
  41498. ;
  41499. _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
  41500. var playlist = segmentInfo.playlist;
  41501. var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  41502. // the start of the range and it's accuracy is 0 (greater accuracy values
  41503. // mean more approximation)
  41504. if (segment.discontinuity) {
  41505. this.discontinuities[segment.timeline] = {
  41506. time: segment.start,
  41507. accuracy: 0
  41508. };
  41509. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  41510. // Search for future discontinuities that we can provide better timing
  41511. // information for and save that information for sync purposes
  41512. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  41513. var segmentIndex = playlist.discontinuityStarts[i];
  41514. var discontinuity = playlist.discontinuitySequence + i + 1;
  41515. var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  41516. var accuracy = Math.abs(mediaIndexDiff);
  41517. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  41518. var time = void 0;
  41519. if (mediaIndexDiff < 0) {
  41520. time = segment.start - sumDurations({
  41521. defaultDuration: playlist.targetDuration,
  41522. durationList: playlist.segments,
  41523. startIndex: segmentInfo.mediaIndex,
  41524. endIndex: segmentIndex
  41525. });
  41526. } else {
  41527. time = segment.end + sumDurations({
  41528. defaultDuration: playlist.targetDuration,
  41529. durationList: playlist.segments,
  41530. startIndex: segmentInfo.mediaIndex + 1,
  41531. endIndex: segmentIndex
  41532. });
  41533. }
  41534. this.discontinuities[discontinuity] = {
  41535. time: time,
  41536. accuracy: accuracy
  41537. };
  41538. }
  41539. }
  41540. }
  41541. };
  41542. _proto.dispose = function dispose() {
  41543. this.trigger('dispose');
  41544. this.off();
  41545. };
  41546. return SyncController;
  41547. }(videojs.EventTarget);
  41548. /**
  41549. * The TimelineChangeController acts as a source for segment loaders to listen for and
  41550. * keep track of latest and pending timeline changes. This is useful to ensure proper
  41551. * sync, as each loader may need to make a consideration for what timeline the other
  41552. * loader is on before making changes which could impact the other loader's media.
  41553. *
  41554. * @class TimelineChangeController
  41555. * @extends videojs.EventTarget
  41556. */
  41557. var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
  41558. _inheritsLoose__default['default'](TimelineChangeController, _videojs$EventTarget);
  41559. function TimelineChangeController() {
  41560. var _this;
  41561. _this = _videojs$EventTarget.call(this) || this;
  41562. _this.pendingTimelineChanges_ = {};
  41563. _this.lastTimelineChanges_ = {};
  41564. return _this;
  41565. }
  41566. var _proto = TimelineChangeController.prototype;
  41567. _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
  41568. this.pendingTimelineChanges_[type] = null;
  41569. this.trigger('pendingtimelinechange');
  41570. };
  41571. _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
  41572. var type = _ref.type,
  41573. from = _ref.from,
  41574. to = _ref.to;
  41575. if (typeof from === 'number' && typeof to === 'number') {
  41576. this.pendingTimelineChanges_[type] = {
  41577. type: type,
  41578. from: from,
  41579. to: to
  41580. };
  41581. this.trigger('pendingtimelinechange');
  41582. }
  41583. return this.pendingTimelineChanges_[type];
  41584. };
  41585. _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
  41586. var type = _ref2.type,
  41587. from = _ref2.from,
  41588. to = _ref2.to;
  41589. if (typeof from === 'number' && typeof to === 'number') {
  41590. this.lastTimelineChanges_[type] = {
  41591. type: type,
  41592. from: from,
  41593. to: to
  41594. };
  41595. delete this.pendingTimelineChanges_[type];
  41596. this.trigger('timelinechange');
  41597. }
  41598. return this.lastTimelineChanges_[type];
  41599. };
  41600. _proto.dispose = function dispose() {
  41601. this.trigger('dispose');
  41602. this.pendingTimelineChanges_ = {};
  41603. this.lastTimelineChanges_ = {};
  41604. this.off();
  41605. };
  41606. return TimelineChangeController;
  41607. }(videojs.EventTarget);
  41608. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  41609. var workerCode = transform(getWorkerString(function () {
  41610. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  41611. function createCommonjsModule(fn, basedir, module) {
  41612. return module = {
  41613. path: basedir,
  41614. exports: {},
  41615. require: function require(path, base) {
  41616. return commonjsRequire(path, base === undefined || base === null ? module.path : base);
  41617. }
  41618. }, fn(module, module.exports), module.exports;
  41619. }
  41620. function commonjsRequire() {
  41621. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  41622. }
  41623. var createClass = createCommonjsModule(function (module) {
  41624. function _defineProperties(target, props) {
  41625. for (var i = 0; i < props.length; i++) {
  41626. var descriptor = props[i];
  41627. descriptor.enumerable = descriptor.enumerable || false;
  41628. descriptor.configurable = true;
  41629. if ("value" in descriptor) descriptor.writable = true;
  41630. Object.defineProperty(target, descriptor.key, descriptor);
  41631. }
  41632. }
  41633. function _createClass(Constructor, protoProps, staticProps) {
  41634. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  41635. if (staticProps) _defineProperties(Constructor, staticProps);
  41636. return Constructor;
  41637. }
  41638. module.exports = _createClass;
  41639. module.exports["default"] = module.exports, module.exports.__esModule = true;
  41640. });
  41641. var setPrototypeOf = createCommonjsModule(function (module) {
  41642. function _setPrototypeOf(o, p) {
  41643. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  41644. o.__proto__ = p;
  41645. return o;
  41646. };
  41647. module.exports["default"] = module.exports, module.exports.__esModule = true;
  41648. return _setPrototypeOf(o, p);
  41649. }
  41650. module.exports = _setPrototypeOf;
  41651. module.exports["default"] = module.exports, module.exports.__esModule = true;
  41652. });
  41653. var inheritsLoose = createCommonjsModule(function (module) {
  41654. function _inheritsLoose(subClass, superClass) {
  41655. subClass.prototype = Object.create(superClass.prototype);
  41656. subClass.prototype.constructor = subClass;
  41657. setPrototypeOf(subClass, superClass);
  41658. }
  41659. module.exports = _inheritsLoose;
  41660. module.exports["default"] = module.exports, module.exports.__esModule = true;
  41661. });
  41662. /**
  41663. * @file stream.js
  41664. */
  41665. /**
  41666. * A lightweight readable stream implemention that handles event dispatching.
  41667. *
  41668. * @class Stream
  41669. */
  41670. var Stream = /*#__PURE__*/function () {
  41671. function Stream() {
  41672. this.listeners = {};
  41673. }
  41674. /**
  41675. * Add a listener for a specified event type.
  41676. *
  41677. * @param {string} type the event name
  41678. * @param {Function} listener the callback to be invoked when an event of
  41679. * the specified type occurs
  41680. */
  41681. var _proto = Stream.prototype;
  41682. _proto.on = function on(type, listener) {
  41683. if (!this.listeners[type]) {
  41684. this.listeners[type] = [];
  41685. }
  41686. this.listeners[type].push(listener);
  41687. }
  41688. /**
  41689. * Remove a listener for a specified event type.
  41690. *
  41691. * @param {string} type the event name
  41692. * @param {Function} listener a function previously registered for this
  41693. * type of event through `on`
  41694. * @return {boolean} if we could turn it off or not
  41695. */
  41696. ;
  41697. _proto.off = function off(type, listener) {
  41698. if (!this.listeners[type]) {
  41699. return false;
  41700. }
  41701. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  41702. // In Video.js we slice listener functions
  41703. // on trigger so that it does not mess up the order
  41704. // while we loop through.
  41705. //
  41706. // Here we slice on off so that the loop in trigger
  41707. // can continue using it's old reference to loop without
  41708. // messing up the order.
  41709. this.listeners[type] = this.listeners[type].slice(0);
  41710. this.listeners[type].splice(index, 1);
  41711. return index > -1;
  41712. }
  41713. /**
  41714. * Trigger an event of the specified type on this stream. Any additional
  41715. * arguments to this function are passed as parameters to event listeners.
  41716. *
  41717. * @param {string} type the event name
  41718. */
  41719. ;
  41720. _proto.trigger = function trigger(type) {
  41721. var callbacks = this.listeners[type];
  41722. if (!callbacks) {
  41723. return;
  41724. } // Slicing the arguments on every invocation of this method
  41725. // can add a significant amount of overhead. Avoid the
  41726. // intermediate object creation for the common case of a
  41727. // single callback argument
  41728. if (arguments.length === 2) {
  41729. var length = callbacks.length;
  41730. for (var i = 0; i < length; ++i) {
  41731. callbacks[i].call(this, arguments[1]);
  41732. }
  41733. } else {
  41734. var args = Array.prototype.slice.call(arguments, 1);
  41735. var _length = callbacks.length;
  41736. for (var _i = 0; _i < _length; ++_i) {
  41737. callbacks[_i].apply(this, args);
  41738. }
  41739. }
  41740. }
  41741. /**
  41742. * Destroys the stream and cleans up.
  41743. */
  41744. ;
  41745. _proto.dispose = function dispose() {
  41746. this.listeners = {};
  41747. }
  41748. /**
  41749. * Forwards all `data` events on this stream to the destination stream. The
  41750. * destination stream should provide a method `push` to receive the data
  41751. * events as they arrive.
  41752. *
  41753. * @param {Stream} destination the stream that will receive all `data` events
  41754. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  41755. */
  41756. ;
  41757. _proto.pipe = function pipe(destination) {
  41758. this.on('data', function (data) {
  41759. destination.push(data);
  41760. });
  41761. };
  41762. return Stream;
  41763. }();
  41764. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  41765. /**
  41766. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  41767. *
  41768. * @param padded {Uint8Array} unencrypted bytes that have been padded
  41769. * @return {Uint8Array} the unpadded bytes
  41770. * @see http://tools.ietf.org/html/rfc5652
  41771. */
  41772. function unpad(padded) {
  41773. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  41774. }
  41775. /*! @name aes-decrypter @version 3.1.3 @license Apache-2.0 */
  41776. /**
  41777. * @file aes.js
  41778. *
  41779. * This file contains an adaptation of the AES decryption algorithm
  41780. * from the Standford Javascript Cryptography Library. That work is
  41781. * covered by the following copyright and permissions notice:
  41782. *
  41783. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  41784. * All rights reserved.
  41785. *
  41786. * Redistribution and use in source and binary forms, with or without
  41787. * modification, are permitted provided that the following conditions are
  41788. * met:
  41789. *
  41790. * 1. Redistributions of source code must retain the above copyright
  41791. * notice, this list of conditions and the following disclaimer.
  41792. *
  41793. * 2. Redistributions in binary form must reproduce the above
  41794. * copyright notice, this list of conditions and the following
  41795. * disclaimer in the documentation and/or other materials provided
  41796. * with the distribution.
  41797. *
  41798. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  41799. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  41800. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  41801. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  41802. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  41803. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  41804. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  41805. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  41806. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  41807. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  41808. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41809. *
  41810. * The views and conclusions contained in the software and documentation
  41811. * are those of the authors and should not be interpreted as representing
  41812. * official policies, either expressed or implied, of the authors.
  41813. */
  41814. /**
  41815. * Expand the S-box tables.
  41816. *
  41817. * @private
  41818. */
  41819. var precompute = function precompute() {
  41820. var tables = [[[], [], [], [], []], [[], [], [], [], []]];
  41821. var encTable = tables[0];
  41822. var decTable = tables[1];
  41823. var sbox = encTable[4];
  41824. var sboxInv = decTable[4];
  41825. var i;
  41826. var x;
  41827. var xInv;
  41828. var d = [];
  41829. var th = [];
  41830. var x2;
  41831. var x4;
  41832. var x8;
  41833. var s;
  41834. var tEnc;
  41835. var tDec; // Compute double and third tables
  41836. for (i = 0; i < 256; i++) {
  41837. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  41838. }
  41839. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  41840. // Compute sbox
  41841. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  41842. s = s >> 8 ^ s & 255 ^ 99;
  41843. sbox[x] = s;
  41844. sboxInv[s] = x; // Compute MixColumns
  41845. x8 = d[x4 = d[x2 = d[x]]];
  41846. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  41847. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  41848. for (i = 0; i < 4; i++) {
  41849. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  41850. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  41851. }
  41852. } // Compactify. Considerable speedup on Firefox.
  41853. for (i = 0; i < 5; i++) {
  41854. encTable[i] = encTable[i].slice(0);
  41855. decTable[i] = decTable[i].slice(0);
  41856. }
  41857. return tables;
  41858. };
  41859. var aesTables = null;
  41860. /**
  41861. * Schedule out an AES key for both encryption and decryption. This
  41862. * is a low-level class. Use a cipher mode to do bulk encryption.
  41863. *
  41864. * @class AES
  41865. * @param key {Array} The key as an array of 4, 6 or 8 words.
  41866. */
  41867. var AES = /*#__PURE__*/function () {
  41868. function AES(key) {
  41869. /**
  41870. * The expanded S-box and inverse S-box tables. These will be computed
  41871. * on the client so that we don't have to send them down the wire.
  41872. *
  41873. * There are two tables, _tables[0] is for encryption and
  41874. * _tables[1] is for decryption.
  41875. *
  41876. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  41877. * last (_tables[01][4]) is the S-box itself.
  41878. *
  41879. * @private
  41880. */
  41881. // if we have yet to precompute the S-box tables
  41882. // do so now
  41883. if (!aesTables) {
  41884. aesTables = precompute();
  41885. } // then make a copy of that object for use
  41886. 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()]];
  41887. var i;
  41888. var j;
  41889. var tmp;
  41890. var sbox = this._tables[0][4];
  41891. var decTable = this._tables[1];
  41892. var keyLen = key.length;
  41893. var rcon = 1;
  41894. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  41895. throw new Error('Invalid aes key size');
  41896. }
  41897. var encKey = key.slice(0);
  41898. var decKey = [];
  41899. this._key = [encKey, decKey]; // schedule encryption keys
  41900. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  41901. tmp = encKey[i - 1]; // apply sbox
  41902. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  41903. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  41904. if (i % keyLen === 0) {
  41905. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  41906. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  41907. }
  41908. }
  41909. encKey[i] = encKey[i - keyLen] ^ tmp;
  41910. } // schedule decryption keys
  41911. for (j = 0; i; j++, i--) {
  41912. tmp = encKey[j & 3 ? i : i - 4];
  41913. if (i <= 4 || j < 4) {
  41914. decKey[j] = tmp;
  41915. } else {
  41916. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  41917. }
  41918. }
  41919. }
  41920. /**
  41921. * Decrypt 16 bytes, specified as four 32-bit words.
  41922. *
  41923. * @param {number} encrypted0 the first word to decrypt
  41924. * @param {number} encrypted1 the second word to decrypt
  41925. * @param {number} encrypted2 the third word to decrypt
  41926. * @param {number} encrypted3 the fourth word to decrypt
  41927. * @param {Int32Array} out the array to write the decrypted words
  41928. * into
  41929. * @param {number} offset the offset into the output array to start
  41930. * writing results
  41931. * @return {Array} The plaintext.
  41932. */
  41933. var _proto = AES.prototype;
  41934. _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  41935. var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  41936. var a = encrypted0 ^ key[0];
  41937. var b = encrypted3 ^ key[1];
  41938. var c = encrypted2 ^ key[2];
  41939. var d = encrypted1 ^ key[3];
  41940. var a2;
  41941. var b2;
  41942. var c2; // key.length === 2 ?
  41943. var nInnerRounds = key.length / 4 - 2;
  41944. var i;
  41945. var kIndex = 4;
  41946. var table = this._tables[1]; // load up the tables
  41947. var table0 = table[0];
  41948. var table1 = table[1];
  41949. var table2 = table[2];
  41950. var table3 = table[3];
  41951. var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  41952. for (i = 0; i < nInnerRounds; i++) {
  41953. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  41954. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  41955. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  41956. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  41957. kIndex += 4;
  41958. a = a2;
  41959. b = b2;
  41960. c = c2;
  41961. } // Last round.
  41962. for (i = 0; i < 4; i++) {
  41963. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  41964. a2 = a;
  41965. a = b;
  41966. b = c;
  41967. c = d;
  41968. d = a2;
  41969. }
  41970. };
  41971. return AES;
  41972. }();
  41973. /**
  41974. * A wrapper around the Stream class to use setTimeout
  41975. * and run stream "jobs" Asynchronously
  41976. *
  41977. * @class AsyncStream
  41978. * @extends Stream
  41979. */
  41980. var AsyncStream = /*#__PURE__*/function (_Stream) {
  41981. inheritsLoose(AsyncStream, _Stream);
  41982. function AsyncStream() {
  41983. var _this;
  41984. _this = _Stream.call(this, Stream) || this;
  41985. _this.jobs = [];
  41986. _this.delay = 1;
  41987. _this.timeout_ = null;
  41988. return _this;
  41989. }
  41990. /**
  41991. * process an async job
  41992. *
  41993. * @private
  41994. */
  41995. var _proto = AsyncStream.prototype;
  41996. _proto.processJob_ = function processJob_() {
  41997. this.jobs.shift()();
  41998. if (this.jobs.length) {
  41999. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42000. } else {
  42001. this.timeout_ = null;
  42002. }
  42003. }
  42004. /**
  42005. * push a job into the stream
  42006. *
  42007. * @param {Function} job the job to push into the stream
  42008. */
  42009. ;
  42010. _proto.push = function push(job) {
  42011. this.jobs.push(job);
  42012. if (!this.timeout_) {
  42013. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  42014. }
  42015. };
  42016. return AsyncStream;
  42017. }(Stream);
  42018. /**
  42019. * Convert network-order (big-endian) bytes into their little-endian
  42020. * representation.
  42021. */
  42022. var ntoh = function ntoh(word) {
  42023. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  42024. };
  42025. /**
  42026. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  42027. *
  42028. * @param {Uint8Array} encrypted the encrypted bytes
  42029. * @param {Uint32Array} key the bytes of the decryption key
  42030. * @param {Uint32Array} initVector the initialization vector (IV) to
  42031. * use for the first round of CBC.
  42032. * @return {Uint8Array} the decrypted bytes
  42033. *
  42034. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  42035. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  42036. * @see https://tools.ietf.org/html/rfc2315
  42037. */
  42038. var decrypt = function decrypt(encrypted, key, initVector) {
  42039. // word-level access to the encrypted bytes
  42040. var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  42041. var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  42042. var decrypted = new Uint8Array(encrypted.byteLength);
  42043. var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  42044. // decrypted data
  42045. var init0;
  42046. var init1;
  42047. var init2;
  42048. var init3;
  42049. var encrypted0;
  42050. var encrypted1;
  42051. var encrypted2;
  42052. var encrypted3; // iteration variable
  42053. var wordIx; // pull out the words of the IV to ensure we don't modify the
  42054. // passed-in reference and easier access
  42055. init0 = initVector[0];
  42056. init1 = initVector[1];
  42057. init2 = initVector[2];
  42058. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  42059. // to each decrypted block
  42060. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  42061. // convert big-endian (network order) words into little-endian
  42062. // (javascript order)
  42063. encrypted0 = ntoh(encrypted32[wordIx]);
  42064. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  42065. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  42066. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  42067. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  42068. // plaintext
  42069. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  42070. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  42071. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  42072. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  42073. init0 = encrypted0;
  42074. init1 = encrypted1;
  42075. init2 = encrypted2;
  42076. init3 = encrypted3;
  42077. }
  42078. return decrypted;
  42079. };
  42080. /**
  42081. * The `Decrypter` class that manages decryption of AES
  42082. * data through `AsyncStream` objects and the `decrypt`
  42083. * function
  42084. *
  42085. * @param {Uint8Array} encrypted the encrypted bytes
  42086. * @param {Uint32Array} key the bytes of the decryption key
  42087. * @param {Uint32Array} initVector the initialization vector (IV) to
  42088. * @param {Function} done the function to run when done
  42089. * @class Decrypter
  42090. */
  42091. var Decrypter = /*#__PURE__*/function () {
  42092. function Decrypter(encrypted, key, initVector, done) {
  42093. var step = Decrypter.STEP;
  42094. var encrypted32 = new Int32Array(encrypted.buffer);
  42095. var decrypted = new Uint8Array(encrypted.byteLength);
  42096. var i = 0;
  42097. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  42098. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42099. for (i = step; i < encrypted32.length; i += step) {
  42100. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  42101. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  42102. } // invoke the done() callback when everything is finished
  42103. this.asyncStream_.push(function () {
  42104. // remove pkcs#7 padding from the decrypted bytes
  42105. done(null, unpad(decrypted));
  42106. });
  42107. }
  42108. /**
  42109. * a getter for step the maximum number of bytes to process at one time
  42110. *
  42111. * @return {number} the value of step 32000
  42112. */
  42113. var _proto = Decrypter.prototype;
  42114. /**
  42115. * @private
  42116. */
  42117. _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
  42118. return function () {
  42119. var bytes = decrypt(encrypted, key, initVector);
  42120. decrypted.set(bytes, encrypted.byteOffset);
  42121. };
  42122. };
  42123. createClass(Decrypter, null, [{
  42124. key: "STEP",
  42125. get: function get() {
  42126. // 4 * 8000;
  42127. return 32000;
  42128. }
  42129. }]);
  42130. return Decrypter;
  42131. }();
  42132. var win;
  42133. if (typeof window !== "undefined") {
  42134. win = window;
  42135. } else if (typeof commonjsGlobal !== "undefined") {
  42136. win = commonjsGlobal;
  42137. } else if (typeof self !== "undefined") {
  42138. win = self;
  42139. } else {
  42140. win = {};
  42141. }
  42142. var window_1 = win;
  42143. var isArrayBufferView = function isArrayBufferView(obj) {
  42144. if (ArrayBuffer.isView === 'function') {
  42145. return ArrayBuffer.isView(obj);
  42146. }
  42147. return obj && obj.buffer instanceof ArrayBuffer;
  42148. };
  42149. var BigInt = window_1.BigInt || Number;
  42150. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  42151. /**
  42152. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  42153. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  42154. *
  42155. * @param {Object} message
  42156. * Object of properties and values to send to the web worker
  42157. * @return {Object}
  42158. * Modified message with TypedArray values expanded
  42159. * @function createTransferableMessage
  42160. */
  42161. var createTransferableMessage = function createTransferableMessage(message) {
  42162. var transferable = {};
  42163. Object.keys(message).forEach(function (key) {
  42164. var value = message[key];
  42165. if (isArrayBufferView(value)) {
  42166. transferable[key] = {
  42167. bytes: value.buffer,
  42168. byteOffset: value.byteOffset,
  42169. byteLength: value.byteLength
  42170. };
  42171. } else {
  42172. transferable[key] = value;
  42173. }
  42174. });
  42175. return transferable;
  42176. };
  42177. /* global self */
  42178. /**
  42179. * Our web worker interface so that things can talk to aes-decrypter
  42180. * that will be running in a web worker. the scope is passed to this by
  42181. * webworkify.
  42182. */
  42183. self.onmessage = function (event) {
  42184. var data = event.data;
  42185. var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  42186. var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  42187. var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  42188. /* eslint-disable no-new, handle-callback-err */
  42189. new Decrypter(encrypted, key, iv, function (err, bytes) {
  42190. self.postMessage(createTransferableMessage({
  42191. source: data.source,
  42192. decrypted: bytes
  42193. }), [bytes.buffer]);
  42194. });
  42195. /* eslint-enable */
  42196. };
  42197. }));
  42198. var Decrypter = factory(workerCode);
  42199. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  42200. /**
  42201. * Convert the properties of an HLS track into an audioTrackKind.
  42202. *
  42203. * @private
  42204. */
  42205. var audioTrackKind_ = function audioTrackKind_(properties) {
  42206. var kind = properties["default"] ? 'main' : 'alternative';
  42207. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  42208. kind = 'main-desc';
  42209. }
  42210. return kind;
  42211. };
  42212. /**
  42213. * Pause provided segment loader and playlist loader if active
  42214. *
  42215. * @param {SegmentLoader} segmentLoader
  42216. * SegmentLoader to pause
  42217. * @param {Object} mediaType
  42218. * Active media type
  42219. * @function stopLoaders
  42220. */
  42221. var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
  42222. segmentLoader.abort();
  42223. segmentLoader.pause();
  42224. if (mediaType && mediaType.activePlaylistLoader) {
  42225. mediaType.activePlaylistLoader.pause();
  42226. mediaType.activePlaylistLoader = null;
  42227. }
  42228. };
  42229. /**
  42230. * Start loading provided segment loader and playlist loader
  42231. *
  42232. * @param {PlaylistLoader} playlistLoader
  42233. * PlaylistLoader to start loading
  42234. * @param {Object} mediaType
  42235. * Active media type
  42236. * @function startLoaders
  42237. */
  42238. var startLoaders = function startLoaders(playlistLoader, mediaType) {
  42239. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  42240. // playlist loader
  42241. mediaType.activePlaylistLoader = playlistLoader;
  42242. playlistLoader.load();
  42243. };
  42244. /**
  42245. * Returns a function to be called when the media group changes. It performs a
  42246. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  42247. * change of group is merely a rendition switch of the same content at another encoding,
  42248. * rather than a change of content, such as switching audio from English to Spanish.
  42249. *
  42250. * @param {string} type
  42251. * MediaGroup type
  42252. * @param {Object} settings
  42253. * Object containing required information for media groups
  42254. * @return {Function}
  42255. * Handler for a non-destructive resync of SegmentLoader when the active media
  42256. * group changes.
  42257. * @function onGroupChanged
  42258. */
  42259. var onGroupChanged = function onGroupChanged(type, settings) {
  42260. return function () {
  42261. var _settings$segmentLoad = settings.segmentLoaders,
  42262. segmentLoader = _settings$segmentLoad[type],
  42263. mainSegmentLoader = _settings$segmentLoad.main,
  42264. mediaType = settings.mediaTypes[type];
  42265. var activeTrack = mediaType.activeTrack();
  42266. var activeGroup = mediaType.getActiveGroup();
  42267. var previousActiveLoader = mediaType.activePlaylistLoader;
  42268. var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  42269. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  42270. return;
  42271. }
  42272. mediaType.lastGroup_ = activeGroup;
  42273. mediaType.lastTrack_ = activeTrack;
  42274. stopLoaders(segmentLoader, mediaType);
  42275. if (!activeGroup || activeGroup.isMasterPlaylist) {
  42276. // there is no group active or active group is a main playlist and won't change
  42277. return;
  42278. }
  42279. if (!activeGroup.playlistLoader) {
  42280. if (previousActiveLoader) {
  42281. // The previous group had a playlist loader but the new active group does not
  42282. // this means we are switching from demuxed to muxed audio. In this case we want to
  42283. // do a destructive reset of the main segment loader and not restart the audio
  42284. // loaders.
  42285. mainSegmentLoader.resetEverything();
  42286. }
  42287. return;
  42288. } // Non-destructive resync
  42289. segmentLoader.resyncLoader();
  42290. startLoaders(activeGroup.playlistLoader, mediaType);
  42291. };
  42292. };
  42293. var onGroupChanging = function onGroupChanging(type, settings) {
  42294. return function () {
  42295. var segmentLoader = settings.segmentLoaders[type],
  42296. mediaType = settings.mediaTypes[type];
  42297. mediaType.lastGroup_ = null;
  42298. segmentLoader.abort();
  42299. segmentLoader.pause();
  42300. };
  42301. };
  42302. /**
  42303. * Returns a function to be called when the media track changes. It performs a
  42304. * destructive reset of the SegmentLoader to ensure we start loading as close to
  42305. * currentTime as possible.
  42306. *
  42307. * @param {string} type
  42308. * MediaGroup type
  42309. * @param {Object} settings
  42310. * Object containing required information for media groups
  42311. * @return {Function}
  42312. * Handler for a destructive reset of SegmentLoader when the active media
  42313. * track changes.
  42314. * @function onTrackChanged
  42315. */
  42316. var onTrackChanged = function onTrackChanged(type, settings) {
  42317. return function () {
  42318. var masterPlaylistLoader = settings.masterPlaylistLoader,
  42319. _settings$segmentLoad2 = settings.segmentLoaders,
  42320. segmentLoader = _settings$segmentLoad2[type],
  42321. mainSegmentLoader = _settings$segmentLoad2.main,
  42322. mediaType = settings.mediaTypes[type];
  42323. var activeTrack = mediaType.activeTrack();
  42324. var activeGroup = mediaType.getActiveGroup();
  42325. var previousActiveLoader = mediaType.activePlaylistLoader;
  42326. var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  42327. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  42328. return;
  42329. }
  42330. mediaType.lastGroup_ = activeGroup;
  42331. mediaType.lastTrack_ = activeTrack;
  42332. stopLoaders(segmentLoader, mediaType);
  42333. if (!activeGroup) {
  42334. // there is no group active so we do not want to restart loaders
  42335. return;
  42336. }
  42337. if (activeGroup.isMasterPlaylist) {
  42338. // track did not change, do nothing
  42339. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  42340. return;
  42341. }
  42342. var mpc = settings.vhs.masterPlaylistController_;
  42343. var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
  42344. if (mpc.media() === newPlaylist) {
  42345. return;
  42346. }
  42347. mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
  42348. masterPlaylistLoader.pause();
  42349. mainSegmentLoader.resetEverything();
  42350. mpc.fastQualityChange_(newPlaylist);
  42351. return;
  42352. }
  42353. if (type === 'AUDIO') {
  42354. if (!activeGroup.playlistLoader) {
  42355. // when switching from demuxed audio/video to muxed audio/video (noted by no
  42356. // playlist loader for the audio group), we want to do a destructive reset of the
  42357. // main segment loader and not restart the audio loaders
  42358. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  42359. // it should be stopped
  42360. mainSegmentLoader.resetEverything();
  42361. return;
  42362. } // although the segment loader is an audio segment loader, call the setAudio
  42363. // function to ensure it is prepared to re-append the init segment (or handle other
  42364. // config changes)
  42365. segmentLoader.setAudio(true);
  42366. mainSegmentLoader.setAudio(false);
  42367. }
  42368. if (previousActiveLoader === activeGroup.playlistLoader) {
  42369. // Nothing has actually changed. This can happen because track change events can fire
  42370. // multiple times for a "single" change. One for enabling the new active track, and
  42371. // one for disabling the track that was active
  42372. startLoaders(activeGroup.playlistLoader, mediaType);
  42373. return;
  42374. }
  42375. if (segmentLoader.track) {
  42376. // For WebVTT, set the new text track in the segmentloader
  42377. segmentLoader.track(activeTrack);
  42378. } // destructive reset
  42379. segmentLoader.resetEverything();
  42380. startLoaders(activeGroup.playlistLoader, mediaType);
  42381. };
  42382. };
  42383. var onError = {
  42384. /**
  42385. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42386. * an error.
  42387. *
  42388. * @param {string} type
  42389. * MediaGroup type
  42390. * @param {Object} settings
  42391. * Object containing required information for media groups
  42392. * @return {Function}
  42393. * Error handler. Logs warning (or error if the playlist is blacklisted) to
  42394. * console and switches back to default audio track.
  42395. * @function onError.AUDIO
  42396. */
  42397. AUDIO: function AUDIO(type, settings) {
  42398. return function () {
  42399. var segmentLoader = settings.segmentLoaders[type],
  42400. mediaType = settings.mediaTypes[type],
  42401. blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
  42402. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  42403. var activeTrack = mediaType.activeTrack();
  42404. var activeGroup = mediaType.activeGroup();
  42405. var id = (activeGroup.filter(function (group) {
  42406. return group["default"];
  42407. })[0] || activeGroup[0]).id;
  42408. var defaultTrack = mediaType.tracks[id];
  42409. if (activeTrack === defaultTrack) {
  42410. // Default track encountered an error. All we can do now is blacklist the current
  42411. // rendition and hope another will switch audio groups
  42412. blacklistCurrentPlaylist({
  42413. message: 'Problem encountered loading the default audio track.'
  42414. });
  42415. return;
  42416. }
  42417. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  42418. for (var trackId in mediaType.tracks) {
  42419. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  42420. }
  42421. mediaType.onTrackChanged();
  42422. };
  42423. },
  42424. /**
  42425. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  42426. * an error.
  42427. *
  42428. * @param {string} type
  42429. * MediaGroup type
  42430. * @param {Object} settings
  42431. * Object containing required information for media groups
  42432. * @return {Function}
  42433. * Error handler. Logs warning to console and disables the active subtitle track
  42434. * @function onError.SUBTITLES
  42435. */
  42436. SUBTITLES: function SUBTITLES(type, settings) {
  42437. return function () {
  42438. var segmentLoader = settings.segmentLoaders[type],
  42439. mediaType = settings.mediaTypes[type];
  42440. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  42441. stopLoaders(segmentLoader, mediaType);
  42442. var track = mediaType.activeTrack();
  42443. if (track) {
  42444. track.mode = 'disabled';
  42445. }
  42446. mediaType.onTrackChanged();
  42447. };
  42448. }
  42449. };
  42450. var setupListeners = {
  42451. /**
  42452. * Setup event listeners for audio playlist loader
  42453. *
  42454. * @param {string} type
  42455. * MediaGroup type
  42456. * @param {PlaylistLoader|null} playlistLoader
  42457. * PlaylistLoader to register listeners on
  42458. * @param {Object} settings
  42459. * Object containing required information for media groups
  42460. * @function setupListeners.AUDIO
  42461. */
  42462. AUDIO: function AUDIO(type, playlistLoader, settings) {
  42463. if (!playlistLoader) {
  42464. // no playlist loader means audio will be muxed with the video
  42465. return;
  42466. }
  42467. var tech = settings.tech,
  42468. requestOptions = settings.requestOptions,
  42469. segmentLoader = settings.segmentLoaders[type];
  42470. playlistLoader.on('loadedmetadata', function () {
  42471. var media = playlistLoader.media();
  42472. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  42473. // permits, start downloading segments
  42474. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42475. segmentLoader.load();
  42476. }
  42477. });
  42478. playlistLoader.on('loadedplaylist', function () {
  42479. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42480. if (!tech.paused()) {
  42481. segmentLoader.load();
  42482. }
  42483. });
  42484. playlistLoader.on('error', onError[type](type, settings));
  42485. },
  42486. /**
  42487. * Setup event listeners for subtitle playlist loader
  42488. *
  42489. * @param {string} type
  42490. * MediaGroup type
  42491. * @param {PlaylistLoader|null} playlistLoader
  42492. * PlaylistLoader to register listeners on
  42493. * @param {Object} settings
  42494. * Object containing required information for media groups
  42495. * @function setupListeners.SUBTITLES
  42496. */
  42497. SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
  42498. var tech = settings.tech,
  42499. requestOptions = settings.requestOptions,
  42500. segmentLoader = settings.segmentLoaders[type],
  42501. mediaType = settings.mediaTypes[type];
  42502. playlistLoader.on('loadedmetadata', function () {
  42503. var media = playlistLoader.media();
  42504. segmentLoader.playlist(media, requestOptions);
  42505. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  42506. // permits, start downloading segments
  42507. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  42508. segmentLoader.load();
  42509. }
  42510. });
  42511. playlistLoader.on('loadedplaylist', function () {
  42512. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  42513. if (!tech.paused()) {
  42514. segmentLoader.load();
  42515. }
  42516. });
  42517. playlistLoader.on('error', onError[type](type, settings));
  42518. }
  42519. };
  42520. var initialize = {
  42521. /**
  42522. * Setup PlaylistLoaders and AudioTracks for the audio groups
  42523. *
  42524. * @param {string} type
  42525. * MediaGroup type
  42526. * @param {Object} settings
  42527. * Object containing required information for media groups
  42528. * @function initialize.AUDIO
  42529. */
  42530. 'AUDIO': function AUDIO(type, settings) {
  42531. var vhs = settings.vhs,
  42532. sourceType = settings.sourceType,
  42533. segmentLoader = settings.segmentLoaders[type],
  42534. requestOptions = settings.requestOptions,
  42535. mediaGroups = settings.master.mediaGroups,
  42536. _settings$mediaTypes$ = settings.mediaTypes[type],
  42537. groups = _settings$mediaTypes$.groups,
  42538. tracks = _settings$mediaTypes$.tracks,
  42539. logger_ = _settings$mediaTypes$.logger_,
  42540. masterPlaylistLoader = settings.masterPlaylistLoader;
  42541. var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
  42542. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  42543. mediaGroups[type] = {
  42544. main: {
  42545. "default": {
  42546. "default": true
  42547. }
  42548. }
  42549. };
  42550. if (audioOnlyMaster) {
  42551. mediaGroups[type].main["default"].playlists = masterPlaylistLoader.master.playlists;
  42552. }
  42553. }
  42554. for (var groupId in mediaGroups[type]) {
  42555. if (!groups[groupId]) {
  42556. groups[groupId] = [];
  42557. }
  42558. for (var variantLabel in mediaGroups[type][groupId]) {
  42559. var properties = mediaGroups[type][groupId][variantLabel];
  42560. var playlistLoader = void 0;
  42561. if (audioOnlyMaster) {
  42562. logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
  42563. properties.isMasterPlaylist = true;
  42564. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  42565. // use the resolved media playlist object
  42566. } else if (sourceType === 'vhs-json' && properties.playlists) {
  42567. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  42568. } else if (properties.resolvedUri) {
  42569. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  42570. // should we even have properties.playlists in this check.
  42571. } else if (properties.playlists && sourceType === 'dash') {
  42572. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  42573. } else {
  42574. // no resolvedUri means the audio is muxed with the video when using this
  42575. // audio track
  42576. playlistLoader = null;
  42577. }
  42578. properties = videojs.mergeOptions({
  42579. id: variantLabel,
  42580. playlistLoader: playlistLoader
  42581. }, properties);
  42582. setupListeners[type](type, properties.playlistLoader, settings);
  42583. groups[groupId].push(properties);
  42584. if (typeof tracks[variantLabel] === 'undefined') {
  42585. var track = new videojs.AudioTrack({
  42586. id: variantLabel,
  42587. kind: audioTrackKind_(properties),
  42588. enabled: false,
  42589. language: properties.language,
  42590. "default": properties["default"],
  42591. label: variantLabel
  42592. });
  42593. tracks[variantLabel] = track;
  42594. }
  42595. }
  42596. } // setup single error event handler for the segment loader
  42597. segmentLoader.on('error', onError[type](type, settings));
  42598. },
  42599. /**
  42600. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  42601. *
  42602. * @param {string} type
  42603. * MediaGroup type
  42604. * @param {Object} settings
  42605. * Object containing required information for media groups
  42606. * @function initialize.SUBTITLES
  42607. */
  42608. 'SUBTITLES': function SUBTITLES(type, settings) {
  42609. var tech = settings.tech,
  42610. vhs = settings.vhs,
  42611. sourceType = settings.sourceType,
  42612. segmentLoader = settings.segmentLoaders[type],
  42613. requestOptions = settings.requestOptions,
  42614. mediaGroups = settings.master.mediaGroups,
  42615. _settings$mediaTypes$2 = settings.mediaTypes[type],
  42616. groups = _settings$mediaTypes$2.groups,
  42617. tracks = _settings$mediaTypes$2.tracks,
  42618. masterPlaylistLoader = settings.masterPlaylistLoader;
  42619. for (var groupId in mediaGroups[type]) {
  42620. if (!groups[groupId]) {
  42621. groups[groupId] = [];
  42622. }
  42623. for (var variantLabel in mediaGroups[type][groupId]) {
  42624. if (mediaGroups[type][groupId][variantLabel].forced) {
  42625. // Subtitle playlists with the forced attribute are not selectable in Safari.
  42626. // According to Apple's HLS Authoring Specification:
  42627. // If content has forced subtitles and regular subtitles in a given language,
  42628. // the regular subtitles track in that language MUST contain both the forced
  42629. // subtitles and the regular subtitles for that language.
  42630. // Because of this requirement and that Safari does not add forced subtitles,
  42631. // forced subtitles are skipped here to maintain consistent experience across
  42632. // all platforms
  42633. continue;
  42634. }
  42635. var properties = mediaGroups[type][groupId][variantLabel];
  42636. var playlistLoader = void 0;
  42637. if (sourceType === 'hls') {
  42638. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  42639. } else if (sourceType === 'dash') {
  42640. var playlists = properties.playlists.filter(function (p) {
  42641. return p.excludeUntil !== Infinity;
  42642. });
  42643. if (!playlists.length) {
  42644. return;
  42645. }
  42646. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  42647. } else if (sourceType === 'vhs-json') {
  42648. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  42649. // as provided, otherwise use the resolved URI to load the playlist
  42650. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  42651. }
  42652. properties = videojs.mergeOptions({
  42653. id: variantLabel,
  42654. playlistLoader: playlistLoader
  42655. }, properties);
  42656. setupListeners[type](type, properties.playlistLoader, settings);
  42657. groups[groupId].push(properties);
  42658. if (typeof tracks[variantLabel] === 'undefined') {
  42659. var track = tech.addRemoteTextTrack({
  42660. id: variantLabel,
  42661. kind: 'subtitles',
  42662. "default": properties["default"] && properties.autoselect,
  42663. language: properties.language,
  42664. label: variantLabel
  42665. }, false).track;
  42666. tracks[variantLabel] = track;
  42667. }
  42668. }
  42669. } // setup single error event handler for the segment loader
  42670. segmentLoader.on('error', onError[type](type, settings));
  42671. },
  42672. /**
  42673. * Setup TextTracks for the closed-caption groups
  42674. *
  42675. * @param {String} type
  42676. * MediaGroup type
  42677. * @param {Object} settings
  42678. * Object containing required information for media groups
  42679. * @function initialize['CLOSED-CAPTIONS']
  42680. */
  42681. 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
  42682. var tech = settings.tech,
  42683. mediaGroups = settings.master.mediaGroups,
  42684. _settings$mediaTypes$3 = settings.mediaTypes[type],
  42685. groups = _settings$mediaTypes$3.groups,
  42686. tracks = _settings$mediaTypes$3.tracks;
  42687. for (var groupId in mediaGroups[type]) {
  42688. if (!groups[groupId]) {
  42689. groups[groupId] = [];
  42690. }
  42691. for (var variantLabel in mediaGroups[type][groupId]) {
  42692. var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  42693. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  42694. continue;
  42695. }
  42696. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  42697. var newProps = {
  42698. label: variantLabel,
  42699. language: properties.language,
  42700. instreamId: properties.instreamId,
  42701. "default": properties["default"] && properties.autoselect
  42702. };
  42703. if (captionServices[newProps.instreamId]) {
  42704. newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
  42705. }
  42706. if (newProps["default"] === undefined) {
  42707. delete newProps["default"];
  42708. } // No PlaylistLoader is required for Closed-Captions because the captions are
  42709. // embedded within the video stream
  42710. groups[groupId].push(videojs.mergeOptions({
  42711. id: variantLabel
  42712. }, properties));
  42713. if (typeof tracks[variantLabel] === 'undefined') {
  42714. var track = tech.addRemoteTextTrack({
  42715. id: newProps.instreamId,
  42716. kind: 'captions',
  42717. "default": newProps["default"],
  42718. language: newProps.language,
  42719. label: newProps.label
  42720. }, false).track;
  42721. tracks[variantLabel] = track;
  42722. }
  42723. }
  42724. }
  42725. }
  42726. };
  42727. var groupMatch = function groupMatch(list, media) {
  42728. for (var i = 0; i < list.length; i++) {
  42729. if (playlistMatch(media, list[i])) {
  42730. return true;
  42731. }
  42732. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  42733. return true;
  42734. }
  42735. }
  42736. return false;
  42737. };
  42738. /**
  42739. * Returns a function used to get the active group of the provided type
  42740. *
  42741. * @param {string} type
  42742. * MediaGroup type
  42743. * @param {Object} settings
  42744. * Object containing required information for media groups
  42745. * @return {Function}
  42746. * Function that returns the active media group for the provided type. Takes an
  42747. * optional parameter {TextTrack} track. If no track is provided, a list of all
  42748. * variants in the group, otherwise the variant corresponding to the provided
  42749. * track is returned.
  42750. * @function activeGroup
  42751. */
  42752. var activeGroup = function activeGroup(type, settings) {
  42753. return function (track) {
  42754. var masterPlaylistLoader = settings.masterPlaylistLoader,
  42755. groups = settings.mediaTypes[type].groups;
  42756. var media = masterPlaylistLoader.media();
  42757. if (!media) {
  42758. return null;
  42759. }
  42760. var variants = null; // set to variants to main media active group
  42761. if (media.attributes[type]) {
  42762. variants = groups[media.attributes[type]];
  42763. }
  42764. var groupKeys = Object.keys(groups);
  42765. if (!variants) {
  42766. // find the masterPlaylistLoader media
  42767. // that is in a media group if we are dealing
  42768. // with audio only
  42769. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
  42770. for (var i = 0; i < groupKeys.length; i++) {
  42771. var groupPropertyList = groups[groupKeys[i]];
  42772. if (groupMatch(groupPropertyList, media)) {
  42773. variants = groupPropertyList;
  42774. break;
  42775. }
  42776. } // use the main group if it exists
  42777. } else if (groups.main) {
  42778. variants = groups.main; // only one group, use that one
  42779. } else if (groupKeys.length === 1) {
  42780. variants = groups[groupKeys[0]];
  42781. }
  42782. }
  42783. if (typeof track === 'undefined') {
  42784. return variants;
  42785. }
  42786. if (track === null || !variants) {
  42787. // An active track was specified so a corresponding group is expected. track === null
  42788. // means no track is currently active so there is no corresponding group
  42789. return null;
  42790. }
  42791. return variants.filter(function (props) {
  42792. return props.id === track.id;
  42793. })[0] || null;
  42794. };
  42795. };
  42796. var activeTrack = {
  42797. /**
  42798. * Returns a function used to get the active track of type provided
  42799. *
  42800. * @param {string} type
  42801. * MediaGroup type
  42802. * @param {Object} settings
  42803. * Object containing required information for media groups
  42804. * @return {Function}
  42805. * Function that returns the active media track for the provided type. Returns
  42806. * null if no track is active
  42807. * @function activeTrack.AUDIO
  42808. */
  42809. AUDIO: function AUDIO(type, settings) {
  42810. return function () {
  42811. var tracks = settings.mediaTypes[type].tracks;
  42812. for (var id in tracks) {
  42813. if (tracks[id].enabled) {
  42814. return tracks[id];
  42815. }
  42816. }
  42817. return null;
  42818. };
  42819. },
  42820. /**
  42821. * Returns a function used to get the active track of type provided
  42822. *
  42823. * @param {string} type
  42824. * MediaGroup type
  42825. * @param {Object} settings
  42826. * Object containing required information for media groups
  42827. * @return {Function}
  42828. * Function that returns the active media track for the provided type. Returns
  42829. * null if no track is active
  42830. * @function activeTrack.SUBTITLES
  42831. */
  42832. SUBTITLES: function SUBTITLES(type, settings) {
  42833. return function () {
  42834. var tracks = settings.mediaTypes[type].tracks;
  42835. for (var id in tracks) {
  42836. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  42837. return tracks[id];
  42838. }
  42839. }
  42840. return null;
  42841. };
  42842. }
  42843. };
  42844. var getActiveGroup = function getActiveGroup(type, _ref) {
  42845. var mediaTypes = _ref.mediaTypes;
  42846. return function () {
  42847. var activeTrack_ = mediaTypes[type].activeTrack();
  42848. if (!activeTrack_) {
  42849. return null;
  42850. }
  42851. return mediaTypes[type].activeGroup(activeTrack_);
  42852. };
  42853. };
  42854. /**
  42855. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  42856. * Closed-Captions) specified in the master manifest.
  42857. *
  42858. * @param {Object} settings
  42859. * Object containing required information for setting up the media groups
  42860. * @param {Tech} settings.tech
  42861. * The tech of the player
  42862. * @param {Object} settings.requestOptions
  42863. * XHR request options used by the segment loaders
  42864. * @param {PlaylistLoader} settings.masterPlaylistLoader
  42865. * PlaylistLoader for the master source
  42866. * @param {VhsHandler} settings.vhs
  42867. * VHS SourceHandler
  42868. * @param {Object} settings.master
  42869. * The parsed master manifest
  42870. * @param {Object} settings.mediaTypes
  42871. * Object to store the loaders, tracks, and utility methods for each media type
  42872. * @param {Function} settings.blacklistCurrentPlaylist
  42873. * Blacklists the current rendition and forces a rendition switch.
  42874. * @function setupMediaGroups
  42875. */
  42876. var setupMediaGroups = function setupMediaGroups(settings) {
  42877. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  42878. initialize[type](type, settings);
  42879. });
  42880. var mediaTypes = settings.mediaTypes,
  42881. masterPlaylistLoader = settings.masterPlaylistLoader,
  42882. tech = settings.tech,
  42883. vhs = settings.vhs,
  42884. _settings$segmentLoad3 = settings.segmentLoaders,
  42885. audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
  42886. mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
  42887. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  42888. mediaTypes[type].activeGroup = activeGroup(type, settings);
  42889. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  42890. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  42891. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  42892. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  42893. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  42894. }); // DO NOT enable the default subtitle or caption track.
  42895. // DO enable the default audio track
  42896. var audioGroup = mediaTypes.AUDIO.activeGroup();
  42897. if (audioGroup) {
  42898. var groupId = (audioGroup.filter(function (group) {
  42899. return group["default"];
  42900. })[0] || audioGroup[0]).id;
  42901. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  42902. mediaTypes.AUDIO.onGroupChanged();
  42903. mediaTypes.AUDIO.onTrackChanged();
  42904. var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  42905. // track is changed, but needs to be handled here since the track may not be considered
  42906. // changed on the first call to onTrackChanged
  42907. if (!activeAudioGroup.playlistLoader) {
  42908. // either audio is muxed with video or the stream is audio only
  42909. mainSegmentLoader.setAudio(true);
  42910. } else {
  42911. // audio is demuxed
  42912. mainSegmentLoader.setAudio(false);
  42913. audioSegmentLoader.setAudio(true);
  42914. }
  42915. }
  42916. masterPlaylistLoader.on('mediachange', function () {
  42917. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  42918. return mediaTypes[type].onGroupChanged();
  42919. });
  42920. });
  42921. masterPlaylistLoader.on('mediachanging', function () {
  42922. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  42923. return mediaTypes[type].onGroupChanging();
  42924. });
  42925. }); // custom audio track change event handler for usage event
  42926. var onAudioTrackChanged = function onAudioTrackChanged() {
  42927. mediaTypes.AUDIO.onTrackChanged();
  42928. tech.trigger({
  42929. type: 'usage',
  42930. name: 'vhs-audio-change'
  42931. });
  42932. tech.trigger({
  42933. type: 'usage',
  42934. name: 'hls-audio-change'
  42935. });
  42936. };
  42937. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  42938. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  42939. vhs.on('dispose', function () {
  42940. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  42941. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  42942. }); // clear existing audio tracks and add the ones we just created
  42943. tech.clearTracks('audio');
  42944. for (var id in mediaTypes.AUDIO.tracks) {
  42945. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  42946. }
  42947. };
  42948. /**
  42949. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  42950. * media type
  42951. *
  42952. * @return {Object}
  42953. * Object to store the loaders, tracks, and utility methods for each media type
  42954. * @function createMediaTypes
  42955. */
  42956. var createMediaTypes = function createMediaTypes() {
  42957. var mediaTypes = {};
  42958. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  42959. mediaTypes[type] = {
  42960. groups: {},
  42961. tracks: {},
  42962. activePlaylistLoader: null,
  42963. activeGroup: noop,
  42964. activeTrack: noop,
  42965. getActiveGroup: noop,
  42966. onGroupChanged: noop,
  42967. onTrackChanged: noop,
  42968. lastTrack_: null,
  42969. logger_: logger("MediaGroups[" + type + "]")
  42970. };
  42971. });
  42972. return mediaTypes;
  42973. };
  42974. var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
  42975. var Vhs$1; // SegmentLoader stats that need to have each loader's
  42976. // values summed to calculate the final value
  42977. var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  42978. var sumLoaderStat = function sumLoaderStat(stat) {
  42979. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  42980. };
  42981. var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
  42982. var currentPlaylist = _ref.currentPlaylist,
  42983. buffered = _ref.buffered,
  42984. currentTime = _ref.currentTime,
  42985. nextPlaylist = _ref.nextPlaylist,
  42986. bufferLowWaterLine = _ref.bufferLowWaterLine,
  42987. bufferHighWaterLine = _ref.bufferHighWaterLine,
  42988. duration = _ref.duration,
  42989. experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
  42990. log = _ref.log; // we have no other playlist to switch to
  42991. if (!nextPlaylist) {
  42992. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  42993. return false;
  42994. }
  42995. var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id;
  42996. if (!currentPlaylist) {
  42997. log(sharedLogLine + " as current playlist is not set");
  42998. return true;
  42999. } // no need to switch if playlist is the same
  43000. if (nextPlaylist.id === currentPlaylist.id) {
  43001. return false;
  43002. } // determine if current time is in a buffered range.
  43003. var isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  43004. // This is because in LIVE, the player plays 3 segments from the end of the
  43005. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  43006. // in those segments, a viewer will never experience a rendition upswitch.
  43007. if (!currentPlaylist.endList) {
  43008. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  43009. // doubles the time to first playback.
  43010. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  43011. log("not " + sharedLogLine + " as current playlist is live llhls, but currentTime isn't in buffered.");
  43012. return false;
  43013. }
  43014. log(sharedLogLine + " as current playlist is live");
  43015. return true;
  43016. }
  43017. var forwardBuffer = timeAheadOf(buffered, currentTime);
  43018. var maxBufferLowWaterLine = experimentalBufferBasedABR ? 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
  43019. // duration is below the max potential low water line
  43020. if (duration < maxBufferLowWaterLine) {
  43021. log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
  43022. return true;
  43023. }
  43024. var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  43025. var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  43026. // we can switch down
  43027. if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  43028. var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
  43029. if (experimentalBufferBasedABR) {
  43030. logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
  43031. }
  43032. log(logLine);
  43033. return true;
  43034. } // and if our buffer is higher than the low water line,
  43035. // we can switch up
  43036. if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  43037. var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
  43038. if (experimentalBufferBasedABR) {
  43039. _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
  43040. }
  43041. log(_logLine);
  43042. return true;
  43043. }
  43044. log("not " + sharedLogLine + " as no switching criteria met");
  43045. return false;
  43046. };
  43047. /**
  43048. * the master playlist controller controller all interactons
  43049. * between playlists and segmentloaders. At this time this mainly
  43050. * involves a master playlist and a series of audio playlists
  43051. * if they are available
  43052. *
  43053. * @class MasterPlaylistController
  43054. * @extends videojs.EventTarget
  43055. */
  43056. var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
  43057. _inheritsLoose__default['default'](MasterPlaylistController, _videojs$EventTarget);
  43058. function MasterPlaylistController(options) {
  43059. var _this;
  43060. _this = _videojs$EventTarget.call(this) || this;
  43061. var src = options.src,
  43062. handleManifestRedirects = options.handleManifestRedirects,
  43063. withCredentials = options.withCredentials,
  43064. tech = options.tech,
  43065. bandwidth = options.bandwidth,
  43066. externVhs = options.externVhs,
  43067. useCueTags = options.useCueTags,
  43068. blacklistDuration = options.blacklistDuration,
  43069. enableLowInitialPlaylist = options.enableLowInitialPlaylist,
  43070. sourceType = options.sourceType,
  43071. cacheEncryptionKeys = options.cacheEncryptionKeys,
  43072. experimentalBufferBasedABR = options.experimentalBufferBasedABR,
  43073. experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector,
  43074. captionServices = options.captionServices;
  43075. if (!src) {
  43076. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  43077. }
  43078. var maxPlaylistRetries = options.maxPlaylistRetries;
  43079. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  43080. maxPlaylistRetries = Infinity;
  43081. }
  43082. Vhs$1 = externVhs;
  43083. _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
  43084. _this.experimentalLeastPixelDiffSelector = Boolean(experimentalLeastPixelDiffSelector);
  43085. _this.withCredentials = withCredentials;
  43086. _this.tech_ = tech;
  43087. _this.vhs_ = tech.vhs;
  43088. _this.sourceType_ = sourceType;
  43089. _this.useCueTags_ = useCueTags;
  43090. _this.blacklistDuration = blacklistDuration;
  43091. _this.maxPlaylistRetries = maxPlaylistRetries;
  43092. _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  43093. if (_this.useCueTags_) {
  43094. _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
  43095. _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  43096. }
  43097. _this.requestOptions_ = {
  43098. withCredentials: withCredentials,
  43099. handleManifestRedirects: handleManifestRedirects,
  43100. maxPlaylistRetries: maxPlaylistRetries,
  43101. timeout: null
  43102. };
  43103. _this.on('error', _this.pauseLoading);
  43104. _this.mediaTypes_ = createMediaTypes();
  43105. _this.mediaSource = new window__default['default'].MediaSource();
  43106. _this.handleDurationChange_ = _this.handleDurationChange_.bind(_assertThisInitialized__default['default'](_this));
  43107. _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(_assertThisInitialized__default['default'](_this));
  43108. _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(_assertThisInitialized__default['default'](_this));
  43109. _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
  43110. _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
  43111. _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  43112. // everything, and the MediaSource should not be detached without a proper disposal
  43113. _this.seekable_ = videojs.createTimeRanges();
  43114. _this.hasPlayed_ = false;
  43115. _this.syncController_ = new SyncController(options);
  43116. _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  43117. kind: 'metadata',
  43118. label: 'segment-metadata'
  43119. }, false).track;
  43120. _this.decrypter_ = new Decrypter();
  43121. _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
  43122. _this.inbandTextTracks_ = {};
  43123. _this.timelineChangeController_ = new TimelineChangeController();
  43124. var segmentLoaderSettings = {
  43125. vhs: _this.vhs_,
  43126. parse708captions: options.parse708captions,
  43127. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  43128. captionServices: captionServices,
  43129. mediaSource: _this.mediaSource,
  43130. currentTime: _this.tech_.currentTime.bind(_this.tech_),
  43131. seekable: function seekable() {
  43132. return _this.seekable();
  43133. },
  43134. seeking: function seeking() {
  43135. return _this.tech_.seeking();
  43136. },
  43137. duration: function duration() {
  43138. return _this.duration();
  43139. },
  43140. hasPlayed: function hasPlayed() {
  43141. return _this.hasPlayed_;
  43142. },
  43143. goalBufferLength: function goalBufferLength() {
  43144. return _this.goalBufferLength();
  43145. },
  43146. bandwidth: bandwidth,
  43147. syncController: _this.syncController_,
  43148. decrypter: _this.decrypter_,
  43149. sourceType: _this.sourceType_,
  43150. inbandTextTracks: _this.inbandTextTracks_,
  43151. cacheEncryptionKeys: cacheEncryptionKeys,
  43152. sourceUpdater: _this.sourceUpdater_,
  43153. timelineChangeController: _this.timelineChangeController_,
  43154. experimentalExactManifestTimings: options.experimentalExactManifestTimings
  43155. }; // The source type check not only determines whether a special DASH playlist loader
  43156. // should be used, but also covers the case where the provided src is a vhs-json
  43157. // manifest object (instead of a URL). In the case of vhs-json, the default
  43158. // PlaylistLoader should be used.
  43159. _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
  43160. _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
  43161. // combined audio/video or just video when alternate audio track is selected
  43162. _this.mainSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  43163. segmentMetadataTrack: _this.segmentMetadataTrack_,
  43164. loaderType: 'main'
  43165. }), options); // alternate audio track
  43166. _this.audioSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  43167. loaderType: 'audio'
  43168. }), options);
  43169. _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  43170. loaderType: 'vtt',
  43171. featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks,
  43172. loadVttJs: function loadVttJs() {
  43173. return new Promise(function (resolve, reject) {
  43174. function onLoad() {
  43175. tech.off('vttjserror', onError);
  43176. resolve();
  43177. }
  43178. function onError() {
  43179. tech.off('vttjsloaded', onLoad);
  43180. reject();
  43181. }
  43182. tech.one('vttjsloaded', onLoad);
  43183. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  43184. tech.addWebVttScript_();
  43185. });
  43186. }
  43187. }), options);
  43188. _this.setupSegmentLoaderListeners_();
  43189. if (_this.experimentalBufferBasedABR) {
  43190. _this.masterPlaylistLoader_.one('loadedplaylist', function () {
  43191. return _this.startABRTimer_();
  43192. });
  43193. _this.tech_.on('pause', function () {
  43194. return _this.stopABRTimer_();
  43195. });
  43196. _this.tech_.on('play', function () {
  43197. return _this.startABRTimer_();
  43198. });
  43199. } // Create SegmentLoader stat-getters
  43200. // mediaRequests_
  43201. // mediaRequestsAborted_
  43202. // mediaRequestsTimedout_
  43203. // mediaRequestsErrored_
  43204. // mediaTransferDuration_
  43205. // mediaBytesTransferred_
  43206. // mediaAppends_
  43207. loaderStats.forEach(function (stat) {
  43208. _this[stat + '_'] = sumLoaderStat.bind(_assertThisInitialized__default['default'](_this), stat);
  43209. });
  43210. _this.logger_ = logger('MPC');
  43211. _this.triggeredFmp4Usage = false;
  43212. if (_this.tech_.preload() === 'none') {
  43213. _this.loadOnPlay_ = function () {
  43214. _this.loadOnPlay_ = null;
  43215. _this.masterPlaylistLoader_.load();
  43216. };
  43217. _this.tech_.one('play', _this.loadOnPlay_);
  43218. } else {
  43219. _this.masterPlaylistLoader_.load();
  43220. }
  43221. _this.timeToLoadedData__ = -1;
  43222. _this.mainAppendsToLoadedData__ = -1;
  43223. _this.audioAppendsToLoadedData__ = -1;
  43224. var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  43225. _this.tech_.one(event, function () {
  43226. var timeToLoadedDataStart = Date.now();
  43227. _this.tech_.one('loadeddata', function () {
  43228. _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  43229. _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
  43230. _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
  43231. });
  43232. });
  43233. return _this;
  43234. }
  43235. var _proto = MasterPlaylistController.prototype;
  43236. _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
  43237. return this.mainAppendsToLoadedData__;
  43238. };
  43239. _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
  43240. return this.audioAppendsToLoadedData__;
  43241. };
  43242. _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
  43243. var main = this.mainAppendsToLoadedData_();
  43244. var audio = this.audioAppendsToLoadedData_();
  43245. if (main === -1 || audio === -1) {
  43246. return -1;
  43247. }
  43248. return main + audio;
  43249. };
  43250. _proto.timeToLoadedData_ = function timeToLoadedData_() {
  43251. return this.timeToLoadedData__;
  43252. }
  43253. /**
  43254. * Run selectPlaylist and switch to the new playlist if we should
  43255. *
  43256. * @param {string} [reason=abr] a reason for why the ABR check is made
  43257. * @private
  43258. */
  43259. ;
  43260. _proto.checkABR_ = function checkABR_(reason) {
  43261. if (reason === void 0) {
  43262. reason = 'abr';
  43263. }
  43264. var nextPlaylist = this.selectPlaylist();
  43265. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  43266. this.switchMedia_(nextPlaylist, reason);
  43267. }
  43268. };
  43269. _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
  43270. var oldMedia = this.media();
  43271. var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  43272. var newId = playlist.id || playlist.uri;
  43273. if (oldId && oldId !== newId) {
  43274. this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
  43275. this.tech_.trigger({
  43276. type: 'usage',
  43277. name: "vhs-rendition-change-" + cause
  43278. });
  43279. }
  43280. this.masterPlaylistLoader_.media(playlist, delay);
  43281. }
  43282. /**
  43283. * Start a timer that periodically calls checkABR_
  43284. *
  43285. * @private
  43286. */
  43287. ;
  43288. _proto.startABRTimer_ = function startABRTimer_() {
  43289. var _this2 = this;
  43290. this.stopABRTimer_();
  43291. this.abrTimer_ = window__default['default'].setInterval(function () {
  43292. return _this2.checkABR_();
  43293. }, 250);
  43294. }
  43295. /**
  43296. * Stop the timer that periodically calls checkABR_
  43297. *
  43298. * @private
  43299. */
  43300. ;
  43301. _proto.stopABRTimer_ = function stopABRTimer_() {
  43302. // if we're scrubbing, we don't need to pause.
  43303. // This getter will be added to Video.js in version 7.11.
  43304. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  43305. return;
  43306. }
  43307. window__default['default'].clearInterval(this.abrTimer_);
  43308. this.abrTimer_ = null;
  43309. }
  43310. /**
  43311. * Get a list of playlists for the currently selected audio playlist
  43312. *
  43313. * @return {Array} the array of audio playlists
  43314. */
  43315. ;
  43316. _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
  43317. var master = this.master();
  43318. var defaultPlaylists = master && master.playlists || []; // if we don't have any audio groups then we can only
  43319. // assume that the audio tracks are contained in masters
  43320. // playlist array, use that or an empty array.
  43321. if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
  43322. return defaultPlaylists;
  43323. }
  43324. var AUDIO = master.mediaGroups.AUDIO;
  43325. var groupKeys = Object.keys(AUDIO);
  43326. var track; // get the current active track
  43327. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  43328. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
  43329. } else {
  43330. // default group is `main` or just the first group.
  43331. var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  43332. for (var label in defaultGroup) {
  43333. if (defaultGroup[label]["default"]) {
  43334. track = {
  43335. label: label
  43336. };
  43337. break;
  43338. }
  43339. }
  43340. } // no active track no playlists.
  43341. if (!track) {
  43342. return defaultPlaylists;
  43343. }
  43344. var playlists = []; // get all of the playlists that are possible for the
  43345. // active track.
  43346. for (var group in AUDIO) {
  43347. if (AUDIO[group][track.label]) {
  43348. var properties = AUDIO[group][track.label];
  43349. if (properties.playlists && properties.playlists.length) {
  43350. playlists.push.apply(playlists, properties.playlists);
  43351. } else if (properties.uri) {
  43352. playlists.push(properties);
  43353. } else if (master.playlists.length) {
  43354. // if an audio group does not have a uri
  43355. // see if we have main playlists that use it as a group.
  43356. // if we do then add those to the playlists list.
  43357. for (var i = 0; i < master.playlists.length; i++) {
  43358. var playlist = master.playlists[i];
  43359. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  43360. playlists.push(playlist);
  43361. }
  43362. }
  43363. }
  43364. }
  43365. }
  43366. if (!playlists.length) {
  43367. return defaultPlaylists;
  43368. }
  43369. return playlists;
  43370. }
  43371. /**
  43372. * Register event handlers on the master playlist loader. A helper
  43373. * function for construction time.
  43374. *
  43375. * @private
  43376. */
  43377. ;
  43378. _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
  43379. var _this3 = this;
  43380. this.masterPlaylistLoader_.on('loadedmetadata', function () {
  43381. var media = _this3.masterPlaylistLoader_.media();
  43382. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43383. // timeout the request.
  43384. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  43385. _this3.requestOptions_.timeout = 0;
  43386. } else {
  43387. _this3.requestOptions_.timeout = requestTimeout;
  43388. } // if this isn't a live video and preload permits, start
  43389. // downloading segments
  43390. if (media.endList && _this3.tech_.preload() !== 'none') {
  43391. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  43392. _this3.mainSegmentLoader_.load();
  43393. }
  43394. setupMediaGroups({
  43395. sourceType: _this3.sourceType_,
  43396. segmentLoaders: {
  43397. AUDIO: _this3.audioSegmentLoader_,
  43398. SUBTITLES: _this3.subtitleSegmentLoader_,
  43399. main: _this3.mainSegmentLoader_
  43400. },
  43401. tech: _this3.tech_,
  43402. requestOptions: _this3.requestOptions_,
  43403. masterPlaylistLoader: _this3.masterPlaylistLoader_,
  43404. vhs: _this3.vhs_,
  43405. master: _this3.master(),
  43406. mediaTypes: _this3.mediaTypes_,
  43407. blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
  43408. });
  43409. _this3.triggerPresenceUsage_(_this3.master(), media);
  43410. _this3.setupFirstPlay();
  43411. if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  43412. _this3.trigger('selectedinitialmedia');
  43413. } else {
  43414. // We must wait for the active audio playlist loader to
  43415. // finish setting up before triggering this event so the
  43416. // representations API and EME setup is correct
  43417. _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
  43418. _this3.trigger('selectedinitialmedia');
  43419. });
  43420. }
  43421. });
  43422. this.masterPlaylistLoader_.on('loadedplaylist', function () {
  43423. if (_this3.loadOnPlay_) {
  43424. _this3.tech_.off('play', _this3.loadOnPlay_);
  43425. }
  43426. var updatedPlaylist = _this3.masterPlaylistLoader_.media();
  43427. if (!updatedPlaylist) {
  43428. // exclude any variants that are not supported by the browser before selecting
  43429. // an initial media as the playlist selectors do not consider browser support
  43430. _this3.excludeUnsupportedVariants_();
  43431. var selectedMedia;
  43432. if (_this3.enableLowInitialPlaylist) {
  43433. selectedMedia = _this3.selectInitialPlaylist();
  43434. }
  43435. if (!selectedMedia) {
  43436. selectedMedia = _this3.selectPlaylist();
  43437. }
  43438. if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
  43439. return;
  43440. }
  43441. _this3.initialMedia_ = selectedMedia;
  43442. _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  43443. // fire again since the playlist will be requested. In the case of vhs-json
  43444. // (where the manifest object is provided as the source), when the media
  43445. // playlist's `segments` list is already available, a media playlist won't be
  43446. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  43447. // called on its own here.
  43448. var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
  43449. if (!haveJsonSource) {
  43450. return;
  43451. }
  43452. updatedPlaylist = _this3.initialMedia_;
  43453. }
  43454. _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
  43455. });
  43456. this.masterPlaylistLoader_.on('error', function () {
  43457. _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
  43458. });
  43459. this.masterPlaylistLoader_.on('mediachanging', function () {
  43460. _this3.mainSegmentLoader_.abort();
  43461. _this3.mainSegmentLoader_.pause();
  43462. });
  43463. this.masterPlaylistLoader_.on('mediachange', function () {
  43464. var media = _this3.masterPlaylistLoader_.media();
  43465. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  43466. // timeout the request.
  43467. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  43468. _this3.requestOptions_.timeout = 0;
  43469. } else {
  43470. _this3.requestOptions_.timeout = requestTimeout;
  43471. }
  43472. _this3.masterPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  43473. // that the segments have changed in some way and use that to
  43474. // update the SegmentLoader instead of doing it twice here and
  43475. // on `loadedplaylist`
  43476. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  43477. _this3.mainSegmentLoader_.load();
  43478. _this3.tech_.trigger({
  43479. type: 'mediachange',
  43480. bubbles: true
  43481. });
  43482. });
  43483. this.masterPlaylistLoader_.on('playlistunchanged', function () {
  43484. var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  43485. // excluded for not-changing. We likely just have a really slowly updating
  43486. // playlist.
  43487. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  43488. return;
  43489. }
  43490. var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
  43491. if (playlistOutdated) {
  43492. // Playlist has stopped updating and we're stuck at its end. Try to
  43493. // blacklist it and switch to another playlist in the hope that that
  43494. // one is updating (and give the player a chance to re-adjust to the
  43495. // safe live point).
  43496. _this3.blacklistCurrentPlaylist({
  43497. message: 'Playlist no longer updating.',
  43498. reason: 'playlist-unchanged'
  43499. }); // useful for monitoring QoS
  43500. _this3.tech_.trigger('playliststuck');
  43501. }
  43502. });
  43503. this.masterPlaylistLoader_.on('renditiondisabled', function () {
  43504. _this3.tech_.trigger({
  43505. type: 'usage',
  43506. name: 'vhs-rendition-disabled'
  43507. });
  43508. _this3.tech_.trigger({
  43509. type: 'usage',
  43510. name: 'hls-rendition-disabled'
  43511. });
  43512. });
  43513. this.masterPlaylistLoader_.on('renditionenabled', function () {
  43514. _this3.tech_.trigger({
  43515. type: 'usage',
  43516. name: 'vhs-rendition-enabled'
  43517. });
  43518. _this3.tech_.trigger({
  43519. type: 'usage',
  43520. name: 'hls-rendition-enabled'
  43521. });
  43522. });
  43523. }
  43524. /**
  43525. * Given an updated media playlist (whether it was loaded for the first time, or
  43526. * refreshed for live playlists), update any relevant properties and state to reflect
  43527. * changes in the media that should be accounted for (e.g., cues and duration).
  43528. *
  43529. * @param {Object} updatedPlaylist the updated media playlist object
  43530. *
  43531. * @private
  43532. */
  43533. ;
  43534. _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
  43535. if (this.useCueTags_) {
  43536. this.updateAdCues_(updatedPlaylist);
  43537. } // TODO: Create a new event on the PlaylistLoader that signals
  43538. // that the segments have changed in some way and use that to
  43539. // update the SegmentLoader instead of doing it twice here and
  43540. // on `mediachange`
  43541. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  43542. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  43543. // as it is possible that it was temporarily stopped while waiting for
  43544. // a playlist (e.g., in case the playlist errored and we re-requested it).
  43545. if (!this.tech_.paused()) {
  43546. this.mainSegmentLoader_.load();
  43547. if (this.audioSegmentLoader_) {
  43548. this.audioSegmentLoader_.load();
  43549. }
  43550. }
  43551. }
  43552. /**
  43553. * A helper function for triggerring presence usage events once per source
  43554. *
  43555. * @private
  43556. */
  43557. ;
  43558. _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
  43559. var mediaGroups = master.mediaGroups || {};
  43560. var defaultDemuxed = true;
  43561. var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  43562. for (var mediaGroup in mediaGroups.AUDIO) {
  43563. for (var label in mediaGroups.AUDIO[mediaGroup]) {
  43564. var properties = mediaGroups.AUDIO[mediaGroup][label];
  43565. if (!properties.uri) {
  43566. defaultDemuxed = false;
  43567. }
  43568. }
  43569. }
  43570. if (defaultDemuxed) {
  43571. this.tech_.trigger({
  43572. type: 'usage',
  43573. name: 'vhs-demuxed'
  43574. });
  43575. this.tech_.trigger({
  43576. type: 'usage',
  43577. name: 'hls-demuxed'
  43578. });
  43579. }
  43580. if (Object.keys(mediaGroups.SUBTITLES).length) {
  43581. this.tech_.trigger({
  43582. type: 'usage',
  43583. name: 'vhs-webvtt'
  43584. });
  43585. this.tech_.trigger({
  43586. type: 'usage',
  43587. name: 'hls-webvtt'
  43588. });
  43589. }
  43590. if (Vhs$1.Playlist.isAes(media)) {
  43591. this.tech_.trigger({
  43592. type: 'usage',
  43593. name: 'vhs-aes'
  43594. });
  43595. this.tech_.trigger({
  43596. type: 'usage',
  43597. name: 'hls-aes'
  43598. });
  43599. }
  43600. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  43601. this.tech_.trigger({
  43602. type: 'usage',
  43603. name: 'vhs-alternate-audio'
  43604. });
  43605. this.tech_.trigger({
  43606. type: 'usage',
  43607. name: 'hls-alternate-audio'
  43608. });
  43609. }
  43610. if (this.useCueTags_) {
  43611. this.tech_.trigger({
  43612. type: 'usage',
  43613. name: 'vhs-playlist-cue-tags'
  43614. });
  43615. this.tech_.trigger({
  43616. type: 'usage',
  43617. name: 'hls-playlist-cue-tags'
  43618. });
  43619. }
  43620. };
  43621. _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
  43622. var currentPlaylist = this.masterPlaylistLoader_.media() || this.masterPlaylistLoader_.pendingMedia_;
  43623. var currentTime = this.tech_.currentTime();
  43624. var bufferLowWaterLine = this.bufferLowWaterLine();
  43625. var bufferHighWaterLine = this.bufferHighWaterLine();
  43626. var buffered = this.tech_.buffered();
  43627. return shouldSwitchToMedia({
  43628. buffered: buffered,
  43629. currentTime: currentTime,
  43630. currentPlaylist: currentPlaylist,
  43631. nextPlaylist: nextPlaylist,
  43632. bufferLowWaterLine: bufferLowWaterLine,
  43633. bufferHighWaterLine: bufferHighWaterLine,
  43634. duration: this.duration(),
  43635. experimentalBufferBasedABR: this.experimentalBufferBasedABR,
  43636. log: this.logger_
  43637. });
  43638. }
  43639. /**
  43640. * Register event handlers on the segment loaders. A helper function
  43641. * for construction time.
  43642. *
  43643. * @private
  43644. */
  43645. ;
  43646. _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
  43647. var _this4 = this;
  43648. this.mainSegmentLoader_.on('bandwidthupdate', function () {
  43649. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  43650. // useful to check to see if a rendition switch should be made.
  43651. _this4.checkABR_('bandwidthupdate');
  43652. _this4.tech_.trigger('bandwidthupdate');
  43653. });
  43654. this.mainSegmentLoader_.on('timeout', function () {
  43655. if (_this4.experimentalBufferBasedABR) {
  43656. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  43657. // Here the only consideration is that for buffer based ABR there's no guarantee
  43658. // of an immediate switch (since the bandwidth is averaged with a timeout
  43659. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  43660. _this4.mainSegmentLoader_.load();
  43661. }
  43662. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  43663. // based ABR.
  43664. if (!this.experimentalBufferBasedABR) {
  43665. this.mainSegmentLoader_.on('progress', function () {
  43666. _this4.trigger('progress');
  43667. });
  43668. }
  43669. this.mainSegmentLoader_.on('error', function () {
  43670. _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
  43671. });
  43672. this.mainSegmentLoader_.on('appenderror', function () {
  43673. _this4.error = _this4.mainSegmentLoader_.error_;
  43674. _this4.trigger('error');
  43675. });
  43676. this.mainSegmentLoader_.on('syncinfoupdate', function () {
  43677. _this4.onSyncInfoUpdate_();
  43678. });
  43679. this.mainSegmentLoader_.on('timestampoffset', function () {
  43680. _this4.tech_.trigger({
  43681. type: 'usage',
  43682. name: 'vhs-timestamp-offset'
  43683. });
  43684. _this4.tech_.trigger({
  43685. type: 'usage',
  43686. name: 'hls-timestamp-offset'
  43687. });
  43688. });
  43689. this.audioSegmentLoader_.on('syncinfoupdate', function () {
  43690. _this4.onSyncInfoUpdate_();
  43691. });
  43692. this.audioSegmentLoader_.on('appenderror', function () {
  43693. _this4.error = _this4.audioSegmentLoader_.error_;
  43694. _this4.trigger('error');
  43695. });
  43696. this.mainSegmentLoader_.on('ended', function () {
  43697. _this4.logger_('main segment loader ended');
  43698. _this4.onEndOfStream();
  43699. });
  43700. this.mainSegmentLoader_.on('earlyabort', function (event) {
  43701. // never try to early abort with the new ABR algorithm
  43702. if (_this4.experimentalBufferBasedABR) {
  43703. return;
  43704. }
  43705. _this4.delegateLoaders_('all', ['abort']);
  43706. _this4.blacklistCurrentPlaylist({
  43707. message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
  43708. }, ABORT_EARLY_BLACKLIST_SECONDS);
  43709. });
  43710. var updateCodecs = function updateCodecs() {
  43711. if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
  43712. return _this4.tryToCreateSourceBuffers_();
  43713. }
  43714. var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  43715. if (!codecs) {
  43716. return;
  43717. }
  43718. _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  43719. };
  43720. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  43721. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  43722. this.mainSegmentLoader_.on('fmp4', function () {
  43723. if (!_this4.triggeredFmp4Usage) {
  43724. _this4.tech_.trigger({
  43725. type: 'usage',
  43726. name: 'vhs-fmp4'
  43727. });
  43728. _this4.tech_.trigger({
  43729. type: 'usage',
  43730. name: 'hls-fmp4'
  43731. });
  43732. _this4.triggeredFmp4Usage = true;
  43733. }
  43734. });
  43735. this.audioSegmentLoader_.on('fmp4', function () {
  43736. if (!_this4.triggeredFmp4Usage) {
  43737. _this4.tech_.trigger({
  43738. type: 'usage',
  43739. name: 'vhs-fmp4'
  43740. });
  43741. _this4.tech_.trigger({
  43742. type: 'usage',
  43743. name: 'hls-fmp4'
  43744. });
  43745. _this4.triggeredFmp4Usage = true;
  43746. }
  43747. });
  43748. this.audioSegmentLoader_.on('ended', function () {
  43749. _this4.logger_('audioSegmentLoader ended');
  43750. _this4.onEndOfStream();
  43751. });
  43752. };
  43753. _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
  43754. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  43755. }
  43756. /**
  43757. * Call load on our SegmentLoaders
  43758. */
  43759. ;
  43760. _proto.load = function load() {
  43761. this.mainSegmentLoader_.load();
  43762. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43763. this.audioSegmentLoader_.load();
  43764. }
  43765. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  43766. this.subtitleSegmentLoader_.load();
  43767. }
  43768. }
  43769. /**
  43770. * Re-tune playback quality level for the current player
  43771. * conditions without performing destructive actions, like
  43772. * removing already buffered content
  43773. *
  43774. * @private
  43775. * @deprecated
  43776. */
  43777. ;
  43778. _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
  43779. if (media === void 0) {
  43780. media = this.selectPlaylist();
  43781. }
  43782. this.fastQualityChange_(media);
  43783. }
  43784. /**
  43785. * Re-tune playback quality level for the current player
  43786. * conditions. This method will perform destructive actions like removing
  43787. * already buffered content in order to readjust the currently active
  43788. * playlist quickly. This is good for manual quality changes
  43789. *
  43790. * @private
  43791. */
  43792. ;
  43793. _proto.fastQualityChange_ = function fastQualityChange_(media) {
  43794. var _this5 = this;
  43795. if (media === void 0) {
  43796. media = this.selectPlaylist();
  43797. }
  43798. if (media === this.masterPlaylistLoader_.media()) {
  43799. this.logger_('skipping fastQualityChange because new media is same as old');
  43800. return;
  43801. }
  43802. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  43803. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  43804. // ahead is roughly the minimum that will accomplish this across a variety of content
  43805. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  43806. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  43807. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  43808. this.mainSegmentLoader_.resetEverything(function () {
  43809. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  43810. // from the previously enabled rendition to load before the new playlist has finished loading
  43811. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  43812. _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
  43813. } else {
  43814. _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
  43815. }
  43816. }); // don't need to reset audio as it is reset when media changes
  43817. }
  43818. /**
  43819. * Begin playback.
  43820. */
  43821. ;
  43822. _proto.play = function play() {
  43823. if (this.setupFirstPlay()) {
  43824. return;
  43825. }
  43826. if (this.tech_.ended()) {
  43827. this.tech_.setCurrentTime(0);
  43828. }
  43829. if (this.hasPlayed_) {
  43830. this.load();
  43831. }
  43832. var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  43833. // seek forward to the live point
  43834. if (this.tech_.duration() === Infinity) {
  43835. if (this.tech_.currentTime() < seekable.start(0)) {
  43836. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  43837. }
  43838. }
  43839. }
  43840. /**
  43841. * Seek to the latest media position if this is a live video and the
  43842. * player and video are loaded and initialized.
  43843. */
  43844. ;
  43845. _proto.setupFirstPlay = function setupFirstPlay() {
  43846. var _this6 = this;
  43847. var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  43848. // If 1) there is no active media
  43849. // 2) the player is paused
  43850. // 3) the first play has already been setup
  43851. // then exit early
  43852. if (!media || this.tech_.paused() || this.hasPlayed_) {
  43853. return false;
  43854. } // when the video is a live stream
  43855. if (!media.endList) {
  43856. var seekable = this.seekable();
  43857. if (!seekable.length) {
  43858. // without a seekable range, the player cannot seek to begin buffering at the live
  43859. // point
  43860. return false;
  43861. }
  43862. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  43863. // IE11 throws an InvalidStateError if you try to set currentTime while the
  43864. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  43865. this.tech_.one('loadedmetadata', function () {
  43866. _this6.trigger('firstplay');
  43867. _this6.tech_.setCurrentTime(seekable.end(0));
  43868. _this6.hasPlayed_ = true;
  43869. });
  43870. return false;
  43871. } // trigger firstplay to inform the source handler to ignore the next seek event
  43872. this.trigger('firstplay'); // seek to the live point
  43873. this.tech_.setCurrentTime(seekable.end(0));
  43874. }
  43875. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  43876. this.load();
  43877. return true;
  43878. }
  43879. /**
  43880. * handle the sourceopen event on the MediaSource
  43881. *
  43882. * @private
  43883. */
  43884. ;
  43885. _proto.handleSourceOpen_ = function handleSourceOpen_() {
  43886. // Only attempt to create the source buffer if none already exist.
  43887. // handleSourceOpen is also called when we are "re-opening" a source buffer
  43888. // after `endOfStream` has been called (in response to a seek for instance)
  43889. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  43890. // code in video.js but is required because play() must be invoked
  43891. // *after* the media source has opened.
  43892. if (this.tech_.autoplay()) {
  43893. var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  43894. // on browsers which return a promise
  43895. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  43896. playPromise.then(null, function (e) {});
  43897. }
  43898. }
  43899. this.trigger('sourceopen');
  43900. }
  43901. /**
  43902. * handle the sourceended event on the MediaSource
  43903. *
  43904. * @private
  43905. */
  43906. ;
  43907. _proto.handleSourceEnded_ = function handleSourceEnded_() {
  43908. if (!this.inbandTextTracks_.metadataTrack_) {
  43909. return;
  43910. }
  43911. var cues = this.inbandTextTracks_.metadataTrack_.cues;
  43912. if (!cues || !cues.length) {
  43913. return;
  43914. }
  43915. var duration = this.duration();
  43916. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  43917. }
  43918. /**
  43919. * handle the durationchange event on the MediaSource
  43920. *
  43921. * @private
  43922. */
  43923. ;
  43924. _proto.handleDurationChange_ = function handleDurationChange_() {
  43925. this.tech_.trigger('durationchange');
  43926. }
  43927. /**
  43928. * Calls endOfStream on the media source when all active stream types have called
  43929. * endOfStream
  43930. *
  43931. * @param {string} streamType
  43932. * Stream type of the segment loader that called endOfStream
  43933. * @private
  43934. */
  43935. ;
  43936. _proto.onEndOfStream = function onEndOfStream() {
  43937. var isEndOfStream = this.mainSegmentLoader_.ended_;
  43938. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  43939. var mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  43940. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  43941. // if we do not know if the main segment loader contains video yet or if we
  43942. // definitively know the main segment loader contains video, then we need to wait
  43943. // for both main and audio segment loaders to call endOfStream
  43944. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  43945. } else {
  43946. // otherwise just rely on the audio loader
  43947. isEndOfStream = this.audioSegmentLoader_.ended_;
  43948. }
  43949. }
  43950. if (!isEndOfStream) {
  43951. return;
  43952. }
  43953. this.stopABRTimer_();
  43954. this.sourceUpdater_.endOfStream();
  43955. }
  43956. /**
  43957. * Check if a playlist has stopped being updated
  43958. *
  43959. * @param {Object} playlist the media playlist object
  43960. * @return {boolean} whether the playlist has stopped being updated or not
  43961. */
  43962. ;
  43963. _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
  43964. var seekable = this.seekable();
  43965. if (!seekable.length) {
  43966. // playlist doesn't have enough information to determine whether we are stuck
  43967. return false;
  43968. }
  43969. var expired = this.syncController_.getExpiredTime(playlist, this.duration());
  43970. if (expired === null) {
  43971. return false;
  43972. } // does not use the safe live end to calculate playlist end, since we
  43973. // don't want to say we are stuck while there is still content
  43974. var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  43975. var currentTime = this.tech_.currentTime();
  43976. var buffered = this.tech_.buffered();
  43977. if (!buffered.length) {
  43978. // return true if the playhead reached the absolute end of the playlist
  43979. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  43980. }
  43981. var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  43982. // end of playlist
  43983. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  43984. }
  43985. /**
  43986. * Blacklists a playlist when an error occurs for a set amount of time
  43987. * making it unavailable for selection by the rendition selection algorithm
  43988. * and then forces a new playlist (rendition) selection.
  43989. *
  43990. * @param {Object=} error an optional error that may include the playlist
  43991. * to blacklist
  43992. * @param {number=} blacklistDuration an optional number of seconds to blacklist the
  43993. * playlist
  43994. */
  43995. ;
  43996. _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
  43997. if (error === void 0) {
  43998. error = {};
  43999. } // If the `error` was generated by the playlist loader, it will contain
  44000. // the playlist we were trying to load (but failed) and that should be
  44001. // blacklisted instead of the currently selected playlist which is likely
  44002. // out-of-date in this scenario
  44003. var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
  44004. blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
  44005. // trying to load the master OR while we were disposing of the tech
  44006. if (!currentPlaylist) {
  44007. this.error = error;
  44008. if (this.mediaSource.readyState !== 'open') {
  44009. this.trigger('error');
  44010. } else {
  44011. this.sourceUpdater_.endOfStream('network');
  44012. }
  44013. return;
  44014. }
  44015. currentPlaylist.playlistErrors_++;
  44016. var playlists = this.masterPlaylistLoader_.master.playlists;
  44017. var enabledPlaylists = playlists.filter(isEnabled);
  44018. var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
  44019. // forever
  44020. if (playlists.length === 1 && blacklistDuration !== Infinity) {
  44021. videojs.log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
  44022. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  44023. return this.masterPlaylistLoader_.load(isFinalRendition);
  44024. }
  44025. if (isFinalRendition) {
  44026. // Since we're on the final non-blacklisted playlist, and we're about to blacklist
  44027. // it, instead of erring the player or retrying this playlist, clear out the current
  44028. // blacklist. This allows other playlists to be attempted in case any have been
  44029. // fixed.
  44030. var reincluded = false;
  44031. playlists.forEach(function (playlist) {
  44032. // skip current playlist which is about to be blacklisted
  44033. if (playlist === currentPlaylist) {
  44034. return;
  44035. }
  44036. var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  44037. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  44038. reincluded = true;
  44039. delete playlist.excludeUntil;
  44040. }
  44041. });
  44042. if (reincluded) {
  44043. 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
  44044. // playlist. This is needed for users relying on the retryplaylist event to catch a
  44045. // case where the player might be stuck and looping through "dead" playlists.
  44046. this.tech_.trigger('retryplaylist');
  44047. }
  44048. } // Blacklist this playlist
  44049. var excludeUntil;
  44050. if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
  44051. excludeUntil = Infinity;
  44052. } else {
  44053. excludeUntil = Date.now() + blacklistDuration * 1000;
  44054. }
  44055. currentPlaylist.excludeUntil = excludeUntil;
  44056. if (error.reason) {
  44057. currentPlaylist.lastExcludeReason_ = error.reason;
  44058. }
  44059. this.tech_.trigger('blacklistplaylist');
  44060. this.tech_.trigger({
  44061. type: 'usage',
  44062. name: 'vhs-rendition-blacklisted'
  44063. });
  44064. this.tech_.trigger({
  44065. type: 'usage',
  44066. name: 'hls-rendition-blacklisted'
  44067. }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
  44068. // Would be something like media().id !=== currentPlaylist.id and we would need something
  44069. // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
  44070. // from loading a new playlist on any blacklist.
  44071. // Select a new playlist
  44072. var nextPlaylist = this.selectPlaylist();
  44073. if (!nextPlaylist) {
  44074. this.error = 'Playback cannot continue. No available working or supported playlists.';
  44075. this.trigger('error');
  44076. return;
  44077. }
  44078. var logFn = error.internal ? this.logger_ : videojs.log.warn;
  44079. var errorMessage = error.message ? ' ' + error.message : '';
  44080. logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
  44081. if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
  44082. this.delegateLoaders_('audio', ['abort', 'pause']);
  44083. } // if subtitle group changed reset subtitle loaders
  44084. if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
  44085. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  44086. }
  44087. this.delegateLoaders_('main', ['abort', 'pause']);
  44088. var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  44089. var 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
  44090. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  44091. }
  44092. /**
  44093. * Pause all segment/playlist loaders
  44094. */
  44095. ;
  44096. _proto.pauseLoading = function pauseLoading() {
  44097. this.delegateLoaders_('all', ['abort', 'pause']);
  44098. this.stopABRTimer_();
  44099. }
  44100. /**
  44101. * Call a set of functions in order on playlist loaders, segment loaders,
  44102. * or both types of loaders.
  44103. *
  44104. * @param {string} filter
  44105. * Filter loaders that should call fnNames using a string. Can be:
  44106. * * all - run on all loaders
  44107. * * audio - run on all audio loaders
  44108. * * subtitle - run on all subtitle loaders
  44109. * * main - run on the main/master loaders
  44110. *
  44111. * @param {Array|string} fnNames
  44112. * A string or array of function names to call.
  44113. */
  44114. ;
  44115. _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
  44116. var _this7 = this;
  44117. var loaders = [];
  44118. var dontFilterPlaylist = filter === 'all';
  44119. if (dontFilterPlaylist || filter === 'main') {
  44120. loaders.push(this.masterPlaylistLoader_);
  44121. }
  44122. var mediaTypes = [];
  44123. if (dontFilterPlaylist || filter === 'audio') {
  44124. mediaTypes.push('AUDIO');
  44125. }
  44126. if (dontFilterPlaylist || filter === 'subtitle') {
  44127. mediaTypes.push('CLOSED-CAPTIONS');
  44128. mediaTypes.push('SUBTITLES');
  44129. }
  44130. mediaTypes.forEach(function (mediaType) {
  44131. var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
  44132. if (loader) {
  44133. loaders.push(loader);
  44134. }
  44135. });
  44136. ['main', 'audio', 'subtitle'].forEach(function (name) {
  44137. var loader = _this7[name + "SegmentLoader_"];
  44138. if (loader && (filter === name || filter === 'all')) {
  44139. loaders.push(loader);
  44140. }
  44141. });
  44142. loaders.forEach(function (loader) {
  44143. return fnNames.forEach(function (fnName) {
  44144. if (typeof loader[fnName] === 'function') {
  44145. loader[fnName]();
  44146. }
  44147. });
  44148. });
  44149. }
  44150. /**
  44151. * set the current time on all segment loaders
  44152. *
  44153. * @param {TimeRange} currentTime the current time to set
  44154. * @return {TimeRange} the current time
  44155. */
  44156. ;
  44157. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  44158. var buffered = findRange(this.tech_.buffered(), currentTime);
  44159. if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
  44160. // return immediately if the metadata is not ready yet
  44161. return 0;
  44162. } // it's clearly an edge-case but don't thrown an error if asked to
  44163. // seek within an empty playlist
  44164. if (!this.masterPlaylistLoader_.media().segments) {
  44165. return 0;
  44166. } // if the seek location is already buffered, continue buffering as usual
  44167. if (buffered && buffered.length) {
  44168. return currentTime;
  44169. } // cancel outstanding requests so we begin buffering at the new
  44170. // location
  44171. this.mainSegmentLoader_.resetEverything();
  44172. this.mainSegmentLoader_.abort();
  44173. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44174. this.audioSegmentLoader_.resetEverything();
  44175. this.audioSegmentLoader_.abort();
  44176. }
  44177. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  44178. this.subtitleSegmentLoader_.resetEverything();
  44179. this.subtitleSegmentLoader_.abort();
  44180. } // start segment loader loading in case they are paused
  44181. this.load();
  44182. }
  44183. /**
  44184. * get the current duration
  44185. *
  44186. * @return {TimeRange} the duration
  44187. */
  44188. ;
  44189. _proto.duration = function duration() {
  44190. if (!this.masterPlaylistLoader_) {
  44191. return 0;
  44192. }
  44193. var media = this.masterPlaylistLoader_.media();
  44194. if (!media) {
  44195. // no playlists loaded yet, so can't determine a duration
  44196. return 0;
  44197. } // Don't rely on the media source for duration in the case of a live playlist since
  44198. // setting the native MediaSource's duration to infinity ends up with consequences to
  44199. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44200. //
  44201. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44202. // however, few browsers have support for setLiveSeekableRange()
  44203. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44204. //
  44205. // Until a time when the duration of the media source can be set to infinity, and a
  44206. // seekable range specified across browsers, just return Infinity.
  44207. if (!media.endList) {
  44208. return Infinity;
  44209. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  44210. // available). If it's not available, fall back to a playlist-calculated estimate.
  44211. if (this.mediaSource) {
  44212. return this.mediaSource.duration;
  44213. }
  44214. return Vhs$1.Playlist.duration(media);
  44215. }
  44216. /**
  44217. * check the seekable range
  44218. *
  44219. * @return {TimeRange} the seekable range
  44220. */
  44221. ;
  44222. _proto.seekable = function seekable() {
  44223. return this.seekable_;
  44224. };
  44225. _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
  44226. var audioSeekable; // TODO check for creation of both source buffers before updating seekable
  44227. //
  44228. // A fix was made to this function where a check for
  44229. // this.sourceUpdater_.hasCreatedSourceBuffers
  44230. // was added to ensure that both source buffers were created before seekable was
  44231. // updated. However, it originally had a bug where it was checking for a true and
  44232. // returning early instead of checking for false. Setting it to check for false to
  44233. // return early though created other issues. A call to play() would check for seekable
  44234. // end without verifying that a seekable range was present. In addition, even checking
  44235. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  44236. // due to a media update calling load on the segment loaders, skipping a seek to live,
  44237. // thereby starting live streams at the beginning of the stream rather than at the end.
  44238. //
  44239. // This conditional should be fixed to wait for the creation of two source buffers at
  44240. // the same time as the other sections of code are fixed to properly seek to live and
  44241. // not throw an error due to checking for a seekable end when no seekable range exists.
  44242. //
  44243. // For now, fall back to the older behavior, with the understanding that the seekable
  44244. // range may not be completely correct, leading to a suboptimal initial live point.
  44245. if (!this.masterPlaylistLoader_) {
  44246. return;
  44247. }
  44248. var media = this.masterPlaylistLoader_.media();
  44249. if (!media) {
  44250. return;
  44251. }
  44252. var expired = this.syncController_.getExpiredTime(media, this.duration());
  44253. if (expired === null) {
  44254. // not enough information to update seekable
  44255. return;
  44256. }
  44257. var master = this.masterPlaylistLoader_.master;
  44258. var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  44259. if (mainSeekable.length === 0) {
  44260. return;
  44261. }
  44262. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  44263. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  44264. expired = this.syncController_.getExpiredTime(media, this.duration());
  44265. if (expired === null) {
  44266. return;
  44267. }
  44268. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  44269. if (audioSeekable.length === 0) {
  44270. return;
  44271. }
  44272. }
  44273. var oldEnd;
  44274. var oldStart;
  44275. if (this.seekable_ && this.seekable_.length) {
  44276. oldEnd = this.seekable_.end(0);
  44277. oldStart = this.seekable_.start(0);
  44278. }
  44279. if (!audioSeekable) {
  44280. // seekable has been calculated based on buffering video data so it
  44281. // can be returned directly
  44282. this.seekable_ = mainSeekable;
  44283. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  44284. // seekables are pretty far off, rely on main
  44285. this.seekable_ = mainSeekable;
  44286. } else {
  44287. this.seekable_ = videojs.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)]]);
  44288. } // seekable is the same as last time
  44289. if (this.seekable_ && this.seekable_.length) {
  44290. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  44291. return;
  44292. }
  44293. }
  44294. this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
  44295. this.tech_.trigger('seekablechanged');
  44296. }
  44297. /**
  44298. * Update the player duration
  44299. */
  44300. ;
  44301. _proto.updateDuration = function updateDuration(isLive) {
  44302. if (this.updateDuration_) {
  44303. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44304. this.updateDuration_ = null;
  44305. }
  44306. if (this.mediaSource.readyState !== 'open') {
  44307. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  44308. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  44309. return;
  44310. }
  44311. if (isLive) {
  44312. var seekable = this.seekable();
  44313. if (!seekable.length) {
  44314. return;
  44315. } // Even in the case of a live playlist, the native MediaSource's duration should not
  44316. // be set to Infinity (even though this would be expected for a live playlist), since
  44317. // setting the native MediaSource's duration to infinity ends up with consequences to
  44318. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  44319. //
  44320. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  44321. // however, few browsers have support for setLiveSeekableRange()
  44322. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  44323. //
  44324. // Until a time when the duration of the media source can be set to infinity, and a
  44325. // seekable range specified across browsers, the duration should be greater than or
  44326. // equal to the last possible seekable value.
  44327. // MediaSource duration starts as NaN
  44328. // It is possible (and probable) that this case will never be reached for many
  44329. // sources, since the MediaSource reports duration as the highest value without
  44330. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  44331. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  44332. // time will be between 0 and 100, the native media source may report the duration
  44333. // as 200. However, since we report duration separate from the media source (as
  44334. // Infinity), and as long as the native media source duration value is greater than
  44335. // our reported seekable range, seeks will work as expected. The large number as
  44336. // duration for live is actually a strategy used by some players to work around the
  44337. // issue of live seekable ranges cited above.
  44338. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  44339. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  44340. }
  44341. return;
  44342. }
  44343. var buffered = this.tech_.buffered();
  44344. var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
  44345. if (buffered.length > 0) {
  44346. duration = Math.max(duration, buffered.end(buffered.length - 1));
  44347. }
  44348. if (this.mediaSource.duration !== duration) {
  44349. this.sourceUpdater_.setDuration(duration);
  44350. }
  44351. }
  44352. /**
  44353. * dispose of the MasterPlaylistController and everything
  44354. * that it controls
  44355. */
  44356. ;
  44357. _proto.dispose = function dispose() {
  44358. var _this8 = this;
  44359. this.trigger('dispose');
  44360. this.decrypter_.terminate();
  44361. this.masterPlaylistLoader_.dispose();
  44362. this.mainSegmentLoader_.dispose();
  44363. if (this.loadOnPlay_) {
  44364. this.tech_.off('play', this.loadOnPlay_);
  44365. }
  44366. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  44367. var groups = _this8.mediaTypes_[type].groups;
  44368. for (var id in groups) {
  44369. groups[id].forEach(function (group) {
  44370. if (group.playlistLoader) {
  44371. group.playlistLoader.dispose();
  44372. }
  44373. });
  44374. }
  44375. });
  44376. this.audioSegmentLoader_.dispose();
  44377. this.subtitleSegmentLoader_.dispose();
  44378. this.sourceUpdater_.dispose();
  44379. this.timelineChangeController_.dispose();
  44380. this.stopABRTimer_();
  44381. if (this.updateDuration_) {
  44382. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  44383. }
  44384. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  44385. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  44386. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  44387. this.off();
  44388. }
  44389. /**
  44390. * return the master playlist object if we have one
  44391. *
  44392. * @return {Object} the master playlist object that we parsed
  44393. */
  44394. ;
  44395. _proto.master = function master() {
  44396. return this.masterPlaylistLoader_.master;
  44397. }
  44398. /**
  44399. * return the currently selected playlist
  44400. *
  44401. * @return {Object} the currently selected playlist object that we parsed
  44402. */
  44403. ;
  44404. _proto.media = function media() {
  44405. // playlist loader will not return media if it has not been fully loaded
  44406. return this.masterPlaylistLoader_.media() || this.initialMedia_;
  44407. };
  44408. _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
  44409. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44410. var hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  44411. // otherwise check on the segment loader.
  44412. var hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  44413. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  44414. return false;
  44415. }
  44416. return true;
  44417. };
  44418. _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
  44419. var _this9 = this;
  44420. var media = {
  44421. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  44422. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  44423. };
  44424. var playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  44425. media.video = media.main;
  44426. var playlistCodecs = codecsForPlaylist(this.master(), playlist);
  44427. var codecs = {};
  44428. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  44429. if (media.main.hasVideo) {
  44430. codecs.video = playlistCodecs.video || media.main.videoCodec || codecs_js.DEFAULT_VIDEO_CODEC;
  44431. }
  44432. if (media.main.isMuxed) {
  44433. codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC);
  44434. }
  44435. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  44436. 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
  44437. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  44438. } // no codecs, no playback.
  44439. if (!codecs.audio && !codecs.video) {
  44440. this.blacklistCurrentPlaylist({
  44441. playlist: playlist,
  44442. message: 'Could not determine codecs for playlist.',
  44443. blacklistDuration: Infinity
  44444. });
  44445. return;
  44446. } // fmp4 relies on browser support, while ts relies on muxer support
  44447. var supportFunction = function supportFunction(isFmp4, codec) {
  44448. return isFmp4 ? codecs_js.browserSupportsCodec(codec) : codecs_js.muxerSupportsCodec(codec);
  44449. };
  44450. var unsupportedCodecs = {};
  44451. var unsupportedAudio;
  44452. ['video', 'audio'].forEach(function (type) {
  44453. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  44454. var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  44455. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  44456. unsupportedCodecs[supporter].push(codecs[type]);
  44457. if (type === 'audio') {
  44458. unsupportedAudio = supporter;
  44459. }
  44460. }
  44461. });
  44462. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  44463. var audioGroup = playlist.attributes.AUDIO;
  44464. this.master().playlists.forEach(function (variant) {
  44465. var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  44466. if (variantAudioGroup === audioGroup && variant !== playlist) {
  44467. variant.excludeUntil = Infinity;
  44468. }
  44469. });
  44470. this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
  44471. } // if we have any unsupported codecs blacklist this playlist.
  44472. if (Object.keys(unsupportedCodecs).length) {
  44473. var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
  44474. if (acc) {
  44475. acc += ', ';
  44476. }
  44477. acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
  44478. return acc;
  44479. }, '') + '.';
  44480. this.blacklistCurrentPlaylist({
  44481. playlist: playlist,
  44482. internal: true,
  44483. message: message,
  44484. blacklistDuration: Infinity
  44485. });
  44486. return;
  44487. } // check if codec switching is happening
  44488. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  44489. var switchMessages = [];
  44490. ['video', 'audio'].forEach(function (type) {
  44491. var newCodec = (codecs_js.parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  44492. var oldCodec = (codecs_js.parseCodecs(codecs[type] || '')[0] || {}).type;
  44493. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  44494. switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
  44495. }
  44496. });
  44497. if (switchMessages.length) {
  44498. this.blacklistCurrentPlaylist({
  44499. playlist: playlist,
  44500. message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
  44501. blacklistDuration: Infinity,
  44502. internal: true
  44503. });
  44504. return;
  44505. }
  44506. } // TODO: when using the muxer shouldn't we just return
  44507. // the codecs that the muxer outputs?
  44508. return codecs;
  44509. }
  44510. /**
  44511. * Create source buffers and exlude any incompatible renditions.
  44512. *
  44513. * @private
  44514. */
  44515. ;
  44516. _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
  44517. // media source is not ready yet or sourceBuffers are already
  44518. // created.
  44519. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  44520. return;
  44521. }
  44522. if (!this.areMediaTypesKnown_()) {
  44523. return;
  44524. }
  44525. var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  44526. if (!codecs) {
  44527. return;
  44528. }
  44529. this.sourceUpdater_.createSourceBuffers(codecs);
  44530. var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  44531. this.excludeIncompatibleVariants_(codecString);
  44532. }
  44533. /**
  44534. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  44535. */
  44536. ;
  44537. _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
  44538. var _this10 = this;
  44539. var playlists = this.master().playlists;
  44540. var ids = []; // TODO: why don't we have a property to loop through all
  44541. // playlist? Why did we ever mix indexes and keys?
  44542. Object.keys(playlists).forEach(function (key) {
  44543. var variant = playlists[key]; // check if we already processed this playlist.
  44544. if (ids.indexOf(variant.id) !== -1) {
  44545. return;
  44546. }
  44547. ids.push(variant.id);
  44548. var codecs = codecsForPlaylist(_this10.master, variant);
  44549. var unsupported = [];
  44550. if (codecs.audio && !codecs_js.muxerSupportsCodec(codecs.audio) && !codecs_js.browserSupportsCodec(codecs.audio)) {
  44551. unsupported.push("audio codec " + codecs.audio);
  44552. }
  44553. if (codecs.video && !codecs_js.muxerSupportsCodec(codecs.video) && !codecs_js.browserSupportsCodec(codecs.video)) {
  44554. unsupported.push("video codec " + codecs.video);
  44555. }
  44556. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  44557. unsupported.push("text codec " + codecs.text);
  44558. }
  44559. if (unsupported.length) {
  44560. variant.excludeUntil = Infinity;
  44561. _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
  44562. }
  44563. });
  44564. }
  44565. /**
  44566. * Blacklist playlists that are known to be codec or
  44567. * stream-incompatible with the SourceBuffer configuration. For
  44568. * instance, Media Source Extensions would cause the video element to
  44569. * stall waiting for video data if you switched from a variant with
  44570. * video and audio to an audio-only one.
  44571. *
  44572. * @param {Object} media a media playlist compatible with the current
  44573. * set of SourceBuffers. Variants in the current master playlist that
  44574. * do not appear to have compatible codec or stream configurations
  44575. * will be excluded from the default playlist selection algorithm
  44576. * indefinitely.
  44577. * @private
  44578. */
  44579. ;
  44580. _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
  44581. var _this11 = this;
  44582. var ids = [];
  44583. var playlists = this.master().playlists;
  44584. var codecs = unwrapCodecList(codecs_js.parseCodecs(codecString));
  44585. var codecCount_ = codecCount(codecs);
  44586. var videoDetails = codecs.video && codecs_js.parseCodecs(codecs.video)[0] || null;
  44587. var audioDetails = codecs.audio && codecs_js.parseCodecs(codecs.audio)[0] || null;
  44588. Object.keys(playlists).forEach(function (key) {
  44589. var variant = playlists[key]; // check if we already processed this playlist.
  44590. // or it if it is already excluded forever.
  44591. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  44592. return;
  44593. }
  44594. ids.push(variant.id);
  44595. var blacklistReasons = []; // get codecs from the playlist for this variant
  44596. var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
  44597. var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  44598. // variant is incompatible. Wait for mux.js to probe
  44599. if (!variantCodecs.audio && !variantCodecs.video) {
  44600. return;
  44601. } // TODO: we can support this by removing the
  44602. // old media source and creating a new one, but it will take some work.
  44603. // The number of streams cannot change
  44604. if (variantCodecCount !== codecCount_) {
  44605. blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
  44606. } // only exclude playlists by codec change, if codecs cannot switch
  44607. // during playback.
  44608. if (!_this11.sourceUpdater_.canChangeType()) {
  44609. var variantVideoDetails = variantCodecs.video && codecs_js.parseCodecs(variantCodecs.video)[0] || null;
  44610. var variantAudioDetails = variantCodecs.audio && codecs_js.parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  44611. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  44612. blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
  44613. } // the audio codec cannot change
  44614. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  44615. blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
  44616. }
  44617. }
  44618. if (blacklistReasons.length) {
  44619. variant.excludeUntil = Infinity;
  44620. _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
  44621. }
  44622. });
  44623. };
  44624. _proto.updateAdCues_ = function updateAdCues_(media) {
  44625. var offset = 0;
  44626. var seekable = this.seekable();
  44627. if (seekable.length) {
  44628. offset = seekable.start(0);
  44629. }
  44630. updateAdCues(media, this.cueTagsTrack_, offset);
  44631. }
  44632. /**
  44633. * Calculates the desired forward buffer length based on current time
  44634. *
  44635. * @return {number} Desired forward buffer length in seconds
  44636. */
  44637. ;
  44638. _proto.goalBufferLength = function goalBufferLength() {
  44639. var currentTime = this.tech_.currentTime();
  44640. var initial = Config.GOAL_BUFFER_LENGTH;
  44641. var rate = Config.GOAL_BUFFER_LENGTH_RATE;
  44642. var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  44643. return Math.min(initial + currentTime * rate, max);
  44644. }
  44645. /**
  44646. * Calculates the desired buffer low water line based on current time
  44647. *
  44648. * @return {number} Desired buffer low water line in seconds
  44649. */
  44650. ;
  44651. _proto.bufferLowWaterLine = function bufferLowWaterLine() {
  44652. var currentTime = this.tech_.currentTime();
  44653. var initial = Config.BUFFER_LOW_WATER_LINE;
  44654. var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  44655. var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  44656. var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  44657. return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
  44658. };
  44659. _proto.bufferHighWaterLine = function bufferHighWaterLine() {
  44660. return Config.BUFFER_HIGH_WATER_LINE;
  44661. };
  44662. return MasterPlaylistController;
  44663. }(videojs.EventTarget);
  44664. /**
  44665. * Returns a function that acts as the Enable/disable playlist function.
  44666. *
  44667. * @param {PlaylistLoader} loader - The master playlist loader
  44668. * @param {string} playlistID - id of the playlist
  44669. * @param {Function} changePlaylistFn - A function to be called after a
  44670. * playlist's enabled-state has been changed. Will NOT be called if a
  44671. * playlist's enabled-state is unchanged
  44672. * @param {boolean=} enable - Value to set the playlist enabled-state to
  44673. * or if undefined returns the current enabled-state for the playlist
  44674. * @return {Function} Function for setting/getting enabled
  44675. */
  44676. var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
  44677. return function (enable) {
  44678. var playlist = loader.master.playlists[playlistID];
  44679. var incompatible = isIncompatible(playlist);
  44680. var currentlyEnabled = isEnabled(playlist);
  44681. if (typeof enable === 'undefined') {
  44682. return currentlyEnabled;
  44683. }
  44684. if (enable) {
  44685. delete playlist.disabled;
  44686. } else {
  44687. playlist.disabled = true;
  44688. }
  44689. if (enable !== currentlyEnabled && !incompatible) {
  44690. // Ensure the outside world knows about our changes
  44691. changePlaylistFn();
  44692. if (enable) {
  44693. loader.trigger('renditionenabled');
  44694. } else {
  44695. loader.trigger('renditiondisabled');
  44696. }
  44697. }
  44698. return enable;
  44699. };
  44700. };
  44701. /**
  44702. * The representation object encapsulates the publicly visible information
  44703. * in a media playlist along with a setter/getter-type function (enabled)
  44704. * for changing the enabled-state of a particular playlist entry
  44705. *
  44706. * @class Representation
  44707. */
  44708. var Representation = function Representation(vhsHandler, playlist, id) {
  44709. var mpc = vhsHandler.masterPlaylistController_,
  44710. smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
  44711. var changeType = smoothQualityChange ? 'smooth' : 'fast';
  44712. var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
  44713. if (playlist.attributes) {
  44714. var resolution = playlist.attributes.RESOLUTION;
  44715. this.width = resolution && resolution.width;
  44716. this.height = resolution && resolution.height;
  44717. this.bandwidth = playlist.attributes.BANDWIDTH;
  44718. this.frameRate = playlist.attributes['FRAME-RATE'];
  44719. }
  44720. this.codecs = codecsForPlaylist(mpc.master(), playlist);
  44721. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  44722. // within the master playlist
  44723. this.id = id; // Partially-apply the enableFunction to create a playlist-
  44724. // specific variant
  44725. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  44726. };
  44727. /**
  44728. * A mixin function that adds the `representations` api to an instance
  44729. * of the VhsHandler class
  44730. *
  44731. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  44732. * representation API into
  44733. */
  44734. var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
  44735. // Add a single API-specific function to the VhsHandler instance
  44736. vhsHandler.representations = function () {
  44737. var master = vhsHandler.masterPlaylistController_.master();
  44738. var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
  44739. if (!playlists) {
  44740. return [];
  44741. }
  44742. return playlists.filter(function (media) {
  44743. return !isIncompatible(media);
  44744. }).map(function (e, i) {
  44745. return new Representation(vhsHandler, e, e.id);
  44746. });
  44747. };
  44748. };
  44749. /**
  44750. * @file playback-watcher.js
  44751. *
  44752. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  44753. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  44754. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  44755. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  44756. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  44757. */
  44758. var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  44759. /**
  44760. * @class PlaybackWatcher
  44761. */
  44762. var PlaybackWatcher = /*#__PURE__*/function () {
  44763. /**
  44764. * Represents an PlaybackWatcher object.
  44765. *
  44766. * @class
  44767. * @param {Object} options an object that includes the tech and settings
  44768. */
  44769. function PlaybackWatcher(options) {
  44770. var _this = this;
  44771. this.masterPlaylistController_ = options.masterPlaylistController;
  44772. this.tech_ = options.tech;
  44773. this.seekable = options.seekable;
  44774. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  44775. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  44776. this.media = options.media;
  44777. this.consecutiveUpdates = 0;
  44778. this.lastRecordedTime = null;
  44779. this.timer_ = null;
  44780. this.checkCurrentTimeTimeout_ = null;
  44781. this.logger_ = logger('PlaybackWatcher');
  44782. this.logger_('initialize');
  44783. var playHandler = function playHandler() {
  44784. return _this.monitorCurrentTime_();
  44785. };
  44786. var canPlayHandler = function canPlayHandler() {
  44787. return _this.monitorCurrentTime_();
  44788. };
  44789. var waitingHandler = function waitingHandler() {
  44790. return _this.techWaiting_();
  44791. };
  44792. var cancelTimerHandler = function cancelTimerHandler() {
  44793. return _this.cancelTimer_();
  44794. };
  44795. var mpc = this.masterPlaylistController_;
  44796. var loaderTypes = ['main', 'subtitle', 'audio'];
  44797. var loaderChecks = {};
  44798. loaderTypes.forEach(function (type) {
  44799. loaderChecks[type] = {
  44800. reset: function reset() {
  44801. return _this.resetSegmentDownloads_(type);
  44802. },
  44803. updateend: function updateend() {
  44804. return _this.checkSegmentDownloads_(type);
  44805. }
  44806. };
  44807. mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  44808. // isn't changing we want to reset. We cannot assume that the new rendition
  44809. // will also be stalled, until after new appends.
  44810. mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  44811. // This prevents one segment playlists (single vtt or single segment content)
  44812. // from being detected as stalling. As the buffer will not change in those cases, since
  44813. // the buffer is the entire video duration.
  44814. _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  44815. });
  44816. /**
  44817. * We check if a seek was into a gap through the following steps:
  44818. * 1. We get a seeking event and we do not get a seeked event. This means that
  44819. * a seek was attempted but not completed.
  44820. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  44821. * removed everything from our buffer and appended a segment, and should be ready
  44822. * to check for gaps.
  44823. */
  44824. var setSeekingHandlers = function setSeekingHandlers(fn) {
  44825. ['main', 'audio'].forEach(function (type) {
  44826. mpc[type + "SegmentLoader_"][fn]('appended', _this.seekingAppendCheck_);
  44827. });
  44828. };
  44829. this.seekingAppendCheck_ = function () {
  44830. if (_this.fixesBadSeeks_()) {
  44831. _this.consecutiveUpdates = 0;
  44832. _this.lastRecordedTime = _this.tech_.currentTime();
  44833. setSeekingHandlers('off');
  44834. }
  44835. };
  44836. this.clearSeekingAppendCheck_ = function () {
  44837. return setSeekingHandlers('off');
  44838. };
  44839. this.watchForBadSeeking_ = function () {
  44840. _this.clearSeekingAppendCheck_();
  44841. setSeekingHandlers('on');
  44842. };
  44843. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  44844. this.tech_.on('seeking', this.watchForBadSeeking_);
  44845. this.tech_.on('waiting', waitingHandler);
  44846. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  44847. this.tech_.on('canplay', canPlayHandler);
  44848. /*
  44849. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  44850. is surfaced in one of two ways:
  44851. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  44852. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  44853. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  44854. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  44855. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  44856. even if the player is in a playing state
  44857. */
  44858. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  44859. this.dispose = function () {
  44860. _this.clearSeekingAppendCheck_();
  44861. _this.logger_('dispose');
  44862. _this.tech_.off('waiting', waitingHandler);
  44863. _this.tech_.off(timerCancelEvents, cancelTimerHandler);
  44864. _this.tech_.off('canplay', canPlayHandler);
  44865. _this.tech_.off('play', playHandler);
  44866. _this.tech_.off('seeking', _this.watchForBadSeeking_);
  44867. _this.tech_.off('seeked', _this.clearSeekingAppendCheck_);
  44868. loaderTypes.forEach(function (type) {
  44869. mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
  44870. mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
  44871. _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  44872. });
  44873. if (_this.checkCurrentTimeTimeout_) {
  44874. window__default['default'].clearTimeout(_this.checkCurrentTimeTimeout_);
  44875. }
  44876. _this.cancelTimer_();
  44877. };
  44878. }
  44879. /**
  44880. * Periodically check current time to see if playback stopped
  44881. *
  44882. * @private
  44883. */
  44884. var _proto = PlaybackWatcher.prototype;
  44885. _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
  44886. this.checkCurrentTime_();
  44887. if (this.checkCurrentTimeTimeout_) {
  44888. window__default['default'].clearTimeout(this.checkCurrentTimeTimeout_);
  44889. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  44890. this.checkCurrentTimeTimeout_ = window__default['default'].setTimeout(this.monitorCurrentTime_.bind(this), 250);
  44891. }
  44892. /**
  44893. * Reset stalled download stats for a specific type of loader
  44894. *
  44895. * @param {string} type
  44896. * The segment loader type to check.
  44897. *
  44898. * @listens SegmentLoader#playlistupdate
  44899. * @listens Tech#seeking
  44900. * @listens Tech#seeked
  44901. */
  44902. ;
  44903. _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
  44904. var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
  44905. if (this[type + "StalledDownloads_"] > 0) {
  44906. this.logger_("resetting possible stalled download count for " + type + " loader");
  44907. }
  44908. this[type + "StalledDownloads_"] = 0;
  44909. this[type + "Buffered_"] = loader.buffered_();
  44910. }
  44911. /**
  44912. * Checks on every segment `appendsdone` to see
  44913. * if segment appends are making progress. If they are not
  44914. * and we are still downloading bytes. We blacklist the playlist.
  44915. *
  44916. * @param {string} type
  44917. * The segment loader type to check.
  44918. *
  44919. * @listens SegmentLoader#appendsdone
  44920. */
  44921. ;
  44922. _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
  44923. var mpc = this.masterPlaylistController_;
  44924. var loader = mpc[type + "SegmentLoader_"];
  44925. var buffered = loader.buffered_();
  44926. var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
  44927. this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
  44928. // the buffered value for this loader changed
  44929. // appends are working
  44930. if (isBufferedDifferent) {
  44931. this.resetSegmentDownloads_(type);
  44932. return;
  44933. }
  44934. this[type + "StalledDownloads_"]++;
  44935. this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
  44936. playlistId: loader.playlist_ && loader.playlist_.id,
  44937. buffered: timeRangesToArray(buffered)
  44938. }); // after 10 possibly stalled appends with no reset, exclude
  44939. if (this[type + "StalledDownloads_"] < 10) {
  44940. return;
  44941. }
  44942. this.logger_(type + " loader stalled download exclusion");
  44943. this.resetSegmentDownloads_(type);
  44944. this.tech_.trigger({
  44945. type: 'usage',
  44946. name: "vhs-" + type + "-download-exclusion"
  44947. });
  44948. if (type === 'subtitle') {
  44949. return;
  44950. } // TODO: should we exclude audio tracks rather than main tracks
  44951. // when type is audio?
  44952. mpc.blacklistCurrentPlaylist({
  44953. message: "Excessive " + type + " segment downloading detected."
  44954. }, Infinity);
  44955. }
  44956. /**
  44957. * The purpose of this function is to emulate the "waiting" event on
  44958. * browsers that do not emit it when they are waiting for more
  44959. * data to continue playback
  44960. *
  44961. * @private
  44962. */
  44963. ;
  44964. _proto.checkCurrentTime_ = function checkCurrentTime_() {
  44965. if (this.tech_.paused() || this.tech_.seeking()) {
  44966. return;
  44967. }
  44968. var currentTime = this.tech_.currentTime();
  44969. var buffered = this.tech_.buffered();
  44970. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  44971. // If current time is at the end of the final buffered region, then any playback
  44972. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  44973. // should fire a `waiting` event in this scenario, but due to browser and tech
  44974. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  44975. // responding to a native `waiting` event when the tech fails to emit one.
  44976. return this.techWaiting_();
  44977. }
  44978. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  44979. this.consecutiveUpdates++;
  44980. this.waiting_();
  44981. } else if (currentTime === this.lastRecordedTime) {
  44982. this.consecutiveUpdates++;
  44983. } else {
  44984. this.consecutiveUpdates = 0;
  44985. this.lastRecordedTime = currentTime;
  44986. }
  44987. }
  44988. /**
  44989. * Cancels any pending timers and resets the 'timeupdate' mechanism
  44990. * designed to detect that we are stalled
  44991. *
  44992. * @private
  44993. */
  44994. ;
  44995. _proto.cancelTimer_ = function cancelTimer_() {
  44996. this.consecutiveUpdates = 0;
  44997. if (this.timer_) {
  44998. this.logger_('cancelTimer_');
  44999. clearTimeout(this.timer_);
  45000. }
  45001. this.timer_ = null;
  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. ;
  45010. _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
  45011. var seeking = this.tech_.seeking();
  45012. if (!seeking) {
  45013. return false;
  45014. } // TODO: It's possible that these seekable checks should be moved out of this function
  45015. // and into a function that runs on seekablechange. It's also possible that we only need
  45016. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  45017. // seekable range.
  45018. var seekable = this.seekable();
  45019. var currentTime = this.tech_.currentTime();
  45020. var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  45021. var seekTo;
  45022. if (isAfterSeekableRange) {
  45023. var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  45024. seekTo = seekableEnd;
  45025. }
  45026. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45027. var seekableStart = seekable.start(0); // sync to the beginning of the live window
  45028. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  45029. seekTo = seekableStart + ( // 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. var sourceUpdater = this.masterPlaylistController_.sourceUpdater_;
  45039. var buffered = this.tech_.buffered();
  45040. var audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  45041. var videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  45042. var media = this.media(); // verify that at least two segment durations or one part duration have been
  45043. // appended before checking for a gap.
  45044. var 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. var bufferedToCheck = [audioBuffered, videoBuffered];
  45047. for (var i = 0; i < bufferedToCheck.length; i++) {
  45048. // skip null buffered
  45049. if (!bufferedToCheck[i]) {
  45050. continue;
  45051. }
  45052. var 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. var 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. ;
  45074. _proto.waiting_ = function waiting_() {
  45075. if (this.techWaiting_()) {
  45076. return;
  45077. } // All tech waiting checks failed. Use last resort correction
  45078. var currentTime = this.tech_.currentTime();
  45079. var buffered = this.tech_.buffered();
  45080. var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  45081. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  45082. // currentTime is usually enough to kickstart the player. This checks that the player
  45083. // is currently within a buffered region before attempting a corrective seek.
  45084. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  45085. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  45086. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  45087. // to avoid triggering an `unknownwaiting` event when the network is slow.
  45088. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  45089. this.cancelTimer_();
  45090. this.tech_.setCurrentTime(currentTime);
  45091. 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
  45092. this.tech_.trigger({
  45093. type: 'usage',
  45094. name: 'vhs-unknown-waiting'
  45095. });
  45096. this.tech_.trigger({
  45097. type: 'usage',
  45098. name: 'hls-unknown-waiting'
  45099. });
  45100. return;
  45101. }
  45102. }
  45103. /**
  45104. * Handler for situations when the tech fires a `waiting` event
  45105. *
  45106. * @return {boolean}
  45107. * True if an action (or none) was needed to correct the waiting. False if no
  45108. * checks passed
  45109. * @private
  45110. */
  45111. ;
  45112. _proto.techWaiting_ = function techWaiting_() {
  45113. var seekable = this.seekable();
  45114. var currentTime = this.tech_.currentTime();
  45115. if (this.tech_.seeking() || this.timer_ !== null) {
  45116. // Tech is seeking or already waiting on another action, no action needed
  45117. return true;
  45118. }
  45119. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  45120. var livePoint = seekable.end(seekable.length - 1);
  45121. this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
  45122. this.cancelTimer_();
  45123. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  45124. this.tech_.trigger({
  45125. type: 'usage',
  45126. name: 'vhs-live-resync'
  45127. });
  45128. this.tech_.trigger({
  45129. type: 'usage',
  45130. name: 'hls-live-resync'
  45131. });
  45132. return true;
  45133. }
  45134. var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
  45135. var buffered = this.tech_.buffered();
  45136. var videoUnderflow = this.videoUnderflow_({
  45137. audioBuffered: sourceUpdater.audioBuffered(),
  45138. videoBuffered: sourceUpdater.videoBuffered(),
  45139. currentTime: currentTime
  45140. });
  45141. if (videoUnderflow) {
  45142. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  45143. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  45144. // allows the video to catch up to the audio position without losing any audio
  45145. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  45146. this.cancelTimer_();
  45147. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  45148. this.tech_.trigger({
  45149. type: 'usage',
  45150. name: 'vhs-video-underflow'
  45151. });
  45152. this.tech_.trigger({
  45153. type: 'usage',
  45154. name: 'hls-video-underflow'
  45155. });
  45156. return true;
  45157. }
  45158. var nextRange = findNextRange(buffered, currentTime); // check for gap
  45159. if (nextRange.length > 0) {
  45160. var difference = nextRange.start(0) - currentTime;
  45161. this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
  45162. this.cancelTimer_();
  45163. this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
  45164. return true;
  45165. } // All checks failed. Returning false to indicate failure to correct waiting
  45166. return false;
  45167. };
  45168. _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
  45169. if (allowSeeksWithinUnsafeLiveWindow === void 0) {
  45170. allowSeeksWithinUnsafeLiveWindow = false;
  45171. }
  45172. if (!seekable.length) {
  45173. // we can't make a solid case if there's no seekable, default to false
  45174. return false;
  45175. }
  45176. var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  45177. var isLive = !playlist.endList;
  45178. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  45179. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  45180. }
  45181. if (currentTime > allowedEnd) {
  45182. return true;
  45183. }
  45184. return false;
  45185. };
  45186. _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
  45187. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  45188. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  45189. return true;
  45190. }
  45191. return false;
  45192. };
  45193. _proto.videoUnderflow_ = function videoUnderflow_(_ref) {
  45194. var videoBuffered = _ref.videoBuffered,
  45195. audioBuffered = _ref.audioBuffered,
  45196. currentTime = _ref.currentTime; // audio only content will not have video underflow :)
  45197. if (!videoBuffered) {
  45198. return;
  45199. }
  45200. var gap; // find a gap in demuxed content.
  45201. if (videoBuffered.length && audioBuffered.length) {
  45202. // in Chrome audio will continue to play for ~3s when we run out of video
  45203. // so we have to check that the video buffer did have some buffer in the
  45204. // past.
  45205. var lastVideoRange = findRange(videoBuffered, currentTime - 3);
  45206. var videoRange = findRange(videoBuffered, currentTime);
  45207. var audioRange = findRange(audioBuffered, currentTime);
  45208. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  45209. gap = {
  45210. start: lastVideoRange.end(0),
  45211. end: audioRange.end(0)
  45212. };
  45213. } // find a gap in muxed content.
  45214. } else {
  45215. var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  45216. // stuck in a gap due to video underflow.
  45217. if (!nextRange.length) {
  45218. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  45219. }
  45220. }
  45221. if (gap) {
  45222. this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
  45223. return true;
  45224. }
  45225. return false;
  45226. }
  45227. /**
  45228. * Timer callback. If playback still has not proceeded, then we seek
  45229. * to the start of the next buffered region.
  45230. *
  45231. * @private
  45232. */
  45233. ;
  45234. _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
  45235. var buffered = this.tech_.buffered();
  45236. var currentTime = this.tech_.currentTime();
  45237. var nextRange = findNextRange(buffered, currentTime);
  45238. this.cancelTimer_();
  45239. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  45240. return;
  45241. }
  45242. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  45243. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  45244. this.tech_.trigger({
  45245. type: 'usage',
  45246. name: 'vhs-gap-skip'
  45247. });
  45248. this.tech_.trigger({
  45249. type: 'usage',
  45250. name: 'hls-gap-skip'
  45251. });
  45252. };
  45253. _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
  45254. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  45255. // playing for ~3 seconds after the video gap starts. This is done to account for
  45256. // video buffer underflow/underrun (note that this is not done when there is audio
  45257. // buffer underflow/underrun -- in that case the video will stop as soon as it
  45258. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  45259. // video stalls). The player's time will reflect the playthrough of audio, so the
  45260. // time will appear as if we are in a buffered region, even if we are stuck in a
  45261. // "gap."
  45262. //
  45263. // Example:
  45264. // video buffer: 0 => 10.1, 10.2 => 20
  45265. // audio buffer: 0 => 20
  45266. // overall buffer: 0 => 10.1, 10.2 => 20
  45267. // current time: 13
  45268. //
  45269. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  45270. // however, the audio continued playing until it reached ~3 seconds past the gap
  45271. // (13 seconds), at which point it stops as well. Since current time is past the
  45272. // gap, findNextRange will return no ranges.
  45273. //
  45274. // To check for this issue, we see if there is a gap that starts somewhere within
  45275. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  45276. var gaps = findGaps(buffered);
  45277. for (var i = 0; i < gaps.length; i++) {
  45278. var start = gaps.start(i);
  45279. var end = gaps.end(i); // gap is starts no more than 4 seconds back
  45280. if (currentTime - start < 4 && currentTime - start > 2) {
  45281. return {
  45282. start: start,
  45283. end: end
  45284. };
  45285. }
  45286. }
  45287. return null;
  45288. };
  45289. return PlaybackWatcher;
  45290. }();
  45291. var defaultOptions = {
  45292. errorInterval: 30,
  45293. getSource: function getSource(next) {
  45294. var tech = this.tech({
  45295. IWillNotUseThisInPlugins: true
  45296. });
  45297. var sourceObj = tech.currentSource_ || this.currentSource();
  45298. return next(sourceObj);
  45299. }
  45300. };
  45301. /**
  45302. * Main entry point for the plugin
  45303. *
  45304. * @param {Player} player a reference to a videojs Player instance
  45305. * @param {Object} [options] an object with plugin options
  45306. * @private
  45307. */
  45308. var initPlugin = function initPlugin(player, options) {
  45309. var lastCalled = 0;
  45310. var seekTo = 0;
  45311. var localOptions = videojs.mergeOptions(defaultOptions, options);
  45312. player.ready(function () {
  45313. player.trigger({
  45314. type: 'usage',
  45315. name: 'vhs-error-reload-initialized'
  45316. });
  45317. player.trigger({
  45318. type: 'usage',
  45319. name: 'hls-error-reload-initialized'
  45320. });
  45321. });
  45322. /**
  45323. * Player modifications to perform that must wait until `loadedmetadata`
  45324. * has been triggered
  45325. *
  45326. * @private
  45327. */
  45328. var loadedMetadataHandler = function loadedMetadataHandler() {
  45329. if (seekTo) {
  45330. player.currentTime(seekTo);
  45331. }
  45332. };
  45333. /**
  45334. * Set the source on the player element, play, and seek if necessary
  45335. *
  45336. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  45337. * @private
  45338. */
  45339. var setSource = function setSource(sourceObj) {
  45340. if (sourceObj === null || sourceObj === undefined) {
  45341. return;
  45342. }
  45343. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  45344. player.one('loadedmetadata', loadedMetadataHandler);
  45345. player.src(sourceObj);
  45346. player.trigger({
  45347. type: 'usage',
  45348. name: 'vhs-error-reload'
  45349. });
  45350. player.trigger({
  45351. type: 'usage',
  45352. name: 'hls-error-reload'
  45353. });
  45354. player.play();
  45355. };
  45356. /**
  45357. * Attempt to get a source from either the built-in getSource function
  45358. * or a custom function provided via the options
  45359. *
  45360. * @private
  45361. */
  45362. var errorHandler = function errorHandler() {
  45363. // Do not attempt to reload the source if a source-reload occurred before
  45364. // 'errorInterval' time has elapsed since the last source-reload
  45365. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  45366. player.trigger({
  45367. type: 'usage',
  45368. name: 'vhs-error-reload-canceled'
  45369. });
  45370. player.trigger({
  45371. type: 'usage',
  45372. name: 'hls-error-reload-canceled'
  45373. });
  45374. return;
  45375. }
  45376. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  45377. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  45378. return;
  45379. }
  45380. lastCalled = Date.now();
  45381. return localOptions.getSource.call(player, setSource);
  45382. };
  45383. /**
  45384. * Unbind any event handlers that were bound by the plugin
  45385. *
  45386. * @private
  45387. */
  45388. var cleanupEvents = function cleanupEvents() {
  45389. player.off('loadedmetadata', loadedMetadataHandler);
  45390. player.off('error', errorHandler);
  45391. player.off('dispose', cleanupEvents);
  45392. };
  45393. /**
  45394. * Cleanup before re-initializing the plugin
  45395. *
  45396. * @param {Object} [newOptions] an object with plugin options
  45397. * @private
  45398. */
  45399. var reinitPlugin = function reinitPlugin(newOptions) {
  45400. cleanupEvents();
  45401. initPlugin(player, newOptions);
  45402. };
  45403. player.on('error', errorHandler);
  45404. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  45405. // initializing the plugin
  45406. player.reloadSourceOnError = reinitPlugin;
  45407. };
  45408. /**
  45409. * Reload the source when an error is detected as long as there
  45410. * wasn't an error previously within the last 30 seconds
  45411. *
  45412. * @param {Object} [options] an object with plugin options
  45413. */
  45414. var reloadSourceOnError = function reloadSourceOnError(options) {
  45415. initPlugin(this, options);
  45416. };
  45417. var version$4 = "2.16.2";
  45418. var version$3 = "6.0.1";
  45419. var version$2 = "0.22.1";
  45420. var version$1 = "4.8.0";
  45421. var version = "3.1.3";
  45422. var Vhs = {
  45423. PlaylistLoader: PlaylistLoader,
  45424. Playlist: Playlist,
  45425. utils: utils,
  45426. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  45427. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  45428. lastBandwidthSelector: lastBandwidthSelector,
  45429. movingAverageBandwidthSelector: movingAverageBandwidthSelector,
  45430. comparePlaylistBandwidth: comparePlaylistBandwidth,
  45431. comparePlaylistResolution: comparePlaylistResolution,
  45432. xhr: xhrFactory()
  45433. }; // Define getter/setters for config properties
  45434. Object.keys(Config).forEach(function (prop) {
  45435. Object.defineProperty(Vhs, prop, {
  45436. get: function get() {
  45437. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  45438. return Config[prop];
  45439. },
  45440. set: function set(value) {
  45441. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  45442. if (typeof value !== 'number' || value < 0) {
  45443. videojs.log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
  45444. return;
  45445. }
  45446. Config[prop] = value;
  45447. }
  45448. });
  45449. });
  45450. var LOCAL_STORAGE_KEY = 'videojs-vhs';
  45451. /**
  45452. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  45453. *
  45454. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  45455. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  45456. * @function handleVhsMediaChange
  45457. */
  45458. var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
  45459. var newPlaylist = playlistLoader.media();
  45460. var selectedIndex = -1;
  45461. for (var i = 0; i < qualityLevels.length; i++) {
  45462. if (qualityLevels[i].id === newPlaylist.id) {
  45463. selectedIndex = i;
  45464. break;
  45465. }
  45466. }
  45467. qualityLevels.selectedIndex_ = selectedIndex;
  45468. qualityLevels.trigger({
  45469. selectedIndex: selectedIndex,
  45470. type: 'change'
  45471. });
  45472. };
  45473. /**
  45474. * Adds quality levels to list once playlist metadata is available
  45475. *
  45476. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  45477. * @param {Object} vhs Vhs object to listen to for media events.
  45478. * @function handleVhsLoadedMetadata
  45479. */
  45480. var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
  45481. vhs.representations().forEach(function (rep) {
  45482. qualityLevels.addQualityLevel(rep);
  45483. });
  45484. handleVhsMediaChange(qualityLevels, vhs.playlists);
  45485. }; // HLS is a source handler, not a tech. Make sure attempts to use it
  45486. // as one do not cause exceptions.
  45487. Vhs.canPlaySource = function () {
  45488. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45489. };
  45490. var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
  45491. if (!keySystemOptions) {
  45492. return keySystemOptions;
  45493. }
  45494. var codecs = {};
  45495. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  45496. codecs = unwrapCodecList(codecs_js.parseCodecs(mainPlaylist.attributes.CODECS));
  45497. }
  45498. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  45499. codecs.audio = audioPlaylist.attributes.CODECS;
  45500. }
  45501. var videoContentType = codecs_js.getMimeForCodec(codecs.video);
  45502. var audioContentType = codecs_js.getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  45503. var keySystemContentTypes = {};
  45504. for (var keySystem in keySystemOptions) {
  45505. keySystemContentTypes[keySystem] = {};
  45506. if (audioContentType) {
  45507. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  45508. }
  45509. if (videoContentType) {
  45510. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  45511. } // Default to using the video playlist's PSSH even though they may be different, as
  45512. // videojs-contrib-eme will only accept one in the options.
  45513. //
  45514. // This shouldn't be an issue for most cases as early intialization will handle all
  45515. // unique PSSH values, and if they aren't, then encrypted events should have the
  45516. // specific information needed for the unique license.
  45517. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  45518. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  45519. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  45520. // so we need to prevent overwriting the URL entirely
  45521. if (typeof keySystemOptions[keySystem] === 'string') {
  45522. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  45523. }
  45524. }
  45525. return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
  45526. };
  45527. /**
  45528. * @typedef {Object} KeySystems
  45529. *
  45530. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  45531. * Note: not all options are listed here.
  45532. *
  45533. * @property {Uint8Array} [pssh]
  45534. * Protection System Specific Header
  45535. */
  45536. /**
  45537. * Goes through all the playlists and collects an array of KeySystems options objects
  45538. * containing each playlist's keySystems and their pssh values, if available.
  45539. *
  45540. * @param {Object[]} playlists
  45541. * The playlists to look through
  45542. * @param {string[]} keySystems
  45543. * The keySystems to collect pssh values for
  45544. *
  45545. * @return {KeySystems[]}
  45546. * An array of KeySystems objects containing available key systems and their
  45547. * pssh values
  45548. */
  45549. var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
  45550. return playlists.reduce(function (keySystemsArr, playlist) {
  45551. if (!playlist.contentProtection) {
  45552. return keySystemsArr;
  45553. }
  45554. var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
  45555. var keySystemOptions = playlist.contentProtection[keySystem];
  45556. if (keySystemOptions && keySystemOptions.pssh) {
  45557. keySystemsObj[keySystem] = {
  45558. pssh: keySystemOptions.pssh
  45559. };
  45560. }
  45561. return keySystemsObj;
  45562. }, {});
  45563. if (Object.keys(keySystemsOptions).length) {
  45564. keySystemsArr.push(keySystemsOptions);
  45565. }
  45566. return keySystemsArr;
  45567. }, []);
  45568. };
  45569. /**
  45570. * Returns a promise that waits for the
  45571. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  45572. *
  45573. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  45574. * browsers.
  45575. *
  45576. * As per the above ticket, this is particularly important for Chrome, where, if
  45577. * unencrypted content is appended before encrypted content and the key session has not
  45578. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  45579. * during playback.
  45580. *
  45581. * @param {Object} player
  45582. * The player instance
  45583. * @param {Object[]} sourceKeySystems
  45584. * The key systems options from the player source
  45585. * @param {Object} [audioMedia]
  45586. * The active audio media playlist (optional)
  45587. * @param {Object[]} mainPlaylists
  45588. * The playlists found on the master playlist object
  45589. *
  45590. * @return {Object}
  45591. * Promise that resolves when the key session has been created
  45592. */
  45593. var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
  45594. var player = _ref.player,
  45595. sourceKeySystems = _ref.sourceKeySystems,
  45596. audioMedia = _ref.audioMedia,
  45597. mainPlaylists = _ref.mainPlaylists;
  45598. if (!player.eme.initializeMediaKeys) {
  45599. return Promise.resolve();
  45600. } // TODO should all audio PSSH values be initialized for DRM?
  45601. //
  45602. // All unique video rendition pssh values are initialized for DRM, but here only
  45603. // the initial audio playlist license is initialized. In theory, an encrypted
  45604. // event should be fired if the user switches to an alternative audio playlist
  45605. // where a license is required, but this case hasn't yet been tested. In addition, there
  45606. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  45607. // languages).
  45608. var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  45609. var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  45610. var initializationFinishedPromises = [];
  45611. var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  45612. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  45613. // return for IE11 above, and the existence of modern EME APIs in addition to
  45614. // ms-prefixed APIs on Edge should prevent this from being a concern.
  45615. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  45616. keySystemsOptionsArr.forEach(function (keySystemsOptions) {
  45617. keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
  45618. player.tech_.one('keysessioncreated', resolve);
  45619. }));
  45620. initializationFinishedPromises.push(new Promise(function (resolve, reject) {
  45621. player.eme.initializeMediaKeys({
  45622. keySystems: keySystemsOptions
  45623. }, function (err) {
  45624. if (err) {
  45625. reject(err);
  45626. return;
  45627. }
  45628. resolve();
  45629. });
  45630. }));
  45631. }); // The reasons Promise.race is chosen over Promise.any:
  45632. //
  45633. // * Promise.any is only available in Safari 14+.
  45634. // * None of these promises are expected to reject. If they do reject, it might be
  45635. // better here for the race to surface the rejection, rather than mask it by using
  45636. // Promise.any.
  45637. return Promise.race([// If a session was previously created, these will all finish resolving without
  45638. // creating a new session, otherwise it will take until the end of all license
  45639. // requests, which is why the key session check is used (to make setup much faster).
  45640. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  45641. Promise.race(keySessionCreatedPromises)]);
  45642. };
  45643. /**
  45644. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  45645. * there are keySystems on the source, sets up source options to prepare the source for
  45646. * eme.
  45647. *
  45648. * @param {Object} player
  45649. * The player instance
  45650. * @param {Object[]} sourceKeySystems
  45651. * The key systems options from the player source
  45652. * @param {Object} media
  45653. * The active media playlist
  45654. * @param {Object} [audioMedia]
  45655. * The active audio media playlist (optional)
  45656. *
  45657. * @return {boolean}
  45658. * Whether or not options were configured and EME is available
  45659. */
  45660. var setupEmeOptions = function setupEmeOptions(_ref2) {
  45661. var player = _ref2.player,
  45662. sourceKeySystems = _ref2.sourceKeySystems,
  45663. media = _ref2.media,
  45664. audioMedia = _ref2.audioMedia;
  45665. var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  45666. if (!sourceOptions) {
  45667. return false;
  45668. }
  45669. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  45670. // do nothing.
  45671. if (sourceOptions && !player.eme) {
  45672. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  45673. return false;
  45674. }
  45675. return true;
  45676. };
  45677. var getVhsLocalStorage = function getVhsLocalStorage() {
  45678. if (!window__default['default'].localStorage) {
  45679. return null;
  45680. }
  45681. var storedObject = window__default['default'].localStorage.getItem(LOCAL_STORAGE_KEY);
  45682. if (!storedObject) {
  45683. return null;
  45684. }
  45685. try {
  45686. return JSON.parse(storedObject);
  45687. } catch (e) {
  45688. // someone may have tampered with the value
  45689. return null;
  45690. }
  45691. };
  45692. var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
  45693. if (!window__default['default'].localStorage) {
  45694. return false;
  45695. }
  45696. var objectToStore = getVhsLocalStorage();
  45697. objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
  45698. try {
  45699. window__default['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  45700. } catch (e) {
  45701. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  45702. // storage is set to 0).
  45703. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  45704. // No need to perform any operation.
  45705. return false;
  45706. }
  45707. return objectToStore;
  45708. };
  45709. /**
  45710. * Parses VHS-supported media types from data URIs. See
  45711. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  45712. * for information on data URIs.
  45713. *
  45714. * @param {string} dataUri
  45715. * The data URI
  45716. *
  45717. * @return {string|Object}
  45718. * The parsed object/string, or the original string if no supported media type
  45719. * was found
  45720. */
  45721. var expandDataUri = function expandDataUri(dataUri) {
  45722. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  45723. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  45724. } // no known case for this data URI, return the string as-is
  45725. return dataUri;
  45726. };
  45727. /**
  45728. * Whether the browser has built-in HLS support.
  45729. */
  45730. Vhs.supportsNativeHls = function () {
  45731. if (!document__default['default'] || !document__default['default'].createElement) {
  45732. return false;
  45733. }
  45734. var video = document__default['default'].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  45735. if (!videojs.getTech('Html5').isSupported()) {
  45736. return false;
  45737. } // HLS manifests can go by many mime-types
  45738. var canPlay = [// Apple santioned
  45739. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  45740. 'audio/mpegurl', // Very common
  45741. 'audio/x-mpegurl', // Very common
  45742. 'application/x-mpegurl', // Included for completeness
  45743. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  45744. return canPlay.some(function (canItPlay) {
  45745. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  45746. });
  45747. }();
  45748. Vhs.supportsNativeDash = function () {
  45749. if (!document__default['default'] || !document__default['default'].createElement || !videojs.getTech('Html5').isSupported()) {
  45750. return false;
  45751. }
  45752. return /maybe|probably/i.test(document__default['default'].createElement('video').canPlayType('application/dash+xml'));
  45753. }();
  45754. Vhs.supportsTypeNatively = function (type) {
  45755. if (type === 'hls') {
  45756. return Vhs.supportsNativeHls;
  45757. }
  45758. if (type === 'dash') {
  45759. return Vhs.supportsNativeDash;
  45760. }
  45761. return false;
  45762. };
  45763. /**
  45764. * HLS is a source handler, not a tech. Make sure attempts to use it
  45765. * as one do not cause exceptions.
  45766. */
  45767. Vhs.isSupported = function () {
  45768. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  45769. };
  45770. var Component = videojs.getComponent('Component');
  45771. /**
  45772. * The Vhs Handler object, where we orchestrate all of the parts
  45773. * of HLS to interact with video.js
  45774. *
  45775. * @class VhsHandler
  45776. * @extends videojs.Component
  45777. * @param {Object} source the soruce object
  45778. * @param {Tech} tech the parent tech object
  45779. * @param {Object} options optional and required options
  45780. */
  45781. var VhsHandler = /*#__PURE__*/function (_Component) {
  45782. _inheritsLoose__default['default'](VhsHandler, _Component);
  45783. function VhsHandler(source, tech, options) {
  45784. var _this;
  45785. _this = _Component.call(this, tech, videojs.mergeOptions(options.hls, options.vhs)) || this;
  45786. if (options.hls && Object.keys(options.hls).length) {
  45787. videojs.log.warn('Using hls options is deprecated. Please rename `hls` to `vhs` in your options object.');
  45788. } // if a tech level `initialBandwidth` option was passed
  45789. // use that over the VHS level `bandwidth` option
  45790. if (typeof options.initialBandwidth === 'number') {
  45791. _this.options_.bandwidth = options.initialBandwidth;
  45792. }
  45793. _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
  45794. // backwards-compatibility
  45795. if (tech.options_ && tech.options_.playerId) {
  45796. var _player = videojs(tech.options_.playerId);
  45797. if (!_player.hasOwnProperty('hls')) {
  45798. Object.defineProperty(_player, 'hls', {
  45799. get: function get() {
  45800. videojs.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
  45801. tech.trigger({
  45802. type: 'usage',
  45803. name: 'hls-player-access'
  45804. });
  45805. return _assertThisInitialized__default['default'](_this);
  45806. },
  45807. configurable: true
  45808. });
  45809. }
  45810. if (!_player.hasOwnProperty('vhs')) {
  45811. Object.defineProperty(_player, 'vhs', {
  45812. get: function get() {
  45813. videojs.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
  45814. tech.trigger({
  45815. type: 'usage',
  45816. name: 'vhs-player-access'
  45817. });
  45818. return _assertThisInitialized__default['default'](_this);
  45819. },
  45820. configurable: true
  45821. });
  45822. }
  45823. if (!_player.hasOwnProperty('dash')) {
  45824. Object.defineProperty(_player, 'dash', {
  45825. get: function get() {
  45826. videojs.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
  45827. return _assertThisInitialized__default['default'](_this);
  45828. },
  45829. configurable: true
  45830. });
  45831. }
  45832. _this.player_ = _player;
  45833. }
  45834. _this.tech_ = tech;
  45835. _this.source_ = source;
  45836. _this.stats = {};
  45837. _this.ignoreNextSeekingEvent_ = false;
  45838. _this.setOptions_();
  45839. if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  45840. tech.overrideNativeAudioTracks(true);
  45841. tech.overrideNativeVideoTracks(true);
  45842. } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  45843. // overriding native HLS only works if audio tracks have been emulated
  45844. // error early if we're misconfigured
  45845. throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  45846. } // listen for fullscreenchange events for this player so that we
  45847. // can adjust our quality selection quickly
  45848. _this.on(document__default['default'], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
  45849. var fullscreenElement = document__default['default'].fullscreenElement || document__default['default'].webkitFullscreenElement || document__default['default'].mozFullScreenElement || document__default['default'].msFullscreenElement;
  45850. if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
  45851. _this.masterPlaylistController_.fastQualityChange_();
  45852. } else {
  45853. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  45854. // than full screen, see if there should be a rendition switch down to preserve
  45855. // bandwidth.
  45856. _this.masterPlaylistController_.checkABR_();
  45857. }
  45858. });
  45859. _this.on(_this.tech_, 'seeking', function () {
  45860. if (this.ignoreNextSeekingEvent_) {
  45861. this.ignoreNextSeekingEvent_ = false;
  45862. return;
  45863. }
  45864. this.setCurrentTime(this.tech_.currentTime());
  45865. });
  45866. _this.on(_this.tech_, 'error', function () {
  45867. // verify that the error was real and we are loaded
  45868. // enough to have mpc loaded.
  45869. if (this.tech_.error() && this.masterPlaylistController_) {
  45870. this.masterPlaylistController_.pauseLoading();
  45871. }
  45872. });
  45873. _this.on(_this.tech_, 'play', _this.play);
  45874. return _this;
  45875. }
  45876. var _proto = VhsHandler.prototype;
  45877. _proto.setOptions_ = function setOptions_() {
  45878. var _this2 = this; // defaults
  45879. this.options_.withCredentials = this.options_.withCredentials || false;
  45880. this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
  45881. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  45882. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  45883. this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
  45884. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  45885. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  45886. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  45887. this.options_.customTagParsers = this.options_.customTagParsers || [];
  45888. this.options_.customTagMappers = this.options_.customTagMappers || [];
  45889. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  45890. if (typeof this.options_.blacklistDuration !== 'number') {
  45891. this.options_.blacklistDuration = 5 * 60;
  45892. }
  45893. if (typeof this.options_.bandwidth !== 'number') {
  45894. if (this.options_.useBandwidthFromLocalStorage) {
  45895. var storedObject = getVhsLocalStorage();
  45896. if (storedObject && storedObject.bandwidth) {
  45897. this.options_.bandwidth = storedObject.bandwidth;
  45898. this.tech_.trigger({
  45899. type: 'usage',
  45900. name: 'vhs-bandwidth-from-local-storage'
  45901. });
  45902. this.tech_.trigger({
  45903. type: 'usage',
  45904. name: 'hls-bandwidth-from-local-storage'
  45905. });
  45906. }
  45907. if (storedObject && storedObject.throughput) {
  45908. this.options_.throughput = storedObject.throughput;
  45909. this.tech_.trigger({
  45910. type: 'usage',
  45911. name: 'vhs-throughput-from-local-storage'
  45912. });
  45913. this.tech_.trigger({
  45914. type: 'usage',
  45915. name: 'hls-throughput-from-local-storage'
  45916. });
  45917. }
  45918. }
  45919. } // if bandwidth was not set by options or pulled from local storage, start playlist
  45920. // selection at a reasonable bandwidth
  45921. if (typeof this.options_.bandwidth !== 'number') {
  45922. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  45923. } // If the bandwidth number is unchanged from the initial setting
  45924. // then this takes precedence over the enableLowInitialPlaylist option
  45925. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  45926. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'experimentalExactManifestTimings', 'experimentalLeastPixelDiffSelector'].forEach(function (option) {
  45927. if (typeof _this2.source_[option] !== 'undefined') {
  45928. _this2.options_[option] = _this2.source_[option];
  45929. }
  45930. });
  45931. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  45932. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  45933. }
  45934. /**
  45935. * called when player.src gets called, handle a new source
  45936. *
  45937. * @param {Object} src the source object to handle
  45938. */
  45939. ;
  45940. _proto.src = function src(_src, type) {
  45941. var _this3 = this; // do nothing if the src is falsey
  45942. if (!_src) {
  45943. return;
  45944. }
  45945. this.setOptions_(); // add master playlist controller options
  45946. this.options_.src = expandDataUri(this.source_.src);
  45947. this.options_.tech = this.tech_;
  45948. this.options_.externVhs = Vhs;
  45949. this.options_.sourceType = mediaTypes_js.simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  45950. this.options_.seekTo = function (time) {
  45951. _this3.tech_.setCurrentTime(time);
  45952. };
  45953. if (this.options_.smoothQualityChange) {
  45954. videojs.log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
  45955. }
  45956. this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
  45957. var playbackWatcherOptions = videojs.mergeOptions({
  45958. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  45959. }, this.options_, {
  45960. seekable: function seekable() {
  45961. return _this3.seekable();
  45962. },
  45963. media: function media() {
  45964. return _this3.masterPlaylistController_.media();
  45965. },
  45966. masterPlaylistController: this.masterPlaylistController_
  45967. });
  45968. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  45969. this.masterPlaylistController_.on('error', function () {
  45970. var player = videojs.players[_this3.tech_.options_.playerId];
  45971. var error = _this3.masterPlaylistController_.error;
  45972. if (typeof error === 'object' && !error.code) {
  45973. error.code = 3;
  45974. } else if (typeof error === 'string') {
  45975. error = {
  45976. message: error,
  45977. code: 3
  45978. };
  45979. }
  45980. player.error(error);
  45981. });
  45982. var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  45983. // compatibility with < v2
  45984. this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  45985. this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  45986. this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
  45987. this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
  45988. // controller. Using a custom property for backwards compatibility
  45989. // with < v2
  45990. Object.defineProperties(this, {
  45991. selectPlaylist: {
  45992. get: function get() {
  45993. return this.masterPlaylistController_.selectPlaylist;
  45994. },
  45995. set: function set(selectPlaylist) {
  45996. this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
  45997. }
  45998. },
  45999. throughput: {
  46000. get: function get() {
  46001. return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
  46002. },
  46003. set: function set(throughput) {
  46004. this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  46005. // for the cumulative average
  46006. this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
  46007. }
  46008. },
  46009. bandwidth: {
  46010. get: function get() {
  46011. var playerBandwidthEst = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  46012. var networkInformation = window__default['default'].navigator.connection || window__default['default'].navigator.mozConnection || window__default['default'].navigator.webkitConnection;
  46013. var tenMbpsAsBitsPerSecond = 10e6;
  46014. if (this.options_.useNetworkInformationApi && networkInformation) {
  46015. // downlink returns Mbps
  46016. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  46017. var networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  46018. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  46019. // high quality streams are not filtered out.
  46020. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  46021. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  46022. } else {
  46023. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  46024. }
  46025. }
  46026. return playerBandwidthEst;
  46027. },
  46028. set: function set(bandwidth) {
  46029. this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  46030. // `count` is set to zero that current value of `rate` isn't included
  46031. // in the cumulative average
  46032. this.masterPlaylistController_.mainSegmentLoader_.throughput = {
  46033. rate: 0,
  46034. count: 0
  46035. };
  46036. }
  46037. },
  46038. /**
  46039. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  46040. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  46041. * the entire process after that - decryption, transmuxing, and appending - provided
  46042. * by `throughput`.
  46043. *
  46044. * Since the two process are serial, the overall system bandwidth is given by:
  46045. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  46046. */
  46047. systemBandwidth: {
  46048. get: function get() {
  46049. var invBandwidth = 1 / (this.bandwidth || 1);
  46050. var invThroughput;
  46051. if (this.throughput > 0) {
  46052. invThroughput = 1 / this.throughput;
  46053. } else {
  46054. invThroughput = 0;
  46055. }
  46056. var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  46057. return systemBitrate;
  46058. },
  46059. set: function set() {
  46060. videojs.log.error('The "systemBandwidth" property is read-only');
  46061. }
  46062. }
  46063. });
  46064. if (this.options_.bandwidth) {
  46065. this.bandwidth = this.options_.bandwidth;
  46066. }
  46067. if (this.options_.throughput) {
  46068. this.throughput = this.options_.throughput;
  46069. }
  46070. Object.defineProperties(this.stats, {
  46071. bandwidth: {
  46072. get: function get() {
  46073. return _this3.bandwidth || 0;
  46074. },
  46075. enumerable: true
  46076. },
  46077. mediaRequests: {
  46078. get: function get() {
  46079. return _this3.masterPlaylistController_.mediaRequests_() || 0;
  46080. },
  46081. enumerable: true
  46082. },
  46083. mediaRequestsAborted: {
  46084. get: function get() {
  46085. return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
  46086. },
  46087. enumerable: true
  46088. },
  46089. mediaRequestsTimedout: {
  46090. get: function get() {
  46091. return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
  46092. },
  46093. enumerable: true
  46094. },
  46095. mediaRequestsErrored: {
  46096. get: function get() {
  46097. return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
  46098. },
  46099. enumerable: true
  46100. },
  46101. mediaTransferDuration: {
  46102. get: function get() {
  46103. return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
  46104. },
  46105. enumerable: true
  46106. },
  46107. mediaBytesTransferred: {
  46108. get: function get() {
  46109. return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
  46110. },
  46111. enumerable: true
  46112. },
  46113. mediaSecondsLoaded: {
  46114. get: function get() {
  46115. return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
  46116. },
  46117. enumerable: true
  46118. },
  46119. mediaAppends: {
  46120. get: function get() {
  46121. return _this3.masterPlaylistController_.mediaAppends_() || 0;
  46122. },
  46123. enumerable: true
  46124. },
  46125. mainAppendsToLoadedData: {
  46126. get: function get() {
  46127. return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
  46128. },
  46129. enumerable: true
  46130. },
  46131. audioAppendsToLoadedData: {
  46132. get: function get() {
  46133. return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
  46134. },
  46135. enumerable: true
  46136. },
  46137. appendsToLoadedData: {
  46138. get: function get() {
  46139. return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
  46140. },
  46141. enumerable: true
  46142. },
  46143. timeToLoadedData: {
  46144. get: function get() {
  46145. return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
  46146. },
  46147. enumerable: true
  46148. },
  46149. buffered: {
  46150. get: function get() {
  46151. return timeRangesToArray(_this3.tech_.buffered());
  46152. },
  46153. enumerable: true
  46154. },
  46155. currentTime: {
  46156. get: function get() {
  46157. return _this3.tech_.currentTime();
  46158. },
  46159. enumerable: true
  46160. },
  46161. currentSource: {
  46162. get: function get() {
  46163. return _this3.tech_.currentSource_;
  46164. },
  46165. enumerable: true
  46166. },
  46167. currentTech: {
  46168. get: function get() {
  46169. return _this3.tech_.name_;
  46170. },
  46171. enumerable: true
  46172. },
  46173. duration: {
  46174. get: function get() {
  46175. return _this3.tech_.duration();
  46176. },
  46177. enumerable: true
  46178. },
  46179. master: {
  46180. get: function get() {
  46181. return _this3.playlists.master;
  46182. },
  46183. enumerable: true
  46184. },
  46185. playerDimensions: {
  46186. get: function get() {
  46187. return _this3.tech_.currentDimensions();
  46188. },
  46189. enumerable: true
  46190. },
  46191. seekable: {
  46192. get: function get() {
  46193. return timeRangesToArray(_this3.tech_.seekable());
  46194. },
  46195. enumerable: true
  46196. },
  46197. timestamp: {
  46198. get: function get() {
  46199. return Date.now();
  46200. },
  46201. enumerable: true
  46202. },
  46203. videoPlaybackQuality: {
  46204. get: function get() {
  46205. return _this3.tech_.getVideoPlaybackQuality();
  46206. },
  46207. enumerable: true
  46208. }
  46209. });
  46210. this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
  46211. this.tech_.on('bandwidthupdate', function () {
  46212. if (_this3.options_.useBandwidthFromLocalStorage) {
  46213. updateVhsLocalStorage({
  46214. bandwidth: _this3.bandwidth,
  46215. throughput: Math.round(_this3.throughput)
  46216. });
  46217. }
  46218. });
  46219. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  46220. // Add the manual rendition mix-in to VhsHandler
  46221. renditionSelectionMixin(_this3);
  46222. });
  46223. this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
  46224. _this3.setupEme_();
  46225. }); // the bandwidth of the primary segment loader is our best
  46226. // estimate of overall bandwidth
  46227. this.on(this.masterPlaylistController_, 'progress', function () {
  46228. this.tech_.trigger('progress');
  46229. }); // In the live case, we need to ignore the very first `seeking` event since
  46230. // that will be the result of the seek-to-live behavior
  46231. this.on(this.masterPlaylistController_, 'firstplay', function () {
  46232. this.ignoreNextSeekingEvent_ = true;
  46233. });
  46234. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  46235. // this can occur if someone sets the src in player.ready(), for instance
  46236. if (!this.tech_.el()) {
  46237. return;
  46238. }
  46239. this.mediaSourceUrl_ = window__default['default'].URL.createObjectURL(this.masterPlaylistController_.mediaSource);
  46240. this.tech_.src(this.mediaSourceUrl_);
  46241. };
  46242. _proto.createKeySessions_ = function createKeySessions_() {
  46243. var _this4 = this;
  46244. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46245. this.logger_('waiting for EME key session creation');
  46246. waitForKeySessionCreation({
  46247. player: this.player_,
  46248. sourceKeySystems: this.source_.keySystems,
  46249. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  46250. mainPlaylists: this.playlists.master.playlists
  46251. }).then(function () {
  46252. _this4.logger_('created EME key session');
  46253. _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
  46254. })["catch"](function (err) {
  46255. _this4.logger_('error while creating EME key session', err);
  46256. _this4.player_.error({
  46257. message: 'Failed to initialize media keys for EME',
  46258. code: 3
  46259. });
  46260. });
  46261. };
  46262. _proto.handleWaitingForKey_ = function handleWaitingForKey_() {
  46263. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  46264. // the key is in the manifest. While this should've happened on initial source load, it
  46265. // may happen again in live streams where the keys change, and the manifest info
  46266. // reflects the update.
  46267. //
  46268. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  46269. // already requested keys for, we don't have to worry about this generating extraneous
  46270. // requests.
  46271. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  46272. this.createKeySessions_();
  46273. }
  46274. /**
  46275. * If necessary and EME is available, sets up EME options and waits for key session
  46276. * creation.
  46277. *
  46278. * This function also updates the source updater so taht it can be used, as for some
  46279. * browsers, EME must be configured before content is appended (if appending unencrypted
  46280. * content before encrypted content).
  46281. */
  46282. ;
  46283. _proto.setupEme_ = function setupEme_() {
  46284. var _this5 = this;
  46285. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  46286. var didSetupEmeOptions = setupEmeOptions({
  46287. player: this.player_,
  46288. sourceKeySystems: this.source_.keySystems,
  46289. media: this.playlists.media(),
  46290. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  46291. });
  46292. this.player_.tech_.on('keystatuschange', function (e) {
  46293. if (e.status !== 'output-restricted') {
  46294. return;
  46295. }
  46296. var masterPlaylist = _this5.masterPlaylistController_.master();
  46297. if (!masterPlaylist || !masterPlaylist.playlists) {
  46298. return;
  46299. }
  46300. var excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  46301. masterPlaylist.playlists.forEach(function (playlist) {
  46302. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  46303. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  46304. playlist.excludeUntil = Infinity;
  46305. excludedHDPlaylists.push(playlist);
  46306. }
  46307. }
  46308. });
  46309. if (excludedHDPlaylists.length) {
  46310. var _videojs$log;
  46311. (_videojs$log = videojs.log).warn.apply(_videojs$log, ['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.'].concat(excludedHDPlaylists)); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  46312. _this5.masterPlaylistController_.fastQualityChange_();
  46313. }
  46314. });
  46315. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  46316. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  46317. // promises.
  46318. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  46319. // If EME options were not set up, we've done all we could to initialize EME.
  46320. this.masterPlaylistController_.sourceUpdater_.initializedEme();
  46321. return;
  46322. }
  46323. this.createKeySessions_();
  46324. }
  46325. /**
  46326. * Initializes the quality levels and sets listeners to update them.
  46327. *
  46328. * @method setupQualityLevels_
  46329. * @private
  46330. */
  46331. ;
  46332. _proto.setupQualityLevels_ = function setupQualityLevels_() {
  46333. var _this6 = this;
  46334. var player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  46335. // or qualityLevels_ listeners have already been setup, do nothing.
  46336. if (!player || !player.qualityLevels || this.qualityLevels_) {
  46337. return;
  46338. }
  46339. this.qualityLevels_ = player.qualityLevels();
  46340. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  46341. handleVhsLoadedMetadata(_this6.qualityLevels_, _this6);
  46342. });
  46343. this.playlists.on('mediachange', function () {
  46344. handleVhsMediaChange(_this6.qualityLevels_, _this6.playlists);
  46345. });
  46346. }
  46347. /**
  46348. * return the version
  46349. */
  46350. ;
  46351. VhsHandler.version = function version$5() {
  46352. return {
  46353. '@videojs/http-streaming': version$4,
  46354. 'mux.js': version$3,
  46355. 'mpd-parser': version$2,
  46356. 'm3u8-parser': version$1,
  46357. 'aes-decrypter': version
  46358. };
  46359. }
  46360. /**
  46361. * return the version
  46362. */
  46363. ;
  46364. _proto.version = function version() {
  46365. return this.constructor.version();
  46366. };
  46367. _proto.canChangeType = function canChangeType() {
  46368. return SourceUpdater.canChangeType();
  46369. }
  46370. /**
  46371. * Begin playing the video.
  46372. */
  46373. ;
  46374. _proto.play = function play() {
  46375. this.masterPlaylistController_.play();
  46376. }
  46377. /**
  46378. * a wrapper around the function in MasterPlaylistController
  46379. */
  46380. ;
  46381. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  46382. this.masterPlaylistController_.setCurrentTime(currentTime);
  46383. }
  46384. /**
  46385. * a wrapper around the function in MasterPlaylistController
  46386. */
  46387. ;
  46388. _proto.duration = function duration() {
  46389. return this.masterPlaylistController_.duration();
  46390. }
  46391. /**
  46392. * a wrapper around the function in MasterPlaylistController
  46393. */
  46394. ;
  46395. _proto.seekable = function seekable() {
  46396. return this.masterPlaylistController_.seekable();
  46397. }
  46398. /**
  46399. * Abort all outstanding work and cleanup.
  46400. */
  46401. ;
  46402. _proto.dispose = function dispose() {
  46403. if (this.playbackWatcher_) {
  46404. this.playbackWatcher_.dispose();
  46405. }
  46406. if (this.masterPlaylistController_) {
  46407. this.masterPlaylistController_.dispose();
  46408. }
  46409. if (this.qualityLevels_) {
  46410. this.qualityLevels_.dispose();
  46411. }
  46412. if (this.player_) {
  46413. delete this.player_.vhs;
  46414. delete this.player_.dash;
  46415. delete this.player_.hls;
  46416. }
  46417. if (this.tech_ && this.tech_.vhs) {
  46418. delete this.tech_.vhs;
  46419. } // don't check this.tech_.hls as it will log a deprecated warning
  46420. if (this.tech_) {
  46421. delete this.tech_.hls;
  46422. }
  46423. if (this.mediaSourceUrl_ && window__default['default'].URL.revokeObjectURL) {
  46424. window__default['default'].URL.revokeObjectURL(this.mediaSourceUrl_);
  46425. this.mediaSourceUrl_ = null;
  46426. }
  46427. if (this.tech_) {
  46428. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  46429. }
  46430. _Component.prototype.dispose.call(this);
  46431. };
  46432. _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
  46433. return getProgramTime({
  46434. playlist: this.masterPlaylistController_.media(),
  46435. time: time,
  46436. callback: callback
  46437. });
  46438. } // the player must be playing before calling this
  46439. ;
  46440. _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
  46441. if (pauseAfterSeek === void 0) {
  46442. pauseAfterSeek = true;
  46443. }
  46444. if (retryCount === void 0) {
  46445. retryCount = 2;
  46446. }
  46447. return seekToProgramTime({
  46448. programTime: programTime,
  46449. playlist: this.masterPlaylistController_.media(),
  46450. retryCount: retryCount,
  46451. pauseAfterSeek: pauseAfterSeek,
  46452. seekTo: this.options_.seekTo,
  46453. tech: this.options_.tech,
  46454. callback: callback
  46455. });
  46456. };
  46457. return VhsHandler;
  46458. }(Component);
  46459. /**
  46460. * The Source Handler object, which informs video.js what additional
  46461. * MIME types are supported and sets up playback. It is registered
  46462. * automatically to the appropriate tech based on the capabilities of
  46463. * the browser it is running in. It is not necessary to use or modify
  46464. * this object in normal usage.
  46465. */
  46466. var VhsSourceHandler = {
  46467. name: 'videojs-http-streaming',
  46468. VERSION: version$4,
  46469. canHandleSource: function canHandleSource(srcObj, options) {
  46470. if (options === void 0) {
  46471. options = {};
  46472. }
  46473. var localOptions = videojs.mergeOptions(videojs.options, options);
  46474. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  46475. },
  46476. handleSource: function handleSource(source, tech, options) {
  46477. if (options === void 0) {
  46478. options = {};
  46479. }
  46480. var localOptions = videojs.mergeOptions(videojs.options, options);
  46481. tech.vhs = new VhsHandler(source, tech, localOptions);
  46482. if (!videojs.hasOwnProperty('hls')) {
  46483. Object.defineProperty(tech, 'hls', {
  46484. get: function get() {
  46485. videojs.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
  46486. return tech.vhs;
  46487. },
  46488. configurable: true
  46489. });
  46490. }
  46491. tech.vhs.xhr = xhrFactory();
  46492. tech.vhs.src(source.src, source.type);
  46493. return tech.vhs;
  46494. },
  46495. canPlayType: function canPlayType(type, options) {
  46496. var simpleType = mediaTypes_js.simpleTypeFromSourceType(type);
  46497. if (!simpleType) {
  46498. return '';
  46499. }
  46500. var overrideNative = VhsSourceHandler.getOverrideNative(options);
  46501. var supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  46502. var canUseMsePlayback = !supportsTypeNatively || overrideNative;
  46503. return canUseMsePlayback ? 'maybe' : '';
  46504. },
  46505. getOverrideNative: function getOverrideNative(options) {
  46506. if (options === void 0) {
  46507. options = {};
  46508. }
  46509. var _options = options,
  46510. _options$vhs = _options.vhs,
  46511. vhs = _options$vhs === void 0 ? {} : _options$vhs,
  46512. _options$hls = _options.hls,
  46513. hls = _options$hls === void 0 ? {} : _options$hls;
  46514. var defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  46515. var _vhs$overrideNative = vhs.overrideNative,
  46516. overrideNative = _vhs$overrideNative === void 0 ? defaultOverrideNative : _vhs$overrideNative;
  46517. var _hls$overrideNative = hls.overrideNative,
  46518. legacyOverrideNative = _hls$overrideNative === void 0 ? false : _hls$overrideNative;
  46519. return legacyOverrideNative || overrideNative;
  46520. }
  46521. };
  46522. /**
  46523. * Check to see if the native MediaSource object exists and supports
  46524. * an MP4 container with both H.264 video and AAC-LC audio.
  46525. *
  46526. * @return {boolean} if native media sources are supported
  46527. */
  46528. var supportsNativeMediaSources = function supportsNativeMediaSources() {
  46529. return codecs_js.browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  46530. }; // register source handlers with the appropriate techs
  46531. if (supportsNativeMediaSources()) {
  46532. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  46533. }
  46534. videojs.VhsHandler = VhsHandler;
  46535. Object.defineProperty(videojs, 'HlsHandler', {
  46536. get: function get() {
  46537. videojs.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
  46538. return VhsHandler;
  46539. },
  46540. configurable: true
  46541. });
  46542. videojs.VhsSourceHandler = VhsSourceHandler;
  46543. Object.defineProperty(videojs, 'HlsSourceHandler', {
  46544. get: function get() {
  46545. videojs.log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
  46546. return VhsSourceHandler;
  46547. },
  46548. configurable: true
  46549. });
  46550. videojs.Vhs = Vhs;
  46551. Object.defineProperty(videojs, 'Hls', {
  46552. get: function get() {
  46553. videojs.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
  46554. return Vhs;
  46555. },
  46556. configurable: true
  46557. });
  46558. if (!videojs.use) {
  46559. videojs.registerComponent('Hls', Vhs);
  46560. videojs.registerComponent('Vhs', Vhs);
  46561. }
  46562. videojs.options.vhs = videojs.options.vhs || {};
  46563. videojs.options.hls = videojs.options.hls || {};
  46564. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  46565. var registerPlugin = videojs.registerPlugin || videojs.plugin;
  46566. registerPlugin('reloadSourceOnError', reloadSourceOnError);
  46567. }
  46568. module.exports = videojs;